-
[CODECADEMY] 코드카데미 : JavaScript 조건문 (CONDITIONAL STATEMENTS : if else / if 비교 연산자 /논리 연산자/참과 거짓 (Truthy and Falsy) / 단축평가 / 삼항연산자 / Else If / switch )Java Script 2020. 6. 12. 11:15
1. if 조건문
if 안의 조건문이
true로 평가되면 중괄호 안의 코드 {}가 실행 됨.
false로 평가되면 실행되지 않음.let sale = true; if (sale) { console.log('Time to buy!'); } // print >> Time to buy! let sale = false; if (sale) { console.log('Time to buy!'); } // nothing printed
1-1. if else
if 안의 조건문이
true로 평가되면 중괄호 안의 코드 {}가 실행 됨.
false로 평가되면 else의 중괄호 안의 코드 {}가 실행 됨.let sale = true; sale = false; if(sale) { console.log('Time to buy!'); } else { console.log('Time to wait for a sale.'); }
2. if 비교 연산자 (Comparison Operators)
작다 < 5<10 // true 크다 > 5<10 // false 작거나 같다 <= 5<=10 // true 크거나 같다 >= 5>=10 // false 같다 (변수타입 상관 없음) == 5==5 // true
'5'==5 // true다르다 != 5!=5 // false
'5'==5 // false엄격 일치 (변수타입 엄격 일치) === 5==5 // true
'5'==5 // false엄격 불일치 !== 5!==5 // false
'5'==5 // truelet hungerLevel=7; if(hungerLevel>7){ console.log('Time to eat!'); } else { console.log('We can eat later!'); } // print 'We can eat later!' //
3. 논리 연산자 (Logical Operators)
AND(&&), OR(||), NOT(!)
3-1. and (&&)
x && y일 경우 x,y 모두가 true여야 true값이 추출 됨.
출처 : https://justmakeyourself.tistory.com/entry/javascript-and-or-not 예시 : mood 를 x / tirednessLevel을 y라고 했을때 x 는 true이나 y가 false로 false 값이 추출 됨.
let mood = 'sleepy'; let tirednessLevel = 6; if(mood==='sleepy' && tirednessLevel>8 ){ console.log('time to sleep'); } else { console.log('not bed time yet') ; } // print >> 'not bed time yet'
3-2. or (||)
x && y일 경우 x,y 모두가 false 여야 false 값이 추출 됨.
https://justmakeyourself.tistory.com/entry/javascript-and-or-not 예시 : mood 를 x / tirednessLevel을 y라고 했을때 x 는 true이나 y가 false 여도 true 값이 추출 됨.
let mood = 'sleepy'; let tirednessLevel = 6; if(mood==='sleepy' || tirednessLevel>8 ){ console.log('time to sleep'); } else { console.log('not bed time yet') ; } // print >> 'time to sleep'
3-3. not (!)
false일 경우엔 true로, true일 경우 false로 바꿈
https://justmakeyourself.tistory.com/entry/javascript-and-or-not
4. 참과 거짓 (Truthy and Falsy)
4-1. False로 인식되는 값
- undefined
- null
- 0
- NaN
- false
- ''
- ""
예시 ) numberOfApples 의 value 가 0 일 때, false 로 인식하여 No apples left! 의 값이 나옴
let numberOfApples = 0; if (numberOfApples){ console.log('Let us eat apples!'); } else { console.log('No apples left!'); } // Prints 'No apples left!'
4-2. 단축평가 (short-circuit evaluation)
4-1. 참과 거짓 / 3. 논리연산자를 결함하여 응용
예시 :
tool의 value가 false로 인식되는 값이라면
false || 문자열 일 경우 문자열이 추출 됨
let tool = '' let writingUtensil = tool||'pen' console.log(`The ${writingUtensil} is mightier than the sword.`); // print >> The pen is mightier than the sword.
let tool = 'marker' let writingUtensil = tool||'pen' console.log(`The ${writingUtensil} is mightier than the sword.`); // print >> The marker is mightier than the sword.
5. 삼항연산자 (Ternary Operator)
if...else 구문을 간소화 하게 작성하기
1. 조건 isNightTime은 ? 앞에 제공됩니다 .
2. 두 표현식은 뒤에 ?와 콜론으로 구분됩니다 :.
3. 조건이로 평가 true되면 첫 번째 표현식이 실행됩니다.
4. 조건이로 평가 false되면 두 번째 표현식이 실행됩니다.let isCorrect = true; isCorrect ? console.log('Correct!') : console.log('Incorrect!') // print >> Correct!
여기서 주의!
' ' 안에 don't 과 같이 또 다른 '이 들어갈 경우 '앞에 \을 추가하여 구분한다.
let favoritePhrase = 'Love That!'; favoritePhrase==='Love That!' ? console.log('I love that!'): console.log('I don\'t love that!'); //print >> Love That!
6. Else If 구문
else if 구문은 더 복잡한 조건을 만들기 위해 원하는 만큼 많은 문장을 추가 할 수 있다.
6-1. Else If 구문 특징
■ else if문은 항상 if문장 뒤에 오고, else문 전에 온다.
if{} - else if{} - else{};
■ if/ else if/ else진술은 위에서 아래로 판독되고,
상기에 있는 조건문이 true가 되면 아래의 조건문은 실행되지 않음
let season = 'summer'; if (season === 'spring') { console.log('It\'s spring! The trees are budding!'); } else if (season === 'winter') { console.log('It\'s winter! Everything is covered in snow.'); } else if (season === 'fall') { console.log('It\'s fall! Leaves are falling!'); } else if (season === 'summer') { console.log('It\'s sunny and warm because it\'s summer!');} else { console.log('Invalid season.'); }; // print >> It's sunny and warm because it's summer!
7. switch keyword
코딩은 반복을 싫어함..
let groceryItem = 'papaya'; if (groceryItem === 'tomato') { console.log('Tomatoes are $0.49'); } else if (groceryItem === 'papaya'){ console.log('Papayas are $1.29'); } else { console.log('Invalid item'); }
만약 우리가 체크해야 하는 값이 100개가 넘는다면..
일일이 groceryItem=== 넣기가 귀찮고 반복됨
반복을 줄이고자 switch 구문이 나옴
7-1. switch 문법
https://dasima.xyz/javascript-switch/ let athleteFinalPosition = 'first place'; switch(athleteFinalPosition) { case 'first place' : console.log('You get the gold medal!'); break; case 'second place' : console.log('You get the silver medal!'); break; case 'third place' : console.log('You get the bronze medal!'); break; default : console.log('No medal awarded.'); break } // print >> You get the gold medal!
'Java Script' 카테고리의 다른 글