DEV Community

Nanthini Ammu
Nanthini Ammu

Posted on

Truthy vs Falsy Values, Explicit Type Conversion

Truthy vs Falsy Values:

Falsy Values :

  • "",'' String with zero length
  • false- boolean keyword
  • 0 number zero, -0 negative zero, 0n bigint zero.
  • NaN-Not a Number
  • null
  • undefined- Variable that has been declared but not assigned with a value.

Truthy Values :

  • Everything else Truthy.
function isFalsy(value) {
    if(value) {
        console.log ("The value is truthy.");
    } else {
        console.log ("The value is falsy.");
    }
}

isFalsy(false); //falsy value
isFalsy(0);     //falsy value
isFalsy(-0);    //falsy value
isFalsy(0n);    //falsy value
isFalsy(null);  //falsy value
isFalsy(undefined); //falsy value
isFalsy(NaN);    //falsy value
isFalsy("");    //falsy value
isFalsy('');    //falsy value
isFalsy(``);    //falsy value
isFalsy(1);     //truthy value
isFalsy(-1);    //truthy value
isFalsy(0.1);   //truthy value
isFalsy(-0.1);  //truthy value
isFalsy(1n);    //truthy value
isFalsy("false"); //truthy value
isFalsy("0");    //truthy value 
isFalsy("null"); //truthy value
isFalsy("undefined"); //truthy value
isFalsy("NaN");  //truthy value

Enter fullscreen mode Exit fullscreen mode

Explicit Type Conversion :

  • It is used to manually convert a value from one data type to another using build-in functions.

Converting to String :

  • string(value)
  • .toString(value)
let a = 10;
console.log(typeof a); // number
console.log(typeof String(a)); // string
console.log(typeof a.toString()); // string
Enter fullscreen mode Exit fullscreen mode

Converting to Number :

  • Number(value)
  • parseInt(value)
  • parseFloat(value)
  • Using unary +
let a ="10";
let b ="10.5";
console.log(typeof a); // string
console.log(typeof Number(a)); // number
console.log(typeof parseInt(a)); // number
console.log(typeof parseFloat(b)); // number


console.log(5+"10"); // string concatenation, result is "5" + "10" = "510"

// If one value is a string, + becomes string concatenation, not addition. Only + behaves differently , others (-, *, /) convert to numbers.

// Using unary + we can convert string to numeric.
console.log(5+ +"10"); // numeric addition, +"10" converts "10" to 10, result is 5 + 10 = 15


console.log(5-"10"); // numeric subtraction, "10" is converted to 10, result is 5 - 10 = -5
console.log(5*"10"); // numeric multiplication, "10" is converted to 10, result is 5 * 10 = 50
console.log(5/"10"); // numeric division, "10" is converted to 10, result is 5 / 10 = 0.5
Enter fullscreen mode Exit fullscreen mode

Converting to Boolean :

Top comments (0)