DEV Community

Raja B
Raja B

Posted on

Truthy and Falsy JavaScript

In JavaScript, truthy means a value behaves like true in an if condition, and falsy means a value behaves like false

Easy explanation:

  • Truthy = treated as true

  • Falsy = treated as false

Data Type Falsy Example Truthy Example
Boolean false true
String "" (Empty String) "hello", " ", "0"
Number 0, -0, NaN 1, -10, 3.14
Object / Structural None {}, [], new Date()
Empty / Missing null, undefined None

Undefined:

In JavaScript, undefined is a primitive data type and a global property that signifies a variable has been declared but has not yet been assigned a value

Simple example

let a;
console.log(a); // undefined
Enter fullscreen mode Exit fullscreen mode
undefined vs not defined:

- undefined means the variable exists, but no value is set yet

Example:

let name;
console.log(name); // undefined

Here, name is declared, but it has no value, 
so JavaScript shows undefined

- not defined means the variable was never declared

Example:

console.log(x);

This gives an error because x was never declared anywhere

Example:

function test() {
  console.log(y);
}
test();

If y was never declared, JavaScript cannot find it,
 so it is not defined
Enter fullscreen mode Exit fullscreen mode

NAN:

NaN means Not a Number in JavaScript. It usually appears when a number operation fails or when you try to convert something invalid into a number

Example


let result = 10 / "abc";
console.log(result); // NaN

Here, "abc" cannot be treated as a valid number, 
so the result becomes NaN
Enter fullscreen mode Exit fullscreen mode

Top comments (0)