Home > Web Front-end > JS Tutorial > body text

What is the difference between Null and undefined in JavaScript?

Barbara Streisand
Release: 2024-10-19 06:18:30
Original
948 people have browsed it

Null

In JavaScript, null is a primitive value that represents the intentional absence of any object value. It is one of JavaScript's falsy values, meaning it evaluates to false in boolean contexts. However, it is distinct from undefined, which represents a variable that has been declared but has not been assigned a value.

  • null is a special primitive value, but when you check its type using typeof, it returns "object".

What is the difference between Null and undefined in JavaScript?
null is used when a variable is expected to hold an object but currently doesn't have one. It signals the intentional absence of a value.

let person = null;  // The `person` variable explicitly has no value.
Copy after login

Used when you intentionally want to signify "no value" or "empty."


Undefined

In JavaScript, undefined is a primitive value automatically assigned to variables that have been declared but not yet assigned a value.

  • undefined is a primitive type in JavaScript. It refers to variables that have been declared but not initialized, and its typeof will correctly reflect "undefined".
let x;
console.log(typeof x);         // "undefined"
Copy after login

Difference Between null and undefined

What is the difference between Null and undefined in JavaScript?
In this example, uninitializedVariable is undefined because it hasn't been assigned any value.
Meanwhile, objectWithNoValue is explicitly set to null, signaling that it should hold an object, but currently it doesn’t.

Comparison

  • Loose equality (==) null and undefined are loosely equal because they both represent an "empty" value.
console.log(null == undefined);  // true
Copy after login
Copy after login
  • Strict equality (===) They are not strictly equal because they are different types.
console.log(null == undefined);  // true
Copy after login
Copy after login

The above is the detailed content of What is the difference between Null and undefined in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!