A pot-digging interview question

Here’s an interview question for candidates:

The following code runs as follows:

(undefined = 42) &&console. log(undefined) 1) error 2) no output 3) output 42 4) output undefinedCopy the code

But before I explain that, let me tell you a little bit about how I came up with it.

void 0

It all started with void 0.

If we look at ts, Bable, or some JS libraries, we’ll see that void 0 is mostly used where undefined is needed.

It wasn’t until yesterday that I looked into what void 0 was, and it was really interesting.

First, the result of void 0 is undefined, but the code length is slightly shorter. And undefined is not a keyword in JS, it’s just a property on the window.

Void takes a single argument, but returns undefined, regardless of the argument: void takes a blank and an argument, and returns undefined: void takes a blank and an argument, and returns undefined: void takes a blank and an argument, and returns undefined: void takes a blank and an argument, and returns undefined.

void 0
void 42
void 'hello world'
void void 0
void(void(0))
Copy the code

Yes, that’s all undefined.

undefined

As mentioned, undefined is not a keyword. It is an attribute on the window, so the following code can run:

undefined = 42; window.undefined = 42; var undefined = 42; // let and const do not work because undefined already existsCopy the code

None of the above code will report an error, but we can see that undefined is still undefined.

The reason is simple:

Object.getOwnPropertyDescriptor(window, 'undefined');
// {value: undefined, writable: false, enumerable: false, configurable: false}
Copy the code

That’s right. You can’t write this stuff down.

Use of void 0

But since it’s not a key, it doesn’t stop you from declaring a variable with this name:

(function() { const undefined = 42; console.log(undefined); / / 42}) ();Copy the code

In fact, many js libraries have code like this:

(function(self, undefined) {
  ...
})(window);
Copy the code

I’m going to make undefined a local variable, so I’m not going to fetch it from window.

So instead of undefined for closure, it’s easier to use void 0.

In addition, void can also be used by iife:

void function() { console.log(42); } ();Copy the code

Interview Answers

Finally, answer the interview questions mentioned at the beginning.

First of all, it doesn’t report an error.

Then, the assignment expression’s value is rvalue, so the value of undefined is not changed, but console.log is executed.

So the answer is to print undefined.

Finally, thank you for taking the time to learn these not very useful knowledge.