Unable to determine type undefined ()

I recently explored a situation where a programmer inadvertently passed undefined to addEventListener, thus:
 window.addEventListener('load', undefined); 

No error has been selected. It is as if JavaScript is ready to call undefined . But what in the world of undefined() ? I tried all kinds of things, for example:

 console.log(undefined() === null); console.log(typeof undefined()); 

but I never get anything.

Editing added for clarity . My initial question was based on an error, since I did not install the developer tools for reporting errors on the console. The above two commands (but not the addEventListener call) DO throw errors in the browser, as the answers and comments below show.

+5
source share
4 answers

It is as if JavaScript is ready to call undefined .

No, addEventListener specified to ignore null , which JavaScripts undefined converts to . undefined never called.

Another piece of evidence that JavaScript doesn't want to call undefined in the browser:

 > undefined() Uncaught TypeError: undefined is not a function at <anonymous>:1:1 
+2
source

He will return:

Undefined is not a function

 console.log(typeof undefined()); 

If you run the console in a browser, it will return an undefined non-function. undefined has no value other than null , which is an object.

0
source

null means that something exists, but it has been said that it does not matter. undefined means that the item has not received a value, usually because it has not been declared / initialized.

In Javascript, undefined is primitive. It is false, so it evaluates to False if used in a conditional expression.

Javascript is not a strongly typed language, so there is nothing to verify that a callback function is a function before it is called. In fact, Javascript does not care about how many arguments are passed or what their type is, everything is simply reset when the function is called, and it depends on the argument processing function.

For example, in many enumerated methods, they come back to you (index, value, array) . It doesn't matter if your function searches for these values ​​or assigns them a temporary variable, they are still passed. Both a.forEach(function(index){}) and a.forEach(function(){}) really have access to all 3 mentioned variables.

0
source

You can do something similar to find the type of arguments passed:

 var myVar; Object.prototype.toString.call(myVar); 

and it will return "[object Undefined]"

the same for other use cases, for example, if myVar is a string, as shown below:

 var myVar = 'It is a string'; Object.prototype.toString.call(myVar); 

it will retrieve "[object String]"

0
source

Source: https://habr.com/ru/post/1269917/


All Articles