• 周五. 12月 2nd, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Everything about null in JavaScript

[db:作者]

1月 6, 2022

author :Dmitri Pavluti

translator : The front end little wisdom

source :dmitripavlutin

Have dreams , There are dry goods , WeChat search 【 The big move the world 】 Pay attention to this dish washing wisdom who is still washing dishes in the early morning .

this paper GitHub https://github.com/qq449245884/xiaozhi Included , There is a complete interview site for a large factory 、 Materials and my series .

JavaScript Yes 2 Types : Basic types (string, booleans number, symbol) And the object .

Objects are complex data structures ,JS The simplest object in is a normal object : A set of keys and associated values :

let myObject = {
name: ' The front end little wisdom '
}

But in some cases, objects cannot be created . under these circumstances ,JS Provide a special value null — Indicates that the object is missing .

let myObject = null

In this paper , We will learn about JavaScript in null All the knowledge of : What it means , How to detect it ,null And undefined The difference between and why null It makes code maintenance difficult .

1. null The concept of

JS The specification states about null Information about :

value
null The value of the specified object is not set , It is JS Basic types One of , In Boolean operations, it is considered to be
falsy.

for example , function greetObject() Create objects , But when you can’t create an object, you can return to return null

function greetObject(who) {
if (!who) {
return null;
}
return { message: `Hello, ${who}!` };
}
greetObject('Eric'); // => { message: 'Hello, Eric!' }
greetObject(); // => null

however , Calling functions without parameters greetObject() when , This function returns null. return null It’s reasonable , because who Parameter has no value .

2. How to check null

Check null A good way to do this is to use the strict equality operator :

const missingObject = null;
const existingObject = { message: 'Hello!' };
missingObject === null; // => true
existingObject === null; // => false

missingObject === null As the result of the true, because missingObject The variable contains a null value .

If the variable contains a non null value ( Such as object ), Expression existObject === null The result of the calculation is false.

2.1 null It’s a virtual value

null And false0''undefinedNaN They are all imaginary values . If you encounter a virtual value in a conditional statement , that JS The virtual value will be forced to false.

Boolean(null); // => false
if (null) {
console.log('null is truthy')
} else {
console.log('null is falsy')
}

2.2 typeof null

typeof value Operator to determine the type of value . for example ,typeof 15 yes 'number',typeof {prop:'Value'} The result is 'object'.

Interestingly ,type null What is the result

typeof null; // => 'object'

Why 'object',typoef null by object Is early JS An error in the implementation .

To use typeof Operator detection null value . As mentioned earlier , Use the strictly equal operator myVar === null.

If we want to use it typeof Operator to check whether the variable is an object , It needs to be ruled out null value :

function isObject(object) {
return typeof object === 'object' && object !== null;
}
isObject({ prop: 'Value' }); // => true
isObject(15); // => false
isObject(null); // => false

3. null The trap of

null It often happens unexpectedly when we think the variable is an object . then , If from null Extract attributes from ,JS It throws an error .

Again using greetObject() function , And try to access… From the returned object message attribute :

let who = '';
greetObject(who).message;
// throws "TypeError: greetObject() is null"

because who The variable is an empty string , So this function returns null. from null visit message Attribute , Will lead to TypeError error .

It can be handled by using an optional link with a null merge null:

let who = ''
greetObject(who)?.message ?? 'Hello, Stranger!'
// => 'Hello, Stranger!'

4. null Alternative methods

When an object cannot be constructed , Our usual practice is to return to null, But there are drawbacks to this approach . Appears in the execution stack null when , It has to be checked .

Try to avoid returning null How to do it :

  • Return the default object instead of null
  • Throw an error instead of returning null

Back to the beginning, back to greeting Object’s greetObject() function . When the parameter is missing , You can return a default object , Instead of going back null

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

Or throw an error :

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

These two methods can be avoided null.

5. null vs undefined

undefined Is the value of an uninitialized variable or object property ,undefined Is the value of an uninitialized variable or object property .

let myVariable;
myVariable; // => undefined

null and undefined The main difference between them is ,null Represents the missing object , and undefined Represents an uninitialized state .

Strict equality operations operator === distinguish null and undefined :

null === undefined // => false

And the double equality operator == Think null and undefined equal

null == undefined // => true

I use the double equality operator to check if the variable is null or undefined:

function isEmpty(value) {
return value == null;
}
isEmpty(42); // => false
isEmpty({ prop: 'Value' }); // => false
isEmpty(null); // => true
isEmpty(undefined); // => true

6. summary

null yes JavaScript A special value in , Represents the missing object , The strict equality operator determines whether the variable is empty :variable === null.

typoef Operator for determining the type of variable (number, string, boolean) It is useful to . however , If null, be typeof Misleading :typeof null The value of is 'object'.

null and undefined It’s equivalent in a way , but null Indicates that the object is missing , and undefined Uninitialized state .


original text :https://dmitripavlutin.com/ja…

Possible after code deployment BUG There’s no way to know in real time , In order to solve these problems afterwards BUG, It took a lot of time log debugging , This way, I’d like to recommend an easy-to-use one for you BUG Monitoring tools Fundebug.

communication

Have dreams , There are dry goods , WeChat search 【 The big move the world 】 Pay attention to this dish washing wisdom who is still washing dishes in the early morning .

this paper GitHub https://github.com/qq44924588… Included , There is a complete interview site for a large factory 、 Materials and my series .

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注