Javascript: two outputs when var keyword is not used

In this example, Google Chrome and Firebug give me two different outputs.

if b becomes global, first you need to give me undefined and second 14. right? but in firebug it gives two 14s, and Chrome gives a reference error.

function a() { b = 14; } console.log(b); a(); console.log(b); 
+5
source share
2 answers

Do not use the browser console for volume experiments. Different browser consoles run your code differently.

If you run this code in exactly the same way as in a regular environment, correctly, you will get a ReferenceError from the first line of console.log(b) :

 function a() { b = 14; } console.log(b); // ReferenceError a(); console.log(b); 

Even in free mode, trying to read the value of an undeclared identifier is a ReferenceError .

If we remove the original console.log , we will be in an area that varies depending on the free and strict mode:

 // In loose mode function a() { b = 14; } a(); console.log(b); // 14 

With the horror of implicit globals, 1 in free mode, assigning an undeclared identifier creates a global variable.

Vs.

 // In strict mode "use strict"; function a() { b = 14; // ReferenceError } a(); console.log(b); 

... how it should be.


1 This post is on my anemic little blog.

+6
source

The first console.log() should give a ReferenceError, because the variable is not defined at this time. If it behaves differently in Firebug, then this is a bug in Firebug.

+3
source

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


All Articles