DEV Community

Ranjith srt
Ranjith srt

Posted on • Edited on

Js | Truthy & Falsy |

Truthy and Falsy Values:
Enter fullscreen mode Exit fullscreen mode

in Javascript, truthy and falsy values are used to determine whether a value evaluate to true or false in a boolean
context.this concept is crucial for controlling the flow of your program using conditions like if statement.

Falsy Values: 
Enter fullscreen mode Exit fullscreen mode

0,"",null,NaN,false,undefined

console.log(Boolean(0)); //false
Enter fullscreen mode Exit fullscreen mode
console.log(Boolean(undefined)); //false

Enter fullscreen mode Exit fullscreen mode
console.log(Boolean(' '));  //empty false

Enter fullscreen mode Exit fullscreen mode
console.log(Boolean(null)); //false

Enter fullscreen mode Exit fullscreen mode
console.log(Boolean(NaN)); //false not a number

Enter fullscreen mode Exit fullscreen mode
console.log(Boolean(false)); //false
Enter fullscreen mode Exit fullscreen mode

Truthy Values: any value that is not Falsy :

console.log(Boolean(1)); //true
Enter fullscreen mode Exit fullscreen mode
console.log(Boolean(1833933)); //true
Enter fullscreen mode Exit fullscreen mode
console.log(Boolean(-1)); //true
Enter fullscreen mode Exit fullscreen mode
console.log(Boolean("hello")); //true
Enter fullscreen mode Exit fullscreen mode
console.log(Boolean(1)); //true
Enter fullscreen mode Exit fullscreen mode
console.log(Boolean([])); //true empty array
Enter fullscreen mode Exit fullscreen mode
console.log(Boolean({})); //true empty object
Enter fullscreen mode Exit fullscreen mode
console.log(function (){}); //true
Enter fullscreen mode Exit fullscreen mode
Example:
Enter fullscreen mode Exit fullscreen mode

           t     f
let cash =255  //0 ; 
    //conditions false  statement block not run
if (cash){
  console.log("you can buy burger with drink"); 
}else{
   console.log("you can buy burger"); 
}else{
   console.log("you don't have money"); 
}

Enter fullscreen mode Exit fullscreen mode
let a;
console.log(a); //false
Enter fullscreen mode Exit fullscreen mode
output:
undefined 
Enter fullscreen mode Exit fullscreen mode
let a = 10;
console.log(a); //true
Enter fullscreen mode Exit fullscreen mode
let a = null;
console.log(a); //false
Enter fullscreen mode Exit fullscreen mode

Top comments (0)