DEV Community

Cover image for More JS Concepts
Chayti
Chayti

Posted on • Updated on

More JS Concepts

Truthy and Falsy values
A truthy value is a value which is true in any boolean context. We can say all values as truthy unless they are falsy.

Falsy values are:

  1. false
  2. 0 (zero)
  3. -0 (minus zero)
  4. 0n (BigInt zero)
  5. '', "", `` (empty string)
  6. null
  7. undefined
  8. NaN

Truthy values are:

  1. '0' (a string containing a single zero)
  2. 'false' (a string containing the text “false”)
  3. {} (an empty object)
  4. an empty array
  5. function(){} (an “empty” function)

By writing if condition or passing value to the boolean constructor function, we can check if a value is truthy or falsy.

Null Vs Undefined

  1. Null is an object where undefined is a type.
  2. Null is a declared and assigned value where undefined is just a declared variable.

var example;
alert(example); // output -> undefined

var example = null;
alert(example); // output -> null

Moreover, we can check if null & undefined are the same or not.
null === undefined // false
null == undefined // true

Double equal (==) vs triple equal (===)
Both do the comparison between variables. But the difference between them is that (==) checks for value equality by doing type coercion. That means, if we are performing (==) operation between ‘6’ (string) & 6 (number), the output is true, which is false for (===) operation, because (===) does not allow type coercion. So, we can say, (===) is superior to (==). (==) is also known as a loose, abstract or type converting equality operator.

Implicit conversion
It is also known as automatic type conversion or implicit coercion. JS converts an unexpected value type to an expected value type for performing operations.

We can find implicit conversion to number, to string, implicit boolean conversion to number, null conversion to number.

Implicit conversion to number:

let result;

result = '3' - '2';
alert(result); // 1

result = '3' - 2;
alert(result); // 1


result = '3' * 2;
alert(result); // 6

result = '3' / 2;
alert(result); // 1

When we perform -, /, * operations between a number and string or between two strings, the string is automatically converted to a number before performing the operation.

Implicit conversion to string:

let result;

result = '2' + 2;
console.log(result) // "22"

result = '2' + false;
console.log(result); // "2false"

When we add a number to a string in JS, the number is automatically converted to a string before performing the operation.

Implicit boolean conversion to number:

let result;

result = '3' - true;
alert(result); // 2

result = 3 + false;
alert(result); // 3

JS converts false as 0 and true as 1 in type conversion.

Null conversion to number:

let result;

result = 3 + null;
alert(result); // 3

JS converts null as 0 in type conversion. But for undefined, JS converts it as NaN.

Top comments (0)