Javascript

[JS] 3. 연산자 (Operators), 조건문과 반복문

개발자 뭄뭄 2022. 11. 7. 23:40
반응형

1. 연산자 (Operators)

1. String concatenation

console.log('my' + ' cat') // my cat
console.log('1' + 2) // 12

2. Assignment operators

let c = 0
c += 10
console.log(c)
  • python과 마찬가지로, +=, -= 등을 지원한다. 연산자는 모두 같으니 기억하기 쉽다!

3. Increment, Decrement

let counter = 2;
const preIncrement = ++counter; // counter : 3, preincrement: 3
const postIncrement = counter++; // counter : 4, postincrement :3

4. Comparison operators

3 > 2 // true
'A' < 'B' // true
'Z' < 'a' // true
'가' < '나' // true
  • 알파벳 순서상 후순위가 더 크다.
  • 소문자 > 대문자 (유니코드 값으로 비교)

5. Logical operators

&& // and
|| // or
! // not
  • 단축평가를 지원한다.
    • ex) or 연산이 여러개 있을 경우, 앞이 True 면? ⇒ 뒤에 볼 것도 없지~ 바로 True!!

6. Equality

console.log('5' == 5) //true
console.log('5' === 5) //false
console.log(null==undefined); // true
console.log(null===undefined); //false
console.log(''== false); //true
  • 동등연산자 (==)
    • 비교할 때 암묵적 타입 변환을 통해 타입을 일치시킨 후 같은 값인지 비교
    • 두 피연산자가 모두 객체일 경우 메모리의 같은 객체를 바라보는지 판별
  • 일치연산자(===)
    • 엄격한 비교로, 암묵적 타입 변환이 발생하지 않는다.
    • 같은 객체를 가리키거나, 같은 타입이면서 같은 값인지 비교한다.

2. 조건문 (Conditional operators)


If statement
const name = 'mummum'
if (name==='mummum') {
console.log('hello mummum')
} else if (name === 'pumpum') {
cosole.log('hello pumpum')
} else {
console.log('wakaranai')
}
Ternary Operator (삼항연산자) 를 사용할 수도 있다.
const name = 'mummum'
console.log(name==='mummum'? 'yes':'no')
  • 조건식이 참이면 : 앞의 값이, 아닐 경우 뒤의 값이 반환된다.
Switch statement
const name = 'mummum'
switch(name){
case 'mummum' : {
console.log('hello mummum')
break
}
case 'pumpum' : {
console.log('hello pumpum')
break
}
default:{
console.log('wakaranai')
}
}
  • 조건이 많은 경우 switch 문을 통해서 가독성 향상을 기대할 수 있다.

3. 반복문(Loops)

While
  • 조건문이 참이기만 하면 문장을 계속해서 수행

for

for ( 시작, condition, step) {}

  • for에서는 최초 정의한 i를 재할당하면서 사용하기 때문에, const가 아닌, let을 사용해야 한다.

for … in
  • 객체(Object)의 속성을 순회할 때 사용한다
  • 배열도 순회가능하지만, 인덱스 순으로 순회한다는 보장이 없다.

for … of
  • 반복 가능한 객체를 순회할 때 사용한다
    • Array, Set, String …

Uploaded by N2T

반응형