Javascript review and upgrade function

I just read a great article about Ben Cherry's Scoping and Hoisting JavaScript in which he gives the following example:

var a = 1; function b() { a = 10; return; function a() {} } b(); alert(a); 

Using the code above, the browser will warn "1".

I'm still not sure why it returns "1". Some of the things he talks about are reminiscent of: All function declarations go up. You can use a variable with a function. Still not pushing me.

+84
javascript scope hoisting scoping
Sep 21 '11 at 9:23 a.m.
source share
16 answers

Raising a function means that the functions move to the top of their area. I.e

 function b() { a = 10; return; function a() {} } 

will be rewritten by the interpreter on this

 function b() { function a() {} a = 10; return; } 

Strange, huh ??

Also in this case

 function a() {} 

behaved the same way

 var a = function () {}; 



So, essentially, this is what the code does:

 var a = 1; //defines "a" in global scope function b() { var a = function () {}; //defines "a" in local scope a = 10; //overwrites local variable "a" return; } b(); alert(a); //alerts global variable "a" 
+111
Sep 21 '11 at 21:33
source share

What you need to remember is that it analyzes the entire function and allows all variable declarations before executing it. So....

 function a() {} 

really getting

 var a = function () {} 

var a causes it to move to the local area, and the scope of the variable through the entire function, so the global variable remains equal to 1, since you declared it in the local area, making it a function.

+6
Sep 21 2018-11-21T00:
source share

Function a is inside function b :

 var a = 1; function b() { function a() {} a = 10; return; } b(); alert(a); 

which is almost like using var :

 var a = 1; function b() { var a = function () {}; a = 10; return; } b(); alert(a); 

The function is declared locally, and the installation of a occurs only in the local scope, and not in the global var.

+5
Sep 21 '11 at 21:30
source share
  • Function declaration function a(){} is executed first, and it behaves like var a = function () {}; therefore in the local area a is created.
  • If you have two variables with the same name (one in the global another in the local), the local variable always takes precedence over the global variable.
  • When you set a=10 , you set the local variable a , not the global one.

Consequently, the value of the global variable remains the same, and you get, warned 1

+3
May 17 '14 at 13:43
source share

function a() { } is a function statement that creates a variable local to function b .
Variables are created when the function is analyzed, regardless of whether the var or function statement is executed.

a = 10 sets this local variable.

+1
21 Sep '11 at 9:29 a.m.
source share

Ascent is a concept made for us to make it easier to understand. In fact, it happens that the announcements are executed first in relation to their areas, and the assignments will be executed after that (not at the same time).

When declarations appear, var a , then function b and inside this region b , function a declared.

This function a obscures the variable a coming from the global scope.

After the declarations are completed, the assignment of values ​​will begin, the global a will get the value 1 , and a inside the function b will get 10 . when you do alert(a) , it will call the actual global scope variable. This small code change will make it more understandable.

  var a = 1; function b() { a = 10; return a; function a() { } } alert(b()); alert(a); 
+1
Apr 14 '15 at 14:40
source share

scpope and close and raise (var / function)

  • scpope: global var can be accessed anywhere (entire file area), local var can only be accessed by local scope (function / block scope)!
    Note: if the local variable is not used var keywords in the function, it will become a global variable!
  • : an internal function is another function accessed by a local scope (parent function) and a global scope, howerver it vars cannot be accessed by others! if you do not return it as a return value!
  • hoisting: move all declare / declare vars / function to the area above, than assign a value or null!
    Note: it just moves the declaration, not the value!

 var a = 1; //"a" is global scope function b() { var a = function () {}; //"a" is local scope var x = 12; //"x" is local scope a = 10; //global variable "a" was overwrited by the local variable "a" console.log("local a =" + a); return console.log("local x = " + x); } b(); // local a =10 // local x = 12 console.log("global a = " + a); // global a = 1 console.log("can't access local x = \n"); // can't access local x = console.log(x); // ReferenceError: x is not defined 
+1
Dec 17 '16 at 14:25
source share

What is the essence of this small piece of code?

Case 1:

Include the definition of function a(){} inside the body of function b as follows. logs value of a = 1

 var a = 1; function b() { a = 10; return; function a() {} } b(); console.log(a); // logs a = 1 

Case 2

Exclude function a(){} definition inside the body of function b as follows. logs value of a = 10

 var a = 1; function b() { a = 10; // overwrites the value of global 'var a' return; } b(); console.log(a); // logs a = 10 

Observation will help you understand that the console.log(a) statement logs the following values.

Case 1: a = 1

Case 2: a = 10

postulates

  • var a been defined and declared lexically in the global scope.
  • a=10 This operator reassigns the value 10, it is lexically located inside the function b.

Explanation of both cases

Due to function definition with name property a is similar to variable a . variable a inside function body b becomes a local variable. The previous line assumes that the global value of a remains intact, and the local value of a is updated to 10.

So, we intend to say that the code is below

 var a = 1; function b() { a = 10; return; function a() {} } b(); console.log(a); // logs a = 1 

It is interpreted by the JS interpreter as follows.

 var a = 1; function b() { function a() {} a = 10; return; } b(); console.log(a); // logs a = 1 

However, when we delete function a(){} definition , value of 'a' declared and defined outside function b, this value is overwritten, and it changes to 10 in case 2. The value is overwritten, since a=10 refers to the global declaration , and if it must be declared locally, we must write var a = 10; .

 var a = 1; function b() { var a = 10; // here var a is declared and defined locally because it uses a var keyword. return; } b(); console.log(a); // logs a = 1 

We can clarify our doubts by changing the name property in function a(){} definition to a different name than 'a'

 var a = 1; function b() { a = 10; // here var a is declared and defined locally because it uses a var keyword. return; function foo() {} } b(); console.log(a); // logs a = 1 
+1
Apr 20 '17 at 16:26
source share

This is due to the fact that the variable name matches the function name "a". Thus, due to Javascript hoisting, it is trying to resolve the name conflict and it will return a = 1.

I, too, was confused until I read this post in the "Raising JavaScript" section http://www.ufthelp.com/2014/11/JavaScript-Hoisting.html

Hope this helps.

0
Nov 16 '14 at 12:55
source share

Here is my answer answer with more annotation and an acoustic game to play with.

 // hoisting_example.js // top of scope ie. global var a = 1 var a = 1; // new scope due to js' functional (not block) level scope function b() { a = 10; // if the function 'a' didn't exist in this scope, global a = 10 return; // the return illustrates that function 'a' is hoisted to top function a(){}; // 'a' will be hoisted to top as var a = function(){}; } // exec 'b' and you would expect to see a = 10 in subsequent alert // but the interpreter acutally 'hoisted' the function 'a' within 'b' // and in doing so, created a new named variable 'a' // which is a function within b scope b(); // a will alert 1, see comment above alert(a); 

https://jsfiddle.net/adjavaherian/fffpxjx7/

0
May 09 '16 at 18:41
source share

Long mail!

But it will clean the air!

The way Java Script works is that it includes a two-step process:

  • Compilation (so to speak). This step registers the declarations of variables and functions and their corresponding scope. This is not related to evaluating a function expression: var a = function() {} or a variable expression (for example, assigning 3 x in the case of var x = 3; which is nothing more than evaluating the RHS part.)

  • Interpreter: this is part of the performance / assessment.

Check the output below the code to understand:

 //b()   ! //c ()    . console.log( "a is" + a); console.log( "b -" + b); console.log( "c is" + c); var a = 1; console.log( ", a " + a); var c = function() {}; console.log( " c " + c);  b() { //     : //console.log(e); //  e  . e = 10;// Java-           ,             10   . console.log( "e is" + e) ​​//! console.log( "f " + f); var f = 7; console.log( " f " + f); console.log( "d is" + d); ;  d() {} } (); console.log();> 

Lets break it:

  • At the compilation stage, "a" will be registered in the global scope with the value " undefined ". The same goes for " c ", its value at this moment will be " undefined ", not " function() "). ' b ' will be registered as a function in the global area. Inside region b , ' f ' will be registered as a variable that is not currently defined, and function ' d ' will be registered.

  • When the interpreter starts, the declared variables and function() (rather than expressions) may be available before the interpreter reaches the line of the actual expression. Thus, the variables will be printed " undefined ", and the anonymous function may be called earlier. However, trying to access an undeclared variable before its initialization of the expression results in an error, for example:

  console.log(e) e = 3; 

Now, what happens when you have a variable and function declaration with the same name.

The answer is that functions always go up to and if the same name variable is declared, it is considered as repeating and ignored. Remember, order doesn't matter. Functions always take precedence. But at the evaluation stage, you can change the link to the variable to anything (it saves everything that was the last assignment). Take a look at the code below:

  var a = 1; console.log( "a is" + a);  b() { console.log( "a   b " + a);//  'a'  ()   .     ,   "". a = 3;// console.log( "Now a is" + a); ;  a() {} } var a;//    . (); console.log( "a -" + a + "   );//   . 
0
Apr 21 '17 at 4:29 on
source share

Getting started in JavaScript means that variable declarations are executed through a program before any code is executed. Therefore, declaring a variable anywhere in the code is equivalent to declaring it at the beginning.

0
Feb 14 '18 at 22:13
source share

It all depends on the scope of the variable "a". Let me explain by creating areas like images.

Here JavaScript will create 3 areas.

i) Global reach. ii) Scope b (). iii) Function a () scope.

enter image description here

Clarity when you call the alert scope belongs to global time, so it will select the value of the variable a from the global scope only 1.

0
Feb 28 '18 at 15:51
source share

Lifting is the behavioral concept of JavaScript. Rising (say, moving) is a concept that explains how and where variables should be declared.

In JavaScript, a variable can be declared after it has been used, because function declarations and variable declarations always move ("rise") invisibly to the top of their scope using a JavaScript interpreter.

In most cases, we are faced with two types of lifting.

1. Variable declaration declaration

Let's look at this piece of code.

  a = 5; // Assign 5 to a elem = document.getElementById("demo"); // Find an element elem.innerHTML = a; // Display a in the element var a; // Declare a //output-> 5 

Here the declaration of the variable a will be displayed invisibly using the javascript interpreter at compile time. Thus, we were able to get the value of a. But this approach of variable declaration is not recommended, since we must declare variables from above just like this.

  var a = 5; // Assign and declare 5 to a elem = document.getElementById("demo"); // Find an element elem.innerHTML = a; // Display a in the element // output -> 5 

consider another example.

  function foo() { console.log(x) var x = 1; } 

actually interpreted like this:

  function foo() { var x; console.log(x) x = 1; } 

In this case, x will be undefined

It doesn't matter if the code that contains the variable declaration is executed. Consider this example.

  function foo() { if (false) { var a = 1; } return; var b = 1; } 

This function is such.

  function foo() { var a, b; if (false) { a = 1; } return; b = 1; } 

In a variable declaration, only tanks are used to define variables, and not an assignment.

  1. Function Declaration Confirmation

Unlike raising a variable, the function case or assigned value will also be raised. Consider this code

  function demo() { foo(); // this will give error because it is variable hoisting bar(); // "this will run!" as it is function hoisting var foo = function () { alert("this would not run!!"); } function bar() { alert("this will run!!"); } } demo(); 

Now that we understand how to drag and drop a variable and a function, let this code understand now.

 var a = 1; function b() { a = 10; return; function a() {} } b(); alert(a); 

This code will be like this.

 var a = 1; //defines "a" in global scope function b() { var a = function () {}; //defines "a" in local scope a = 10; //overwrites local variable "a" return; } b(); alert(a); 

The function a () will have a local area inside b (). a () will be moved to the beginning when interpreting the code with its definition (only in the case of raising the function), so now it will have a local scope and, therefore, will not affect the global while while having its own area inside the b () function,

0
May 01 '18 at 7:20
source share

Surprisingly, none of the answers given here mention the relevance of the execution context in the scope chain.

The JavaScript engine places the currently executing code in the execution context. The underlying execution context is the global execution context. Each time a new function is called, a new execution context is created and pushed onto the execution stack. Think of a stack stack located on a call stack in other programming languages. Last in the first came out. Now each execution context has its own environment variable and external environment in JavaScript.

I will use the example below as a demonstration.

1) First, we enter the phase of creating a global execution context. Both the external environment and the variable environment of the lexical environment are created. The global object is configured and placed into memory with a special variable "this" pointing to it. The function a and its code, as well as the variable myVar with an undefined value, are stored in memory in a global environment variable. It is important to note that the code function is not executed. It just fits in memory with function a.

2) Secondly, this is the execution phase of the execution context. myVar is no longer an undefined value. It is initialized with a value of 1, which is stored in a global environment variable. The function a is called and a new execution context is created.

3) In the "Execution Context" function, it goes through the phase of creating and executing its own execution context. He has his own external environment and a variable environment, that is, his own lexical environment. The function b and the variable myVar are stored in their environment variable. This environment variable is different from the global environment variable. Since the function a is lexically (physically in the code) at the same level as the global execution context, its external environment is the global execution context. Thus, if function a should refer to a variable that is not in its variable environment, it will search the chain of scopes and try to find the variable in the variable environment of the global execution context.

4) Function b is called in function a. A new execution context has been created. Since he is in function a lexically, his external environment is this. Therefore, when it refers to myVar, since myVar is not in function b of the Variable Environment, it will look in function Variable Environment. He finds it there, and console.log prints 2. But if the variable was not in the Variable Environment function, then since the Outer Environment function is a global execution context, the scope chain will continue to search there.

5) After completion of the execution of functions b and a, they are removed from the execution stack. The single-threaded JavaScript engine continues execution in the global execution context. It calls function b. But in the global environment of variables there is no function b, and there is no other external environment for searching in the global context of execution. Thus, the JavaScript engine throws an exception.

 function a(){ function b(){ console.log(myVar); } var myVar = 2; b(); } var myVar = 1; a(); b(); > 2 > Uncaught ReferenceError: b is not defined 

The following example shows a chain of scopes in action. In function b, the Runtime Context Variable Environment is missing myVar. Thus, he seeks his external environment, which is a function of a. Function a also does not have myVar in its variable. Thus, the Search Engine performs the function External Environment, which is the global External Environment of the execution context, and it defines myVar. Therefore, console.log prints 1.

 function a(){ function b(){ console.log(myVar); } b(); } var myVar = 1; a(); > 1 

Regarding the execution context and the associated lexical environment, including the external environment and the environment variable, it is possible to define variable areas in JavaScript. Even if you call the same function several times, for each call it will create its own execution context. Thus, each execution context will have its own copy of the variables in its environment of variables. There is no separation of variables.

0
Feb 13 '19 at 15:51
source share

As far as I know, the rise is done by declaring variables and functions, for example:

 a = 7; var a; console.log(a) 

What happens inside the JavaScript engine:

 var a; a = 7; console.log(a); // 7 

Or:

 console.log(square(7)); // Output: 49 function square(n) { return n * n; } 

It will become:

 function square(n) { return n * n; } console.log(square(7)); // 49 

But assignments such as variable assignment, function expression assignment will not be raised: For example:

 console.log(x); var x = 7; // undefined 

It could be like this:

 var x; console.log(x); // undefined x = 7; 
0
Aug 16 '19 at 15:14
source share



All Articles