Home Web Front-end JS Tutorial Talk about the void operator in Javascript

Talk about the void operator in Javascript

Dec 13, 2016 pm 01:24 PM

Since JS expressions tend to be verbose, I have recently begun to use Coffeescript to reduce the burden. For example, when I want to retrieve the first dog in the house, I must first determine whether the house object exists, then determine whether house.dogs exists, and finally retrieve house.dogs[0]. In JS, I need to write like this

1

var dog = (typeof house !== 'undefined && house !== null) && house.dogs && house.dogs[0]

Copy after login

In Coffee, I only need to write like this:

1

dog = house?.dogs?[0];

Copy after login

After writing this, readers will ask, does this have anything to do with the title "void in Javascript"? The essence of Coffee is JS. The reason why Coffee works so well is because it generates efficient and robust JS code. We can take a look at its generated results.

1

2

var dog, _ref;

dog = typeof house !== "undefined" && house !== null ? (_ref = house.dogs) != null ? _ref[0] : void 0 : void 0;

Copy after login

Just one line of Coffee code generated such a long JS code, which seems to be more reliable and safer than the one I wrote in JS earlier. There are two void 0s at the end. Who is this?

Structure the above example:

1

2

3

dog = (typeof house !== "undefined" && house !== null) ?

        ((_ref = house.dogs) != null ? _ref[0] : void 0 )

        : void 0;

Copy after login

If house is undefined or house is null, void 0 is returned

If house.dogs is null, void 0 is returned

But what is the value of void 0? This is It’s easy to test:

1

typeof void 0 //得到"undefined"console.log(void 0) //输出undefined

Copy after login

It seems that void 0 is undefined, but this method is too wild and not rigorous enough, that is, it is impossible to answer: What are the values ​​​​of the countless possible combinations of void 100, void hello(), void i++?

Let’s take a look at what the standards say.

The specification says this

In the ECMAScript 262 specification, there is the following description:

1

2

3

4

5

6

The void Operator

The production UnaryExpression : void UnaryExpression is evaluated as follows:

Let expr be the result of evaluating UnaryExpression.

Call GetValue(expr).

Return undefined.

NOTE: GetValue must be called even though its value is not used because it may have observable side-effects.

Copy after login

Translation:

1

2

3

4

5

6

void操作符

产生式 UnaryExpression : void UnaryExpression 按如下流程解释:

令 expr 为解释执行UnaryExpression的结果。

调用 GetValue(expr).

返回 undefined.

注意:GetValue一定要调用,即使它的值不会被用到,但是这个表达式可能会有副作用(side-effects)。

Copy after login

The key point is: no matter what the expression after void is, the void operator will return undefined. Therefore, the above is given by We can think of the code compiled by Coffee as follows:

1

2

3

dog = (typeof house !== "undefined" && house !== null) ?

        ((_ref = house.dogs) != null ? _ref[0] : undefined )

        : undefined ;

Copy after login

The question is, since (void 0) === undefined, wouldn’t it be enough to just write undefined?

Why use void?

Because undefined is not a reserved word in javascript. In other words, you can write:

1

2

3

4

5

function joke() {

    var undefined = "hello world";

    console.log(undefined); //会输出"hello world"

}

console.log(undefined); //输出undefined

Copy after login

Yes, you can use undefined as the variable name in a function context, so the code written in this context can only get undefined from the global scope, such as:

1

2

window.undefined //浏览器环境

GLOBAL.undefined //Node环境

Copy after login

But it should be noted that even if window, GLOBAL can still be defined in the function context, so taking undefined from window/GLOBAL is not 100% reliable. For example:

1

2

3

4

5

6

7

8

9

10

11

function x() {

   var undefined = 'hello world',

       f = {},

       window = {

           'undefined': 'joke'

       };

   console.log(undefined);// hello world

   console.log(window.undefined); //joke

   console.log(f.a === undefined); //false

   console.log(f.a === void 0); //true

}

Copy after login

So, using void to obtain undefined has become a general rule. For example, isUndefined in underscore.js is written like this:

1

2

3

_.isUndefined = function(obj) {

    return obj === void 0;

}

Copy after login

In addition to using void to ensure that the undefined value is obtained, are there any other methods? Yes, another way is through function calling. For example, the source code of AngularJS uses this method:

1

2

(function(window, document, undefined) {    //.....

})(window, document);

Copy after login

By not passing parameters, it ensures that the value of the undefined parameter is undefined.

Other functions

Besides taking undefined, are there any other uses for void?

There is also a common function, filling href. Below is a screenshot of Weibo. Its forwarding, favorites, and discussions are all hyperlinks, but users do not want to click on them to jump to another page, but to trigger some interactive operations.

Talk about the void operator in Javascript

Theoretically, these three hyperlinks have no URL, but if you don’t write it, hehe, clicking it will refresh the entire page. So we used href="javascript:void(0) to ensure that clicking it will execute a purely boring void(0).

Another situation is that if we want to generate an empty src image, The best way seems to be src='javascript:void(0)'

Written at the end

Back to the definition of void, there is a sentence that is particularly confusing:

Note: GetValue must be called, even if its value Will not be used, but this expression may have side-effects

.

这是什么意思?这表示无论void右边的表达式是什么,都要对其求值。这么说可能不太明白,在知乎上winter大神有过阐述关于js中void,既然返回永远是undefined,那么GetValue有啥用?,我且拾人牙慧,代入一个场景,看代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

var happiness = 10;

var girl = {

    get whenMarry() {

        happiness--;

        return 1/0; //Infinity

    },

    get happiness() {

        return happiness;

    }

};

 

console.log(girl.whenMarry); //调用了whenMarry的get方法

console.log(girl.happiness); // 9

 

void girl.whenMarry; //调用了whenMarry的get方法

console.log(girl.happiness); // 8

 

delete girl.whenMarry; //没有调用whenMarry的get方法

console.log(girl.happiness); //还是8

Copy after login

上述代码定义了一个大龄文艺女青年,每被问到什么时候结婚呀(whenMarry),happiness都会减1。从执行情况可以看出,无论是普通访问girl.whenMarry,还是void girl.whenMarry都会使她的happiness--。而如果把void换成delete操作符写成delete girl.whenMarry,她的happiness就不会减了,因为delete操作符不会对girl.whenMarry求值。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

10 Ways to Instantly Increase Your jQuery Performance 10 Ways to Instantly Increase Your jQuery Performance Mar 11, 2025 am 12:15 AM

This article outlines ten simple steps to significantly boost your script's performance. These techniques are straightforward and applicable to all skill levels. Stay Updated: Utilize a package manager like NPM with a bundler such as Vite to ensure

Using Passport With Sequelize and MySQL Using Passport With Sequelize and MySQL Mar 11, 2025 am 11:04 AM

Sequelize is a promise-based Node.js ORM. It can be used with PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL. In this tutorial, we will be implementing authentication for users of a web app. And we will use Passport, the popular authentication middlew

How to Build a Simple jQuery Slider How to Build a Simple jQuery Slider Mar 11, 2025 am 12:19 AM

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

See all articles