JavaScript

Variables

WebDevLee 2021. 10. 8. 16:51

이 글은 자바스크립트의 Variables(변수)에 관한 개념 및 문법을 정리하기 위해 작성하였습니다.




< Variables >

You can think of variables as little containers for information that live in a computer's memory.

Provide a way of labeling data with descriptive name.

 


< Create a Variable >

let myName = LSH    //    myName variable is initialized with LSH
var myName = LSH
const myName = LSH

 

1. variable's name(camel casing) : myName

2. value : LSH

3. assignment operator(=)

 

  • let(var) : can be reassigned,
                   can declare without a value  =>  in such a case, automatically initialized with undefined
  • const : can't be reassigned,
                should have a value.

 

< Rules for naming variables >
1. cannot start with number
2. cannot be same as keywords
3. myname !== myName

 


< Mathematical Assignment Operators >

  • x += 1   //   x = x + 1
  • x -= 1   //    x = x - 1
  • x *= 1   //   x = x * 1
  • x /= 1   //   x = x / 1
  • increment operator(++)   //   +1
  • decrement operator(--)   //   -1

 


< String Concatenation with Variables >

ex)

let myPet = 'lion';
console.log('I own a pet ' + myPet + '.');
// I own a pet lion.

 


< Template literals >

For Redability of code

 

  •  `__________${ string }__________`

 

ex)

let myPet = 'lion';
console.log(`I own a pet ${myPet}.`);
// I own a pet lion.

 


< typeof operator >

To check the data type

 

ex)

let unknown1 = 'foo';
console.log(typeof unknown1);   //   string

let unknown2 = 10;
console.log(typeof unknown2);   //   number

let unknown3 = true;
console.log(typeof unknown3);   //   boolean