Table of Contents
null
false
number
4. null 的替代方案
5. null vs undefined
6. 总结
Home Web Front-end JS Tutorial Comprehensive analysis of null in JavaScript

Comprehensive analysis of null in JavaScript

Sep 13, 2022 pm 05:30 PM
javascript

This article brings you relevant knowledge about javascript. Null is a primitive type, which means it intentionally does not contain any object value. Let’s take a look at everything about null in JavaScript: What does it mean, how to detect it, the difference between null and undefined, and why extensive use of null can cause code maintenance difficulties, etc. I hope it will be helpful to everyone.

Comprehensive analysis of null in JavaScript

【Related recommendations: javascript video tutorial, web front-end

JavaScript There are two types: primitive types (strings, booleans, numbers, symbols) and objects

Objects are a complex data structure. The simplest JavaScript objects are ordinary objects - a collection of keys and related values ​​

let myObject = {
  name: 'Eric Cartman'
};
Copy after login

But in many cases it is not possible to create an object. In this case, JavaScript provides a special value null - indicating that the object is missing

let myObject = null;
Copy after login

In this article, you will learn about ## Everything about null in #JavaScript: what it means, how to detect it, the difference between null and undefined, and why # is used a lot ##null Will cause difficulty in code maintenance, etc.1. The concept of null

JavaScript

is described in the specificationnull null is a primitive type that intentionally does not contain any object value

If you see

null

(assigned to a variable or returned by a function), then at that location it should have is an object, but for some reason, an object was not createdFor example, the function

greetObject()

creates an object, but it can also returnnull## when the object cannot be created. #:

function greetObject(who) {
  if (!who) {
    return null;
  }
  return { message: `Hello, ${who}!` };
}

greetObject('Eric'); // => { message: 'Hello, Eric!' }
greetObject();       // => null
Copy after login
When a string parameter is passed in to the above function, as expected, the function returns an object{ message: 'Hello, Eric!' }

However, when no parameters are passed in the function, the function returns null

. It is reasonable to return

null because the who parameter has no value, resulting in the greeting object being unable to be created1.1 A more appropriate metaphor for null

Consider a more apt metaphor for

null

, you can think of a variable as a box. Just like variables can hold objects, boxes can hold items like teapots etc. But once you receive a box, open it, there's nothing! Someone made a mistake and gave you an empty box. The box does not contain any content, or in other words, it contains a

null value

2. How to detect null

Checknull

OK The method is to use the strict equality operator

const missingObject = null;
const existingObject = { message: 'Hello!' };

missingObject  === null; // => true
existingObject === null; // => false
Copy after login

missingObject === null The result is true

because the

missingObject variable contains a null value. If the variable contains a non-null value, such as an object, the expression existingObject === null evaluates to false2.1 null is a false valuenull

and

false

, 0, ",

undefined, NaN are all false values. If they are encountered in a conditional statement , then JavaScript will coerce them to false

Boolean(null); // => false

if (null) {
  console.log('null is truthy');
} else {
  console.log('null is falsy'); // logs 'null is falsy'
}
Copy after login
2.2 typeof nulltypeof value

type operators can determine The type of value. For example, type 15 is

number

,

typeof { prop: 'Value' } is equal to object. Interesting Yes, null What is the result of value type

typeof null; // => 'object'

What about a missing object type Is it judged as
object

? It turns out that

typoef null
is treated as

object. This is a bug in the early JavaScript implementation. Do not use The typeof operator detects null

values. As mentioned earlier, use the strict equality operator

myVar === null if you want To use typeof to check whether a variable is an object, you must exclude the null

situation

function isObject(object) {
  return typeof object === 'object' && object !== null;
}

isObject({ prop: 'Value' }); // => true
isObject(15);                // => false
isObject(null);              // => false
Copy after login
3. The trap of nullnull

usually appears unexpectedly in situations where you expect to use an object. Then, if you try to extract a property from

null

,

JavaScript will throw an error Let's use the greetObject() function again and try to access the message

property from the returned object

let who = '';

greetObject(who).message; 
// throws "TypeError: greetObject() is null"
Copy after login
because the who variable is a empty string, so the function returns null

. When accessing the

message property from null, a TypeError error will be thrown You can pass Use the optional chaining operator to handle null

let who = '';

greetObject(who)?.message ?? 'Hello, Stranger!';  
// => 'Hello, Stranger!'
Copy after login

or use the two alternatives described in the next section.

4. null 的替代方案

当你不能构造一个对象时,很容易返回 null。但这种做法也有缺点

一旦 null 出现在执行堆栈中,你总是必须检查它

我们尽量避免返回 null

  • 返回默认对象而不是 null
  • 抛出错误而不是返回 null

让我们回忆一下 greetObject() 函数返回 greeting 对象

当缺少参数时,可以返回一个默认对象,而不是返回 null

function greetObject(who) {
  if (!who) {
    who = 'Stranger';
  }
  return { message: `Hello, ${who}!` };
}

greetObject('Eric'); // => { message: 'Hello, Eric!' }
greetObject();       // => { message: 'Hello, Stranger!' }
Copy after login

或者抛出一个错误

function greetObject(who) {
  if (!who) {
    throw new Error('"who" argument is missing');
  }
  return { message: `Hello, ${who}!` };
}

greetObject('Eric'); // => { message: 'Hello, Eric!' }
greetObject();       // => throws an error
Copy after login

这些实践可以让你完全避免处理 null

5. null vs undefined

undefined 就是未初始化的变量或对象属性的值

例如,如果在声明变量时没有赋初值,那么访问该变量的结果为 undefined

let myVariable;

myVariable; // => undefined
Copy after login

nullundefined 之间的主要区别是,null 表示丢失了的对象,而 undefined 表示未初始化的状态

严格相等运算符 === 区分 nullundefined

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

而松散相等运算符 == 则认为 nullundefined 相等

null == undefined; // => true
Copy after login

我使用松散相等运算符检查变量是否为 nullundefined

function isEmpty(value) {
  return value == null;
}

isEmpty(42);                // => false
isEmpty({ prop: 'Value' }); // => false
isEmpty(null);              // => true
isEmpty(undefined);         // => true
Copy after login

6. 总结

nullJavaScript 中的一个特殊值,表示丢失的对象

严格相等运算符判断变量是否为空: variable === null

typoef 操作符用于确定变量的类型(number, string, boolean)。但是,typeofnull 情况下会引起误解: typeof null 结果为 object

nullundefined 在某种程度上是等价的,但null 表示一个丢失的对象,而 undefined 表示未初始化状态

尽可能避免返回 null 或将变量设置为 null。因为这种做法会导致 null 值的扩展和需要对 null 的验证。相反,尝试使用具有默认属性的对象,或者甚至抛出错误会是更好的实践

你会使用什么方法来检查 null?

【相关推荐:javascript视频教程web前端

The above is the detailed content of Comprehensive analysis of null in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 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

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.

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).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles