WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Basic · question 16 of 100

What is the difference between "null" and "undefined" in JavaScript?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

In JavaScript, null and undefined are two distinct values that are used to represent the absence of a value. Although they are often used interchangeably, they have slightly different meanings and behaviors in the language.

undefined is a value that indicates that a variable has been declared but has not been assigned a value. In other words, it is the default value of a variable that has not been initialized. For example:

    var myVar;
    console.log(myVar); // Outputs undefined

In this example, the myVar variable is declared but not assigned a value, so its value is undefined.

null, on the other hand, is a value that represents the intentional absence of any object value. It is often used as a placeholder or to indicate that a value does not exist. For example:

    var myVar = null;
    console.log(myVar); // Outputs null

In this example, the myVar variable is assigned the value of null, indicating that there is no object value present.

While undefined is a primitive type in JavaScript, null is an object. Additionally, when a variable is logged to the console with a value of undefined, the console will log the string "undefined", while a value of null will log as "null".

Another important difference between null and undefined is that null is considered a defined value, while undefined is not. This means that a variable can be explicitly set to null, but it cannot be explicitly set to undefined. Instead, undefined is used to indicate that a variable has not been assigned a value.

In summary, null and undefined are both values used to represent the absence of a value in JavaScript. While they are often used interchangeably, they have different meanings and behaviors in the language. undefined indicates that a variable has not been assigned a value, while null represents the intentional absence of any object value.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics