Why is my variable not rising?

I have a global variable i that I am incrementing (see script here ):

 (function increment() { i += 1; })(); i = 0; 

Uncaught ReferenceError: i is not defined error message appears in Chrome

Should I not place the variable i here, so that inside the function increment variable i is defined as undefined ?

+4
source share
1 answer

Operations with variable declarations go up. You do not have a declaration.

The declaration statement uses var to declare a variable. Since you have not announced this, all you have is an assignment expression that implicitly creates a global variable during the evaluation of the expression.

In other words, no formal declaration means a lift.


Now let's say that you officially announced this by allowing the declaration of a variable. An operation inside IIFE will result in NaN , but will be overwritten by a subsequent assignment of 0 .

This is due to the fact that only the announcement is announced, not the appointment.

 // The 'var i' part below is actually happening up here. (function increment() { i += 1; // "i" is declared, but not assigned. Result is NaN })(); var i = 0; // declaration was hoisted, but the assignment still happens here console.log(i); // 0 
+7
source

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


All Articles