console.log('my' + 'cat'); // mycat console.log('1' + 2); // 12 console.log(`${1 + 2}`); // 3 console.log(`${'just test'}`); // just testconsole.log("ellie's book"); // \n: 줄바꿈, \t: 탭키 const test1 = 2; const test2 = 3; console.log(`${test1}+${test2} = ${test1 + test2}`); // 2 + 3 = 5
+를 사용해서 string끼리 합해 사용할 수 있다.
따옴표가 아닌, 백틱(``)을 사용하면. + 없이 문자열을 합할 수 있다. (템플릿 리터럴)
두 번째 예제처럼, 백틱(``) 안의 ${}를 통해 문자열과 변수를 혼합하여 사용할 수 있다.
console.log(6 + 2); // 8 console.log(6 - 2); // 4 console.log(6 / 2); // 3 console.log(6 * 2); // 12 console.log(6 % 2); // 0(나눈 후 나머지 값을 나타냄) console.log(6 ** 2); // 36 (6의 2승)
pre(++변수), post (변수++)로 나뉜다.++변수, --변수)let counter = 2; const preIncrement = ++counter; console.log(`${preIncrement}, ${counter}`); // preIncrement: 3, counter: 3
++counter는 counter = counter + 1과 같다.
즉 1이 증가되어 3이된 counter값과, 그 값이 할당된 preIncrement이 되므로 preIncrement: 3, counter: 3의 결과값이 나온다.
decrement의 경우도 똑같다. (--counter 는 counter = counter - 1과 같다.)
변수++, 변수--)let counter = 2; const postIncrement = counter++; console.log(`${postIncrement}, ${counter}`); // preIncrement: 2, counter: 3
post 는 pre와 증감을 똑같이 하지만, 그 순서에 차이가 있다.
pre의 경우 (++가 앞에 붙는 경우) counter값이 먼저 증가된 후 변수에 증가된 값을 할당한다.
post의 경우 (++가 뒤에 붙는 경우) counter는 먼저 postIncrement에 기존 2인 값을 할당한 후, 1이 증가되어 자기 자신은 3이 된다.
| pre(++변수) | post(변수++) | |
|---|---|---|
| 순서1 | counter = counter + 1(우선 실행) | postIncrement = count;(우선 할당) |
| 순서2 | preincrement = counter; (나중 할당) | counter = counter + 1;(나중 실행) |
let x = 3; //(변수를 통해 값을 할당 가능) let y = 4; x += y; // x = x + y; console.log(x); // x = 7 x -= y; // x = x - y; console.log(x); // x = 3 x *= y; // x = x * y; console.log(x); // x = 12 x /= y; // x = x / y; console.log(x); // x = 3
변수에 특정 값을 할당할 수 있다.
x = x + y 처럼 연산에서 특정 변수가 반복으로 사용될 경우 x+=y로 표기하여 사용할 수 있다.
console.log(10 < 6); //false console.log(10 <= 6); //flase console.log(10 > 6); //true console.log(10 >= 6); //true
값이 같은지, 다른지, 큰지, 작은지를 구분할때 사용한다.
true/false값으로 반환한다. (Boolean)
const stringFive = '5'; const numberFive = 5; console.log(`${typeof stringFive}`); // string console.log(`${typeof numberFive}`); // number console.log(stringFive == numberFive); //true(data type이 서로 다름에도 불구하고 true 값이 반환됨) console.log(stringFive != numberFive); //false(위와 같음)
동등 연산자는 좌항과 우항을 비교하여 같다면 true, 다르다면 false를 반환한다.
자바스크립트의 동등 연산자는 위처럼 data type이 다르더라도, 정보가 같다고 판단하게 되면 마음대로 type을 바꿔 처리하게 된다. (데이터가 정확하게 일치하지 않아도 정보가 비슷하면 마음대로함)
이러한 이유로 인해 ==, !=와 같은 동등 연산자는 사용하지 않는 것이 좋다.
const stringFive = '5'; //string const numberFive = 5; // number console.log(stringFive === numberFive); //false (type이 다름) console.log(stringFive !== numberFive); //true
동등 연산자와 다르게 정보 및 data type이 완벽하게 일치할 시, true 값을 변환한다. (마음대로 data type을 변경하지 않는다.)
자바스크립트에서는 웬만하면 이러한 일치 연산자를 사용하는 것을 권장한다.
const value1 = true; const value2 = true; const value3 = false; console.log(value1 || value2 || value3); // true console.log(value1 && value2 && value3); // false
||: or를 뜻한다. 위 예제의 경우 value 값 중, 한가지 값이라도 true가 있다면, true를 반환한다.&&: and를 뜻한다. 모든 값이 true가 아니라면, false 값을 반환한다.const value = true; console.log(value); // true console.log(!value); // false
!: not을 뜻한다. 기존 값의 반대값으로 만들어준다.const man = 'Yongmin'; if (man === 'Yongmin') { console.log('hi, Yongmin!'); // "hi, yongmin!" 출력 } else if (man === 'coder') { console.log('you are the best coder in the world'); } else { console.log('who are you?'); }
() 안의 조건에 맞춰 함수를 실행한다.else if로 넘어가 새로운 조건을 참고하여 실행하게 된다. const name = 'Yongmin'; if(name === 'Yongmin'){ console.log(`hello ${name}`) // "hello Yongmin" }⬇const name = 'Yongmin'; name === 'Yongmin' ? `hello ${name}` :'no' // "hello Yongmin"
if 조건문을 간단히 쓸 수 있는 방법이다.(조건문) ? 조건과 일치할 경우 : 일치하지 않을 경우 형태로 작성한다.const site = function (browser) { switch (browser) // 소괄호 안 조건 { case 'ie': console.log('go away!'); break; case 'Chrome': case 'Firefox': //출력값이 같을 때는 묶어서 표현해도 상관없음 console.log('love you'); break; default: console.log('same all!'); break; } }; site('Firefox'); // love you 출력
if else 조건문 대신 사용할 수 있다.case 조건과 일치하게 되면 콜론 뒤 코드를 실행하고 (예제에서는 console.log())그 즉시 함수를 멈춘다. (break) let i = 3; while (i > 0) { console.log(i); i--; } // 3, 2, 1
while 은 () 안의 조건이 만족하지 않을 때까지 {}안의 구문이 계속해서 반복한다.
예제에서 확인할 수 있듯, i 값은 console.log(i)를 통해 출력되며 1씩 감소하고 있다. 이러한 루프는 i 값이 0이 되기 전까지 계속 반복되며 0이 될 경우 ()의 조건과 맞지 않기 때문에 루프는 중단된다.
for (let i = 0; i < 10; i++) { console.log(i); } // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
for(begin; condition; step){실행구문}과 같이 작성한다.
begin: 시작 처음 한번만 호출 (ex) let i = 0;)
condition: 조건이 맞는 지 확인 (ex) i < 10;)
step: {실행}블록이 실행된 후 증감이 실행된다.
-> 결론적으로 조건을 벗어나기 전까지 condition, step 부분만 무한 반복된다.