https://bigfrontend.dev/quiz/Implicit-Conversion-1
What does the code snippet below output by console.log
?
console.log(Boolean('false'));
console.log(Boolean(false));
console.log('3' + 1);
console.log('3' - 1);
console.log('3' - ' 02 ');
console.log('3' * ' 02 ');
console.log(Number('1'));
console.log(Number('number'));
console.log(Number(null));
console.log(Number(false));
console.log(Boolean('false')); // true
console.log(Boolean(false)); // false
console.log('3' + 1); // "31"
console.log('3' - 1); // 2
console.log('3' - ' 02 '); // 1
console.log('3' * ' 02 '); // 6
console.log(Number('1')); // 1
console.log(Number('number')); // NaN
console.log(Number(null)); // 0
console.log(Number(false)); // 0
-
When using
Boolean()
as a function, it converts the input value to a boolean value. Since'false'
is a non-empty string, it evaluates totrue
.🙋♀️🙋♂️ However, if we use
new Boolean()
, e.g.new Boolean(false)
, aBoolean
object will be created. Since any object of which the value is notundefined
ornull
, evaluates totrue
when passed to a conditional statement.var x = new Boolean(false); if (x) { // this code is executed }
-
If the
+
operator is used with a string, it acts as the concatenation operator. When concatenating a number on to a string, the number will be converted to a string. -
When using non-numeric operands with the arithmetic operators, JavaScript will attempt to convert it to a numeric value.