- 변수 이름은 숫자로 시작 X
- 대소문자 구분
- 변수를 만드는 키워드
- 값을 할당하기 전부터 선언할 수 있음
- var는 더이상 사용을 권장하지 않음!
그 이유는 var hoisting으로 block scope을 무시하면서 오류가 나타날 수 있기 때문hoisting: 어디에 선언했냐에 상관없이 항상 제일 위로 선언을 끌어올려주는 것
var myName = 'Arya';
console.log(myName);
Output: Arya
- 변수에 다른 값을 다시 할당 할 수 있음
- 값을 할당하지 않고도 선언할 수 있음 (undefined 값으로 자동 초기화됨)
- ES6에서 추가되었음
let meal = 'Enchiladas';
console.log(meal); // Output: Enchiladas
meal = 'Burrito';
console.log(meal); // Output: Burrito
let price;
console.log(price); // Output: undefined
price = 350;
console.log(price); // Output: 350
- let과 동일한 구조를 따름
- 상수이기 때문에 값을 재할당할 수 없음 (재할당 시 TypeError 발생)
- declare 시 값을 할당해야 함. 값 없이 선언하면 SyntaxError 발생
- 변수를 재할당해야한다면 let을, 그렇지 않다면 const 사용
const myName = 'Gilberto';
console.log(myName); // Output: Gilberto
* security, thread safey, reduce human mistakes 의 이점이 있음으로 사용을 권장!
- 변수와 수학 연산자를 사용하여 새 값을 계산하고 변수에 할당하는 법
- +=, -=, *=, /= 를 사용하여 코드 단축 가능
let w = 4;
w = w + 1;
console.log(w); // Output: 5
let w = 4;
w += 1;
console.log(w); // Output: 5
- (++) : 1씩 증가 / (--) 연산자 : 1씩 감소
let a = 10;
a++;
console.log(a); // Output: 11
let b = 20;
b--;
console.log(b); // Output: 19
let num = 2;
const preincrement = ++num;
++num; 처럼 변수 앞에 ++가 있으면 num에 1을 더해서 3으로 나타남
let num = 2;
postincrement = num;
num = num + 1;
일 때, postinrecment는 2, num은 3이 할당됨
- +를 이용하여 변수와 문자열 연결
let myPet = 'armadillo';
console.log('I own a pet ' + myPet + '.');
// Output: 'I own a pet armadillo.'
- template literals를 통해 변수를 문자열에 삽입하거나 보간할 수 있음
- 코드의 가독성을 높일 수 있음.
const myPet = 'armadillo';
console.log(`I own a pet ${myPet}.`);
// Output: I own a pet armadillo.
template literals 는 ` ` 를 통해 사용됨
템플릿 리터럴 내 값 표시는 ${ } 로 표시
- 변수 값의 데이터 유형 확인 시 사용
const unknown1 = 'foo';
console.log(typeof unknown1); // Output: string
const unknown2 = 10;
console.log(typeof unknown2); // Output: number
const unknown3 = true;
console.log(typeof unknown3); // Output: boolean
- 변수에 값을 할당하여 실행
let myVariable = 'I Exist!';
if (myVariable) {
console.log(myVariable)
} else {
console.log('The variable does not exist.')
}
falsy 값
let numberOfApples = 0;
if (numberOfApples){
console.log('Let us eat apples!');
} else {
console.log('No apples left!');
}
// Prints 'No apples left!'
<만들어보기!!>
만약 웹사이트 방문자가 닉네임이 있거나/ 없을 때 명칭을 지정한다면
if문을 사용해서 만들어보고, 논리연산자와 결합해서 만들어보기
if문 사용
let visitorname;
if (username) {
visitorname = username;
} else {
visitorname = 'stranger';
}
논리 연산자와 결합
let visitorname = username || 'stranger';
or연산자는 왼쪽 조건을 먼저 확인한 수, 변수값이 진실이면 username을 표시하고 거짓이면 stranger 값이 할당됨
- if...else 구문을 더 단순하게 표현
- isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!'); -
- 조건명 isNightTime ? 을 넣고 두 표현 사이에 : 를 넣어줌
- 참(True)이면 앞의 문장이, 거짓(False)이면 뒤의 문장이 실행
let isNightTime = true;
if (isNightTime) {
console.log('Turn on the lights!');
} else {
console.log('Turn off the lights!');
}
★ 삼항연산자로 표현 시
isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');
예시)
favoritePhrase === 'Love That!' ? console.log('I love that!') : console.log("I don't love that!");