Javascript type casting

falsy_value

In javascript we can convert one type to another type (typecasting). As we know true and false are related to boolean data type. Zero, empty string, undefined, null, NaN are falsy values. All non-empty things and true are Truthy values.

But going to deep inside into falsy value. We need to know about logical not (!). Logical Not just converts operand into boolean and negates the value. So the result is always a boolean value. Like –


console.info(!1); // false
console.info(!true); // false
console.info(!"test"); // false

Double NOT (!!) is used to convert a value into boolean; and it will just negates the negates value.


console.info(!!1); // true
console.info(!!true); // true
console.info(!!"test"); // true

falsy value with Logical operator –

Case 1 –


var bol = false; // any falsy value
var msg = "";

if (!bol) {
msg = "Inside if";
} else {
msg = "Inside else";
}
console.info(msg) // Inside if

Case 2 –


function logs(msg) {
    var msg = msg || "Hi you are inside logs function";
    console.info(msg);
}

logs("Hi"); // Hi
logs(); // Hi you are inside logs function

You May Also Like

About the Author: Pankaj Bisht