Local and global variables inside the Javascript function

I am studying JS global and local variables, but I am confused about this particular function.

var text = "top"; function print() { return (text); } print(); //returns 'top' 

I understand why he returns to the top. var text is a global variable. print() has access to it and returns text , thereby returning 'top' .

 var text = "top"; function print() { return (text); var text = "bottom"; } print(); // returns undefined 

I have a basic knowledge of global and local variables (or so I thought). I know that the print function has access to its local plus global variables.

I do not understand why this returns undefined . As I understand it, the string return text; retrieves the global variable text , to which it has access (as shown in the first block of code). After returning text = 'top' it also declares its own local variable with the same name but with a different value of 'bottom' . The local variable bottom , as far as I know, should sit there, because it was not called before.

Why didn't he show top (or even show bottom ), but instead show undefined ?

+6
source share
4 answers

Javascript raises your variable declaration so that your code is functionally as follows:

 var text = "top"; function print() { var text; return (text); // unreachable code below text = "bottom"; } print(); // returns undefined 

Since text , as stated in your function, is not yet defined when you press return(text) , and text="bottom" not available, print() returns undefined

See What is a variable scope in Javascript for more information. This question relates to case 7.

+6
source

This is due to the movement of variables

The code in your second example runs in the following order:

  • Declare a global variable text
  • Set the value of the global variable text to "top"
  • Declare a print function
  • print call function
  • Declare a local variable text (due to a raise)
  • The return value of the local variable text ( undefined at this point)
  • Set the value of the local variable text to "bottom"

It is executed as if it were written as follows:

 var text = "top"; function print() { var text; return (text); text = "bottom"; } print(); 

As you can see, the value of text returned before the actual definition, and therefore it is undefined .

+2
source

This is because of the hosting.

hoisting teaches that variable and function declarations physically move at the top of your coding

You can get samples and explanations here.

0
source

Your appointment:

 var text = "bottom"; 

appears after the return function so it is not correct, this is an unreachable statement

 var text = "top"; function print() { return (text); //var text = "bottom"; //the above assignment comes after a return function //so it is not proper, it is unreachable statemen } alert(print()); // returns undefined 
-one
source

All Articles