Understanding javascript scope of functiond [duplicate] - javascript

This question already has answers here:
Understanding JavaScript function scoping
(4 answers)
Closed 9 years ago.
I am new to js and playing around with simple code. When I run the following code
var x=5;
function sum(){
alert(x);
var x=10;
alert(x);
}
sum();
I am getting the alert as "undefined" and 10.
But when I am running the following code,
var x=5;
function sum(){
alert(x);
x=10;
alert(x);
}
sum();
I get the alerts as "5" and "10"
Can someone please explain what is happening?
Note: sorry for giving the same code twice. Have changed now :).
Thanks

The function you have provided is being affected by hoisting. When you declare a local variable it is hoisted to the top of the function, which leaves x undefined.
When the interpreter encounters the function it hoists the local variable x like:
var x=5;
function sum(){
var x;
alert(x); //local x is in scope and undefined
x=10;
alert(x);
}
sum();
In the second function you provide, no hoisting occurs because there is only one global variable x and the function alerts the global variable with its assigned value.
So the main difference between the two functions is that the first function uses two variables, a global variable and a local variable, while the second function uses one global variable. In the first function the local variable is hoisted to the top of the function causing it to output undefined for the first alert.

Related

What if we console a variable just before declare it [duplicate]

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 4 years ago.
What is the difference between the following two cases:
CASE 1:
console.log(c); //console : undefined
var c;
CASE 2:
console.log(c); //console : Uncaught ReferenceError: c is not defined
Why in Case 1 it console undefined? as it was declare after console.log(). At that time variable c is also not defined than why program console undefined
Please check docs for var statement in MDN
variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.
So, in first example variable has been declared, but was not defined (even with var c = 1; before that row it would be not defined). In the second example, it was not declared at all.

Javascript -What happens if a variable and a function have the same name? [duplicate]

This question already has answers here:
Function and variable with the same name
(2 answers)
Closed 5 years ago.
Might be a kind of easy question, but I have a question on the issue of having the same name for a variable and a function.
If there's a variable,
var add = 1;
and a function,
function add(x,y) {return x+y;}
and there're two console.log,
console.log(add)
console.log(add(1,2))
I've expected those 2 console.log would work properly since add contains the Number and add() is classified as a Function, but the second one prints an error. So they aren't considered the same.
But the result says I'm wrong.
Can anyone explain what's going on in my code?
Variables and function definitions(not expressions) are hoisted to up, it means that wherever in scope you wrote your function or variable they will be moved to the start of the scope. First goes functions definitions then variables. So it means that functions will be overwritten by variables.
var add = 1;
function add(x,y) {return x+y;}
console.log(add);
The order doesn't matter. Later will be the variable and will overwrite
function add(x,y) {return x+y;}
var add = 1;
console.log(add);

Javascript function declaration - different behaviour? [duplicate]

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 5 years ago.
By trying to override a function I occurred in this odd behaviour. I hope to find an answer after having searched and read about function declaration methods without success.
In a script, if I declare this
var someFunction = function(){
alert("a");
}
someFunction();
someFunction = function(){
alert("b");
}
By calling someFunction I will have an output of "a"
But if I declare the two functions in this way
function someFunction(){
alert("a");
}
someFunction();
function someFunction(){
alert("b");
}
My output will be "b"
What is the difference here? I understand the first example is assigning to a variable an anonymous function. But the second example is totally unexpected and new to me.
I tested on all browsers and the output is the same.
The difference is the fact you are calling an anonymous function in the first example, Javascript gets evaluated top to bottom. In the case of an anonymous function it isn't actually executed UNTIL it is called later on.

How exactly works the Javascript variable scope? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 7 years ago.
I am pretty new in JavaScript and I have some doubts related to the variable scope.
So I tryed to do this example:
function outer() {
alert("INTO outer()");
var val1 = 1;
inner();
alert(val2);
}
function inner() {
alert("INTO inner()");
val2 = 2;
}
outer();
In this simple example the outer() function is perform, in this function I call the inner() function that declare and initializes the val2 variable. Then come back to the outer() function and from here I access and print the val2 value.
So it seam to me that in Javascript I can access to the variable defined in the inner function from the outer function but I can't access to the variable declared in the outer function from the inner function.
Is it true? If it is true why this choose?
It is true..The use of var in function 'outer' makes val1 local variable whereas val2 of function 'inner' has global scope since the keyword var is not used.
The declaration in your "inner" function is missing the var keyword. That makes val2 a global symbol.

Javascript variable declaration, why is this legal? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.

Categories