惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threatpost
博客园 - 叶小钗
T
The Blog of Author Tim Ferriss
Recent Announcements
Recent Announcements
D
DataBreaches.Net
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
Netflix TechBlog - Medium
Microsoft Azure Blog
Microsoft Azure Blog
Microsoft Security Blog
Microsoft Security Blog
B
Blog
U
Unit 42
有赞技术团队
有赞技术团队
博客园 - 聂微东
GbyAI
GbyAI
宝玉的分享
宝玉的分享
F
Full Disclosure
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MyScale Blog
MyScale Blog
Jina AI
Jina AI
Martin Fowler
Martin Fowler
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
P
Proofpoint News Feed
A
About on SuperTechFans
I
InfoQ
博客园 - 【当耐特】
C
Check Point Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
Y
Y Combinator Blog
Project Zero
Project Zero
WordPress大学
WordPress大学
小众软件
小众软件
AWS News Blog
AWS News Blog
博客园 - 司徒正美
T
The Exploit Database - CXSecurity.com
L
LINUX DO - 热门话题
I
Intezer
Engineering at Meta
Engineering at Meta
C
CXSECURITY Database RSS Feed - CXSecurity.com
J
Java Code Geeks
T
Tenable Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
C
CERT Recently Published Vulnerability Notes

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Everything about null in JavaScript
Dmitri Pavlutin · 2020-09-22 · via Dmitri Pavlutin Blog

JavaScript has 2 kinds of types: primitives (strings, booleans, numbers, symbols) and objects.

Objects are complex data structures. The simplest object in JavaScript is the plain object — a collection of keys and associated values:


let myObject = {

name: 'Eric Cartman'

};


But there are situations when an object cannot be created. For such cases, JavaScript provides a special value null — which indicates a missing object.

In this post, you'll learn everything about null in JavaScript: its meaning, how to detect it, the difference between null and undefined, and why using null extensively creates code maintenance difficulties.

Table of Contents

  • 1. The concept of null
    • 1.1 Real-world analogy of null
  • 2. How to check for null
    • 2.1 null is falsy
    • 2.2 typeof null
  • 3. The trap of null
  • 4. Alternatives to null
  • 5. null vs undefined
  • 6. Summary

1. The concept of null

The JavaScript specification says about null:

null is a primitive value that represents the intentional absence of any object value.

If you see null (either assigned to a variable or returned by a function), then at that place should have been an object, but for some reason, an object wasn't created.

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


function greetObject(who) {

if (!who) {

return null;

}

return { message: `Hello, ${who}!` };

}

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

greetObject(); // => null


When invoking the function with a string argument like greetObject('Eric'), as expected, the function returns an object { message: 'Hello, Eric!' }.

However, when invoking the function with no arguments — greetObject() — the function returns null. Returning null is reasonable because who parameter has no value, and the greeting object cannot be created.

1.1 Real-world analogy of null

Thinking about a real-world analogy, you can imagine a variable as being a box. Just like a variable can hold an object, the box can contain objects like a teapot.

But once you receive a box and open it... and nothing there! Someone made a mistake and sent you an empty box. The box contains nothing, or, saying it differently, contains a null value.

2. How to check for null

The good way to check for null is by using the strict equality operator:


const missingObject = null;

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

missingObject === null; // => true

existingObject === null; // => false


missingObject === null evaluates to true because missingObject variable contains a null value.

If the variable contains a non-null value, like an object, the expression existingObject === null evaluates to false.

2.1 null is falsy

null, alongside false, 0, '', undefined, NaN, is a falsy value. If a falsy value is encountered in conditionals, then JavaScript coerces falsy to false.


Boolean(null); // => false

if (null) {

console.log('null is truthy');

} else {

console.log('null is falsy'); // logs 'null is falsy'

}


2.2 typeof null

typeof value operator determines the type of value. For example typeof 15 is 'number' and typeof { prop: 'Value' } evaluates to 'object'.

Interestingly, to what value type null evaluates to?


typeof null; // => 'object'


Hm... how could the type of a missing object evaluate to 'object'? Turns out typoef null being 'object' was a mistake in the early JavaScript implementation.

Do not use typeof operator to detect a null value. As mentioned previously, use the strict equality operator myVar === null.

If you'd like to check whether a variable contains an object using typeof operator, you have to check againts null too:


function isObject(object) {

return typeof object === 'object' && object !== null;

}

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

isObject(15); // => false

isObject(null); // => false


3. The trap of null

null might appear, often unexpectedly, in situations when you expect an object. Then if you try to extract a property from null, JavaScript throws an error.

Let's use again greetObject() function and try to access message property from the returned object:


let who = '';

greetObject(who).message;

// throws "TypeError: greetObject() is null"


Because who variable is an empty string, the function returns null. When accessing message property from null, a TypeError error is thrown.

You can handle null by either using the optional chaining with nullish coalescing:


let who = '';

greetObject(who)?.message ?? 'Hello, Stranger!';

// => 'Hello, Stranger!'


or use 2 alternatives described in the next section.

4. Alternatives to null

It's tempting to return null when you cannot construct an object. But this practice has downsides.

As soon as null appears within your execution stack, you always have to check for it.

I try to avoid returning null in favor of:

  • returning a default object instead of null
  • throwing an error instead of returning null

Let's recall the greetObject() function that returns greeting objects.

Instead of returning null when the argument is missing, you could either return a default object:


function greetObject(who) {

if (!who) {

who = 'Stranger';

}

return { message: `Hello, ${who}!` };

}

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

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


either 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 practices let you avoid dealing with null at all.

5. null vs undefined

undefined is the value of an uninitialized variable or object property.

For example, if you declare a variable without assigning an initial value, accessing such variable evaluates to undefined:


let myVariable;

myVariable; // => undefined


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

The strict equality operator === distinguishes null from undefined:


null === undefined; // => false


While loose equality operator == considers null and undefined equal:


null == undefined; // => true


I use the loose equality operator to check whether a 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 a variable is null: variable === null.

typoef operator is useful to determine the type of a variable (number, string, boolean). However, typeof is misleading in case of null: typeof null evaluates to 'object'.

null and undefined are somehow equivalent, still, null represents a missing object, while undefined uninitialized state.

Avoid if possible returning null or setting variables to null. This practice leads to the spread of null values and verifications for null. Instead, try to use objects with default properties, or even throw errors.

Having mastered null, why not master undefined? Follow my post 7 Tips to Handle undefined in JavaScript.

What condition do you use to check for null?