김숭늉 마음대로

자바스크립트 ===, ==, 논리연산자(logical operators) 본문

IT/JavaScript

자바스크립트 ===, ==, 논리연산자(logical operators)

김숭늉이 2023. 9. 6. 14:17
728x90

 

 

 

 

 

안녕하세요.

자바스크립트 = = = 와 = = 연산자의 차이와 자바스크립트 논리연산자 (logical operators)에 대해 알아보겠습니다.

 

 

 

 


자바스크립트 = = = 와 = = 연산자의 차이?

 

자바스크립트의 === 와 == 연산자의 차지는 ===은  strict해서 값과 두 변수의 유형 모두 체크하지만 ==의 경우는 값만 비교하여 체크한다. 실제 개발을 하면서는 항상 ===의 등호를 이용하는것이 좋다 ! 버그를 피하기 위해서는!

 

 

# 간단한 예제

const age = 18;

if (age === 18) console.log("You just became an adult (strict) :)"); // 조건이 하나밖에 없으면 {} 안써도 됨! 한줄이 작성해도 무방함!
if (age == 18) console.log("You just became an adult (loose) :)"); // 조건이 하나밖에 없으면 {} 안써도 됨! 한줄이 작성해도 무방함!

* 위의 경우 모두 true의 값을 반환한다

 


const favourite = Number(prompt("What's your favourite number?")); // prompt에 작성된 값을 저장함
console.log(favourite); // prompt에 입력한 텍스트가 나옴
console.log(typeof favourite); // string

if (favourite == 23) {
// '23' == 23
console.log("cool 23 is amazing number!"); // 정상 출력됨 왜냐하면 ==을 사용했기 때문에
}

* 위의 경우 문자열인 '23'과 23은 ==로 비교하는경우 true의 값을 반환한다.

 


if (favourite === 23) {
// '23' === 23
console.log("cool 23 is amazing number!"); // 출력되지 않음 왜냐하면 === 을 사용했기 때문에
}

* 위의 경우 문자열인 '23'과 23은 ===로 비교하는경우 false의 값을 반환한다. (type이 맞지 않기 때문에)

 


자바스크립트 논리연산자 (logical operators)

자바스크립트의 논리 연산자는 ||(OR), &&(AND), !(NOT)가 있습니다. 

 

 

    ||(OR)       A와 B 둘중 하나만 참이거나 둘다 참인경우 true

    &&(AND) A와 B 둘다 모두 참인 경우에만 true

    !(NOT)      true면 false로 변경, false면 true로 변경 합니다.

 

const hasDriversLicense = true; // A
const hasGoodVision = false; // B

console.log(hasDriversLicense && hasGoodVision); // false
console.log(hasDriversLicense || hasGoodVision); // true
console.log(!hasDriversLicense); // false

const shouldDrive = hasDriversLicense && hasGoodVision; // true && false = false

 

const isTired = true; // C
console.log(hasDriversLicense || hasGoodVision || isTired); // true or false or true === true

if (hasDriversLicense && hasGoodVision && !isTired) {
// false
console.log("sarah is able to drive");
} else {
console.log("someone else should drive the car"); // 콘솔창 출력됨
}

 

const scoreDolphins = (96 + 108 + 89) / 3;
const scoreKoalas = (88 + 91 + 110) / 3;
console.log(scoreDolphins, scoreKoalas);

if (scoreDolphins > scoreKoalas) {
console.log("Dolphins win the trophy");
} else if (scoreKoalas > scoreDolphins) {
console.log("Koalas win the trophy");
} else {
console.log("Both win the trophy");
}

 

 

 

그럼 오늘도 좋은하루 보내세요.🤍

 

 

 

 

728x90
반응형