What is difference between null and undefined in javascript

·

1 min read

In JavaScript, null and undefined are both special values that represent absence or lack of a meaningful value, but they have different meanings.

undefined means that a variable has been declared but has not been assigned a value, or that a property or object does not exist. It is also returned when you try to access a nonexistent object property or function argument.

For example:

let x;
console.log(x); // prints undefined

function example(y) {
  console.log(y);
}
example(); // prints undefined

null, on the other hand, is an intentional absence of any object value. It is used to indicate that a variable, object property or argument should have no value or be empty.

For example:

let x = null;
console.log(x); // prints null

let person = {
  name: 'John',
  age: null
};
console.log(person.age); // prints null

So in summary, undefined means a variable is declared but not assigned a value, or a property or object does not exist, while null represents an intentional absence of any object value.