Lexical scope in javascript function - javascript

The following snippet:
a = 0;
function f1() {
a = 1;
f2();
}
function f2() {
return a;
}
f1();
returns undefined.
From what I understand, functions get access to variables when they're defined, and access the values of those variables when they're being executed. So, in this case I would've guessed f2 to have access to the global variable 'a', and read it's modified value (1). So why is it undefined?

You're not returning the result of the invocation of f2(), or anything else, in the f1 function, so f1 is correctly returning undefined.

Perhaps what you were after was the following:
a = 0; // variable a defined in the global scope and set to 0
function f1() {
a = 1; // since a is declared without var,
// sets the value of global variable a to 1
return f2();
}
function f2() {
return a; // since a was not declared with var,
// return a from the global scope
}
alert(f1()); // displays the computed value 1 of a
Regards.

Related

Why the result is 'scope is not defined'

I want to know why the result is scope is not defined
function checkscope() {
var scope = "local scope";
function f() {
console.log(scope);
scope = '123' //为什么这里不是全局变量scope,最后结果为什么是scope is not defined
}
return f;
}
var foo = checkscope();
console.log(foo());
console.log(scope)// 结果是scope is not defined
Because you have defined it out of scope i.e. functional scope.
Please define it out of the function scope. So whenever you call your function. The scope value will be changed.
var scope;
function checkscope() {
scope = "local scope";
function f() {
console.log(scope);
scope = '123' //为什么这里不是全局变量scope,最后结果为什么是scope is not defined
}
return f;
}
var foo = checkscope();
console.log(foo());
console.log(scope)/
scope is declared in the function checkscope. It ceases to exist with the } ending that function.
Thus it no longer exists at the point you use it.

Creating global variables inside function - why does this work?

As far as I know variables declared inside a function are local variables (using var keyword or not).
If so then why does this output 5? Shouldn't I get a ReferenceError when calling func2 because x is only known to func1?
<script>
function func1(){
x = 5;
}
function func2(){
document.write(x);
}
func1();
func2();
</script>
Afaik, variables declared inside a function are local variables (using var keyword or not).
Variables declared inside a function are local, but you are not declaring any variables. What you have is what's known as an "implicit global" and it only works in "sloppy mode".
From MDN:
Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.
In strict mode, your code produces an error:
"use strict";
function func1() {
x = 5;
}
function func2() {
document.write(x);
}
func1();
func2();
It is because you did not define it as
function func1(){
var x = 5;
}
This means that JS will use the global variable x which does not exist, but will when you run func1.
The addition of the "var" defines the variable within the local scope of func1.
function func1(){
x = 5;
}
is equivalent to
var x; // In global scope
function func1(){
x = 5;
}
As the variable was not scoped to func1 with a declaration.
If this was the case, then you would come across an error in the console since you are trying to access a variable that is not defined yet.
function func1(){
var x = 5;
}
"use strict";
function func1() {
window.x = 5;
}
function func2() {
document.write(x);
}
func1();
func2();

Global variable undefined - scope issue

When running the following code, I expected the alert at the end of the function to use the globally defined variable value for "a" (1), but it instead returns undefined. If the code within the if block is never run, why does the the variable "a" return as undefined?
var a = 1;
four();
function four() {
if (false) {
var a = 4;
}
alert(a); //alerts undefined
}
Does the javascript parser "see" the variable declaration within the scope of a conditional expression in the same way that it would "see" it outside of that?
Since variable declarations are 'hoisted' to the top of their scope, the second var a is being set inside of the function scope. so essentially it's turning into something like:
function four() {
var a;
if (false) {
a = 4;
}
alert(a); //alerts undefined
}
if you were to remove the second assignment within the four function you would alert the window.a variable rather than the four.a one.
ie:
var a = 1;
function four() {
if (false) {
a = 4;
}
alert(a); //alerts 1
}
Yes.
All Javascript variable (and function) declarations are "hoisted" to their containing function.
The a local variable exists throughout your function (even before the if), but will only have a value after it's assigned.

trouble understanding javascript function level scope

I have trouble understanding JavaScript function level scope, as a C# programmer it looks wired to me, I will try to explain it through code:
CODE#1
//Problem
//if same named variable (as in global scope) is used inside function scope,
//then variable defined inside function will be used,global one will be shadowed
var a = 123;
function func() {
alert(a); //returns undefined,why not just return 123 ?
//how come js knew that there is variable 'a' will be defined and used in
//this function scope ,js is interpreter based ?
var a = 1; //a is defined inside function
alert(a); //returns 1
}
func();
CODE#2
//when a variable(inside function) not named as same as the global,
//then it can be used inside function,and global variable is not shadowed
var k = 123;
function func2() {
alert(k); //returns 123 ,why not 'undefined'
var c = 1;
alert(c); //returns 1
}
func2();
So my questions are
in CODE#1 why first time a is undefined,why not it's just return 123? And how
come js knew that there is variable 'a' will be defined and used in
this function scope, js is interpreter based?
in CODE#2 why not k is 'undefined'?
http://jsfiddle.net/Nu2Vu/
CODE #1
Hoisting causes all variable declarations to be brought to the top of the scope, but it leaves the assignment where it is. When there is a reference to a variable JavaScript will first look in the current scope, if it doesn't find the variable it will continue to look up the scope chain until if finds the variable.
This code is interpreted something like this:
var a = 123; // global var named a declared, assigned a value
function func() {
var a; // the declaration of the local var a gets
// hoisted to the top of the scope, but the
// assignment is left below, so at the point
// it is initialized with a value of `undefined`
alert(a); // looks for a local var named a, finds it but
// it currently has a value of `undefined`
a = 1; // now the value is assigned to the local a
alert(a); // returns 1
}
func();
CODE #2
This code behaves the way it does because of closure.
A basic definition of closure is that JavaScript functions have access not only to variables defined in their own scope, they can also access variables available to their parent scope.
var k = 123; // declares and assigns a value to global k
function func2() {
alert(k); // looks for a local var named k, doesn't find it,
// looks in its parent scope (the global scope in
// this case) finds k, returns its value of 123
var c = 1;
alert(c); //returns 1
}
func2();
The first code is equal to this:
var a = 123;
function func() {
var a; //Undefined!
alert(a);
a = 1;
alert(a);
}
This explains it pretty well:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var

Puzzled by this JavaScript code snippet

For this snippet, I'm not surprised global variable 'a' evaluates to be 5.
http://jsfiddle.net/MeiJsVa23/gZSxY/ :
var a = 10;
function func(){
a = 5;
}
func(); // expect global variable 'a' to be modified to 5;
alert(a); // and this prints out 5 as expected. No surprise here.
​
But how come for this code snippet, global variable 'a' evaluates to be 10 and not 5? It's as if the a = 5 never happened.
http://jsfiddle.net/MeiJsVa23/2WZ7w/ :
var a = 10;
function func(){
a = 5;
var a = 23;
}
func(); // expect global variable 'a' to be modified to 5;
alert(a); // but this prints out 10!! why?
​
This is due to variable hoisting: anything defined with the var keyword gets 'hoisted' to the top of the current scope, creating a local variable a. See: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
So, there are two things are going here: hoisting and shadowing.
Because the first one, variable declarations are "hoisted" to the top, so your code is equivalent to:
var a = 10;
function func(){
var a;
a = 5;
a = 23;
}
And because the second one, you're "shadowed" the global variable a with a local ones, so the changes are not reflected to the global a.
This is called "variable hoisting". var declarations (and function() declarations) are moved to the top of their scope.
This has to do with hoisting.
In the function, a local variable with the same name is declared. Even though it happens after your modification, it is deemed to have been declared before it - this is called hoisting.
Local variables hoist for declaration but not value. So:
function someFunc() {
alert(localVar); //undefined
var localVar = 5;
}
Functions, if declared with function name() {... syntax, hoist for both declaration and value.
function someFunc() {
alert(someInnerFunc()); //5
function someInnerFunc() { return 5; }
}
var a = 10; //a is 10
function func(){
a = 5; //a is 5
var a = 23; // a is now in local scope (via hoisting) and is 23
}
func();
alert(a); // prints global a = 10
Presumably, the statement var a = 23 creates a local variable for the whole scope. So the global a is shadowed for the entirety of func(), not just for the lines below the statement. So in your second snippet, a = 5 is assigning to the local variable declared below.

Categories

Resources