console.log(Boolean('hello')) // true
console.log(Boolean(' ')); // true
console.log(Boolean([1, 2, 3])); // true
console.log(Boolean([])) // true
console.log(Boolean({})); // true
console.log(Boolean({name: "eunsu", age: 25})); // true
console.log(Boolean(1)); // true
console.log(Boolean(-1)); // true
console.log(Boolean(0)); // false
console.log(Boolean('')); // false
console.log(Boolean(undefined)) // false
console.log(Boolean(null)) // false
console.log(Boolean(NaN)) // false
부정의 부정은 긍정이기 때문에, 실제로 조건문안의 조건식에서 !!을 쓰나 쓰지 않으나
같은 결과값을 낸다.
if("hello"){
console.log("hello") // "hello" 출력
}
if(!!"hello"){
console.log("hello") // "hello" 출력
}
그렇다면 !!는 왜 쓰는 것일까
다른 타입의 데이터를 Boolean 타입으로 명시적으로 형변환 함을 밝히기 위해 쓴다.
console.log(!!'hello') // true
console.log(!!' '); // true
console.log(!![1, 2, 3]); // true
console.log(!![]) // true
console.log(!!{}); // true
console.log(!!{name: "eunsu", age: 25}); // true
console.log(!!1); // true
console.log(!!(-1)); // true
console.log(!!0); // false
console.log(!!''); // false
console.log(!!undefined) // false
console.log(!!null) // false
console.log(!!NaN) // false
OR 연산자의 경우에는 둘중에 하나만 true 여도 true를 반환한다.
console.log(false || false); // false
console.log(false || true); // true
console.log(true || false); // true, 앞의 값이 true이므로 뒤의 식은 보지 않아도 true
console.log(true || true); // true
console.log("hello" || "") // "hello", 앞의 값이 true이면 앞의 값을 출력
console.log("" || "hello") // "hello", 앞의 값이 false이면 뒤의 값을 출력
console.log(undefined || null) // null, 앞의 값이 false이면 뒤의 값을 출력
console.log(0 || undefined) // undefined, 앞의 값이 false이면 뒤의 값을 출력
AND 연산자의 경우에는 둘 모두 true가 되어야 true를 반환한다.
console.log(false && false); // false, 앞의 값이 false이므로 뒤의 식은 보지 않아도 false
console.log(false && true); // false, 앞의 값이 false이므로 뒤의 식은 보지 않아도 false
console.log(true && false); // false
console.log(true && true); // true
console.log("hello" && "") // "", 앞의 값이 true이면 뒤의 값 출력
console.log("" && "hello") // "", 앞의 값이 false이면 뒤의 값 볼 필요 없이 앞의 값 출력
console.log(undefined || null) // undefined, 앞의 값이 false이면 뒤의 값 볼 필요 없이 앞의 값 출력
nullish: null
, undefined
falsy: 0
, ""
, undefined
, null
, NaN
, etc...
let height;
console.log(height ?? 100) // 100, 앞의 값이 null이면 뒤의 값 출력
console.log(height && 100) // undefined, 앞의 값이 false이면 뒤의 값 볼 필요 없이 앞의 값 출력
console.log(height || 100) // 100, 앞의 값이 false이면 뒤의 값을 출력
let height2=""
console.log(height2 ?? 100); // "", 앞의 값이 null이 아니면 앞의 값 출력
console.log(height2 && 100) // "", 앞의 값이 false이면 뒤의 값 볼 필요 없이 앞의 값 출력
console.log(height2 || 100); // 100, 앞의 값이 false이면 뒤의 값 출력