Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Null, Undefined, NaN, Null values are often used in work, if not rigorous judgment, will lead to program error, affecting the operation of the code. So today unified collation of these commonly used false value judgment.

1. Null judgment

= = = 1.1

This can be determined directly by val === null

let val = null
console.log(val === null) // true
Copy the code

1.2 the Number ()

let val = null
console.log(Number(val) === 0) // true
Copy the code

1.3 !val

let val = null
console.log(! val)// true
Copy the code

Wrong way to judge:

let val = null
console.log(typeof(val)) // object
console.log(isNaN(val)) // false
Copy the code

2. Undefined judgment

= = = 2.1

let val = undefined
console.log(val === undefined) // true
Copy the code

2.2 typeof ()

let val = undefined
console.log(typeof(val) === 'undefined') // true
Copy the code

2.3 !val

let val = undefined
console.log(! val)// true
Copy the code

Wrong way to judge:

let val = undefined
console.log(Number(val)) // NaN
console.log(isNaN(val)) // true
Copy the code

3. NaN’s judgment

3.1 isNaN ()

let val = NaN
console.log(isNaN(val)) // true
Copy the code

3.2 !val

let val = NaN
console.log(! val)// true
Copy the code

Wrong way to judge:

let val = NaN
console.log(val === NaN) // false
console.log(Number(val)) // NaN
console.log(typeof(val)) // number
Copy the code

4. Judgment of null values

4.1 !val

let val = ' '
console.log(! val)// true
Copy the code

4.2 the Number ()

let val = ' '
console.log(Number(val)) // true
Copy the code

Wrong way to judge:

let val = ' '
console.log(typeof(val)) // string
console.log(isNaN(val)) // false
Copy the code

We find that there are several ways to judge each value, but by sorting it out! Val applies to all values, and is the most commonly used method in everyday work. Let’s summarize it with a picture:

Original article, hope to help you, but also for the community to contribute their own a modest strength! Please give a thumbs up if you like

Akiko: A little dream in the front

Home page: To learn more, click on your home page