6
Author: Dmitri Pavluti
Translator: Frontend Xiaozhi
Source: dmitripavlutin

If you have dreams and dry goods, search on [Daily Move to the World] Follow this brushing wisdom who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line factory interview complete test sites, materials and my series of articles.

JavaScript has two types: basic types ( string , booleans number , symbol ) and objects.

Objects are complex data structures. The simplest objects in JS are ordinary objects: a set of keys and associated values:

let myObject = {
  name: '前端小智'
}

However, in some cases the object cannot be created. In this case, JS provides a special value null -which means that the object is missing.

let myObject = null

In this article, we will learn all about null in JavaScript: its meaning, how to detect it, null and undefined , and why the use of null makes code maintenance difficult.

1. The concept of null

The JS specification states information about null :

The value null means that the value of the object is not set. It is one of the basic types of JS and is considered to be falsy in Boolean operations.

For example, the function greetObject() creates an object, but it can also return to null when the object cannot be created:

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

greetObject('Eric'); // => { message: 'Hello, Eric!' }
greetObject();       // => null

However, when the function greetObject() is called without parameters, the function returns null . null is reasonable to return who parameter has no value.

2. How to check for null

A good way to check the null is to use the strict equality operator:

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

missingObject  === null; // => true
existingObject === null; // => false

missingObject === null result is true , because missingObject variable contains a null value.

If the variable contains a non-empty value (for example, an object), the expression existObject === nul is calculated as false .

2.1 Null is an imaginary value

null and false , 0 , '' , undefined , NaN are all dummy values. If a dummy value is encountered in the conditional statement, then JS will force the dummy value 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 determines the type of value. For example, typeof 15 is 'number' , typeof {prop:'Value'} calculation result is 'object' .

Interestingly, type null the result of 060da77a30e57b

typeof null; // => 'object'

Why is 'object' , typoef null is object is a mistake in the early JS implementation.

To use the typeof operator to detect the null value. As mentioned earlier, use the strict equality operator myVar === null .

If we want to use the typeof operator to check whether the variable is an object, we also need to exclude the null value:

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

isObject({ prop: 'Value' }); // => true
isObject(15);                // => false
isObject(null);              // => false

3. The null trap

null often appears unexpectedly when we think the variable is an object. Then, if you null , JS will throw an error.

Use the greetObject() function again and try to access the message attribute from the returned object:

let who = '';

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

Because the who is an empty string, the function returns null . null accessing the message attribute from TypeError error will be raised.

null can be handled by using optional links with null merging:

let who = ''

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

4. Alternatives to null

When the object cannot be constructed, our usual approach is to return null , but this approach has disadvantages. null appears in the execution stack, it just has to be checked.

Try to avoid returning null :

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

Back to the beginning, return the greetObject() function of the greeting When the parameter is missing, you can return a default object instead of returning 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 avoid the use of null .

5. null vs undefined

undefined is the value of an uninitialized variable or object attribute, and undefined is the value of an uninitialized variable or object attribute.

let myVariable;

myVariable; // => undefined

The main difference between null and undefined null represents a lost object, while undefined represents an uninitialized state.

The strict equality operation symbol === distinguishes between null and undefined :

null === undefined // => false

The double-equal operator == considers 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 is a special value in JavaScript that represents a missing object. The strict equality operator determines whether the variable is empty: variable === null .

typoef operator is useful for determining the type of a variable ( number , string , boolean ). However, if null , the typeof be misleading: typeof null value 'object' .

null and undefined are equivalent to some extent, but null indicates that the object is missing, and undefined not initialized.


Original: https://dmitripavlutin.com/javascript-null/#comments

code is deployed, the possible bugs cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .

communicate with

There are dreams and dry goods. search 160da77a30e9cc [Great Move to the World] pay attention to this wise brush who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.


王大冶
68k 声望104.9k 粉丝