Home Web Front-end JS Tutorial Detailed explanation of primitive data types Null and Undefined in JavaScript_javascript techniques

Detailed explanation of primitive data types Null and Undefined in JavaScript_javascript techniques

May 16, 2016 pm 03:25 PM
javascript null undefined

When discussing primitive data types in JavaScript, most people know the basics, from String, Number to Boolean. These primitive types are fairly simple and behave like common sense. However, this article will focus more on the unique primitive data types Null and Undefined, and what makes them so similar yet paradoxical.

1. Understanding Null and Undefined
In JavaScript, null is a literal and a keyword in the language, used to represent unrecognized object values. In other words, this is used to mean "no value". Although similar, undefined actually represents non-existence of a value. They are completely immutable, have no properties and methods, and cannot assign values ​​to their properties. In fact, trying to access or define a property will raise a TypeError. As their name implies, they are completely invalid values.

Boolean values ​​represented by no value are false, which means they will evaluate to false in a conditional context, such as an if statement. Use the equality operator (==) to compare these two values ​​with other false values, they are not equal except themselves:

null == 0; // false
undefined == ""; // false
null == false; // false
undefined == false; // false
null == undefined; // true
Copy after login

However, and other similarities, null and undefined are not equivalent. Each is a unique member of its own type, undefined is the Undefined type and null is the Null type. Compare these two values ​​using the equality operator (===), which requires that both types and values ​​are equal, as shown below:

undefined === null; // false
Copy after login

This is an important distinction that serves different purposes and reasons. To distinguish between these two values, you can think of undefined as representing an unexpected no value and null as representing an expected no value.
2. Generate Undefined
There are many ways to generate code with an undefined value. It is usually encountered when trying to access a value that does not exist. In this case, in a dynamic and weakly typed language like JavaScript, an undefined value will be returned by default instead of rising to an error.
Any variable declared without an initial value will have a default value of undefined:

 var foo; // 默认值为 undefined
Copy after login

When trying to access a non-existent object property or array item, return an undefined value:

var array = [1, 2, 3];
var foo = array.foo; // foo 属性不存在, 返回 undefined
var item = array[5]; // 数组中没有索引为5的项,返回 undefined
Copy after login

If the return statement of the function is omitted, undefined is returned:

var value = (function(){})(); // 返回 undefined
Copy after login

Values ​​not provided when the function is called will result in undefined parameter values:

(function(undefined){
  // 参数是 undefined
})();
Copy after login

The void operator can also return an undefined value. Libraries like Underscore use it as a defensive type check because it is immutable and can be relied upon in any context to return undefined:

function isUndefined(obj){
  return obj === void 0;
}
Copy after login

Finally, undefined is a predefined global variable (unlike the null keyword) initialized to the undefined value:

'undefined' in window; // true
Copy after login

In ECMAScript 5, this variable is read-only, which was not the case before.

3. Use cases of Null
The use case of null is the main aspect that makes it different, because unlike undefined, null is considered to be more useful. This is why the typeof operator returns "object" when applied to a null value. The original rationale was, and still is, that a null reference is usually used as a null object is expected, just like a placeholder. This behavior of typeof has been confirmed as a bug, and although a fix was proposed, this has been left unchanged for backward compatibility purposes.
This is why the JavaScript environment never sets a value to null; it must be done programmatically. As the documentation MDN says:
In the API, null is often expected where objects are retrieved, but there is no related object.
This applies to the DOM, which is language independent and outside the scope of the ECMAScript specification. Because it's an external API, trying to get an element that doesn't exist returns a null value, not undefined.
Generally speaking, if you need to assign an immutable value to a variable or property, pass it to a function, or return null from a function, null is almost always the best choice. In short, JavaScript uses undefined and programmers should use null.
Another possible use case for null, which is also considered good practice, is to explicitly designate a variable as invalid (object= null) when a reference is no longer required. By assigning a null value, the reference is effectively cleared, and assuming the object is not referenced by other code, garbage collection is specified to ensure that the memory is reclaimed.
4. Dig deeper
What makes null and undefined like black holes is not just their behavior, but the way they are handled internally within the JavaScript environment. They often don't seem to have the same associated characteristics as other native or built-in objects.
In ES5, the Object.prototype.toString method has become the de facto type checking standard, which is proven to be consistent with null and undefined:

Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(undefined); // [object Undefined]
Copy after login

However, the Object.prototype.toString method does not actually retrieve the internal [[Class]] property of null or the public constructor of undefined. According to the documentation, the following steps occur in the called process:

If the value is undefined, return "[object Undefined]".

  • If this value is null, return "[object Null]".
  • Let O be the result value of calling ToObject while passing this value as a parameter.
  • Let class be the value of O’s internal property [[Class]].
  • The returned result is the string value of the result of concatenating the three strings "[object", class, and "]".

This method performs a simple string return value if it detects null or undefined and other object uniform functions. This is common throughout the specification, as most methods contain a simple catch and return when null and undefined values ​​are encountered. In fact, there is no indication that they contain internal properties associated with any native objects. It’s like they’re not objects. I'm curious to know what would happen if an explicit solution actually existed inside JavaScript's native environment? Maybe someone more familiar with an implementation can get involved.

Conclusion
However unusual these native objects may be, understand the difference between null and undefined, and their distinct roles in JavaScript's language foundation. It may not make your application breakout, but in general it will only prove to be beneficial in the long term during development and debugging.

The above is an introduction to the primitive data types Null and Undefined in JavaScript. I hope it will be helpful to everyone's learning.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

TypeError: Cannot read property '$XXX' of undefined in Vue, how to deal with it? TypeError: Cannot read property '$XXX' of undefined in Vue, how to deal with it? Nov 25, 2023 pm 12:14 PM

If you often encounter the error message "TypeError: Cannotreadproperty'$XXX'ofundefined" when developing with Vue.js, how should you deal with it? This article explains the causes of this error and how to fix it. The cause of the problem is that when using Vue.js, we often use this to call methods of Vue components, such as: exportdefault{data()

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles