Difference Between Null and Undefined in JavaScript
Q: What is the difference between null and undefined in JavaScript?
- JavaScript
- Junior level question
Explore all the latest JavaScript interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create JavaScript interview for FREE!
In JavaScript, `null` and `undefined` are both special values that represent the absence of a value, but they are used in slightly different ways.
`undefined` is a primitive value that is automatically assigned to a variable that has not been initialized or to a function that does not return a value. For example:
let myVariable; console.log(myVariable); // Output: undefined function myFunction() { // This function does not return a value } console.log(myFunction()); // Output: undefined
In these examples, `myVariable` is declared but not initialized, so it has the value of `undefined`. The `myFunction` function does not return a value, so it also has the value of `undefined`.
`null`, on the other hand, is an explicit value that represents the absence of any object value. It is typically used when a variable or property should have an explicit "no value" state. For example:
let myVariable = null; console.log(myVariable); // Output: null
In this example, we're explicitly setting `myVariable` to `null`, which represents an absence of any object value.
Here are some additional differences between `null` and `undefined`:
- `undefined` is a primitive value, while `null` is an object.
- `undefined` is the default value of uninitialized variables, while `null` must be assigned explicitly.
- `undefined` is used when a variable or property has not been assigned a value, while `null` is used to represent an intentional absence of any object value.
It's worth noting that `null` and `undefined` are both "falsy" values in JavaScript, which means that they will be treated as `false` in a boolean context.


