[CODECADEMY] 코드카데미 : JavaScript 변수 (할당 연산자 / 증감연산자 / 템플릿 리터럴 /typeof operator )
변수=계속 변하는 값
예를 들어, 간장공장공장장은 장공장장이다
라는 문장이 있을 때, '장'이라는 글자가 정 또는 박 등등 계속 바뀌어야 한다면?
1. 수작업을 한다 → 오류 발생 가능성 높음.(만약 저 문장이 1000개라면? 수작업 불가능)
2. 변수를 이용한다.
name='장'
간+name+공+name+공+name++name+...
으로 장이 들어가는 자리에 +name+ 이 들어간다면
name=' ? ' 자리에 ? 만 바꾸어 주어도 언제든지 변경 가능
= 변수
변수의 종류
let / const / var
2. var 변수의 특징
2-1. 띄어쓰기 불가능
var myName = 'Arya';
my name으로 띄어쓰기가 불가능 하기 때문에
myName으로 새로 시작되는 단어를 대문자로 Capitalize한다
= camelCase
2-2. 숫자로 시작할 수 없음
var 12myName = 'Arya';
숫자로 시작할 수 없음
2-3. 대 소문자에 민감함
var myName = 'Arya';
와
var myname = 'Arya';
를 다르게 인식 함.
myName과 myname이 다른 문자인것이다..
2-4. 자바크립트가 쓰는 keywords를 사용할 수 없다.
var var='Arya';
안됩니다!!!!
자바스크립트가 쓰는 키워드는 break, case, catch 등 매우 많다
↓↓ 더 많은 keywords 보기 ↓↓
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords
Lexical grammar
This page describes JavaScript's lexical grammar. The source text of ECMAScript scripts gets scanned from left to right and is converted into a sequence of input elements which are tokens, control characters, line terminators, comments or white space. ECMA
developer.mozilla.org
3. let 변수의 특징
3-1. 값을 재할당 할 수 있다.
meal의 값을 변경 할 시, 최근에 입력된 meal의 값이 출력된다 = 값이 변경된다
let meal = 'Enchiladas';
console.log(meal); // Output: Enchiladas
meal = 'Burrito';
console.log(meal); // Output: Burrito
아래와 같이 let meal의 값을 두번 정의하는 경우 에러가 발생한다.
let meal = 'Enchiladas';
console.log(meal); // Output: Enchiladas
let meal = 'Burrito';
console.log(meal); // Error : meal has been declared
3-2. 값이 없으면 undefined 으로 정의
정의되지 않은 값에서 undefined가 자동으로 출력된다.
let price;
console.log(price); // Output: undefined
price = 350;
console.log(price); // Output: 350
4. const 변수의 특징
4-1. 값을 재할당 할 수 없다.
let 처럼 값을 재할당 할 수 없다.
새로운 값을 넣을 시, Type Error 발생함
const entree='Enchiladas';
console.log(entree);
entree='Tacos';// TypeError : Assignment to constant variable.
4-2. 값이 없으면 SyntaxError 발생
const entree;
console.log(entree);
// SyntaxError: Missing initializer in const declaration
let 변수
1. 할당 연산자 응용 ( Mathematical Assignment Operators)
let w = 4;
w = w + 1;
console.log(w); // Output: 5
w = w + 3;
console.log(w); // Output: 8
w 의 초기값(4)에 +1을 더하면, w의 값는 5가 된다.
또 다시 w에 3을 더하면 4+3=7이 아닌 5+3=인 8 이된다.
let levelUp = 10;
let powerLevel = 9001;
let multiplyMe = 32;
let quarterMe = 1152;
levelUp += 5;
powerLevel -= 100;
multiplyMe *= 11;
quarterMe/=4;
console.log('The value of levelUp:', levelUp);
//The value of levelUp: 15
console.log('The value of powerLevel:', powerLevel);
//The value of powerLevel: 8901
console.log('The value of multiplyMe:', multiplyMe);
//The value of multiplyMe: 352
console.log('The value of quarterMe:', quarterMe);
//The value of quarterMe: 288
2. 증감연산자 (Increment and Decrement Operator)
2-1. 증가 ++
a++
a(변수) 의 값을 1 증가시킨다
let a = 10;
a++;
console.log(a); // Output: 11
2-2. 감소 --
a--
a(변수) 의 값을 1 감소 시킨다
let b = 20;
b--;
console.log(b); // Output: 19
3. 템플릿 리터럴 (Template literals)
기존에 사용하던 방식이 아래와 같다면,
let myPet = 'armadillo';
console.log('I own a pet ' + myPet + '.');
// Output: 'I own a pet armadillo.'
-
템플릿 리터럴에서는 백틱(`)(grave accent) 으로 크게 문장을 묶고
변수가 들어가야 할 부분에 $와 중괄호{}를 사용하여 표현식을 표기하여 쉽게 작성
const myPet = 'armadillo';
console.log(`I own a pet ${myPet}.`);
// Output: I own a pet armadillo.
템플릿 리터럴 사용의 가장 큰 장점 중 하나는 코드의 가독성입니다.
템플릿 리터럴을 사용하면 새 문자열이 무엇인지 더 쉽게 알 수 있습니다.
또한 큰 따옴표 나 작은 따옴표를 이스케이프 처리하는 것에 대해 걱정할 필요가 없습니다.
↓↓설명 잘 되어있는 블로그↓↓
https://eblee-repo.tistory.com/38
[JavaScript] ES6 템플릿 리터럴에 대해 알아보자!!
[JavaScript] ES6 템플릿 리터럴에 대해 알아보자!! 안녕하세요. 이번 포스팅은 ES6의 템플릿 리터럴과 활용법에 대해 알아봅니다. Template literals 템플릿 리터럴 은 내장된 표현식을 허용하는 문자열 ��
eblee-repo.tistory.com
4. typeof operator
값의 형태를 알려주는 연산자.
값이 문자일 경우 string /
숫자일 경우 number /
true or false일 경우 boolean
let unknown1 = 'foo';
console.log(typeof unknown1); // Output: string
let unknown2 = 10;
console.log(typeof unknown2); // Output: number
let unknown3 = true;
console.log(typeof unknown3); // Output: boolean