Skip to content

Latest commit

 

History

History
57 lines (43 loc) · 1.58 KB

8.Implicit-Coercion-I.md

File metadata and controls

57 lines (43 loc) · 1.58 KB

8. Implicit Coercion I

Problem

https://bigfrontend.dev/quiz/Implicit-Conversion-1

Problem Description

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));

Answer

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

Explanation

  • When using Boolean() as a function, it converts the input value to a boolean value. Since 'false' is a non-empty string, it evaluates to true.

    🙋‍♀️🙋‍♂️ However, if we use new Boolean(), e.g. new Boolean(false), a Boolean object will be created. Since any object of which the value is not undefined or null, evaluates to true 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.