Why the result is 'scope is not defined' - javascript

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.

Related

JS variable hoisting inside closure

JS hoists all variables within scope so why does this code throw an exception:
(function() {
function i() {
console.log(a.a);
}
i();
var a = { a:1 };
})()
While this one works:
(function() {
var a = { a:1 };
function i() {
console.log(a.a);
}
i();
})()
What behavior of interpreter causes this?
The variable a is already visible, but its value {a:1} is not assigned until the var is reached by the execution. Things are somewhat different for local functions declared with function foo(){...} because the names are bound to the respective functions/closures before the execution starts.
If you call the closure i before assigning a a value you get the problem, however with
(function(){
function i(){
console.log(foo());
}
i();
function foo() { return 42; }
})();
the output is 42 and there's no error.
Note that this is true because the function statement is used... changing the code to
(function(){
function i(){
console.log(foo());
}
i();
var foo = function(){ return 42; }
})();
gives an error because in this case when i() is executed foo is not yet bound to the function (like in your case).

calling a function from its string name on Window object

Why is the test fuction declaration not found in the window object? Thanks
!function(){
function test(){
console.log("testing");
}
var check = window["test"]
console.log(check); //undefined
}();
Since function test() is local to the scope of the toplevel function expression, it's not bound to window, the global scope. You can refer to it as a local variable:
!function() {
function test() {
console.log('testing')
}
console.log(test)
}()
Or bind it directly to window for a global variable:
!function() {
window.test = function test() {
console.log('testing')
}
var check = window['test']
console.log(check)
}()
You cannot access the local scope as a variable - see this question for more details.

Javascript- Variable Hoisting

This is a simple snippet, I just dont understand something.
The below code outputs 12, I understand that, because the var foo = 12; replaces the previous declaration of the variable.
<script>
var foo = 1;
function bar(){
if (!foo) {
var foo = 12;
}
alert(foo);
}
bar();
</script>
In the below code, it alerts 1 , which means the variable declared outside the function is accessible inside the function.
<script>
var foo = 1;
function bar(){
alert(foo);
}
bar();
</script>
But, in the below code, why it alerts undefined ?? I thought, it will alert 1, I am just assigning the previously declared variable to the new one.
<script>
var foo = 1;
function bar(){
if (!foo) {
var foo = foo;
}
alert(foo);
}
bar();
</script>
Variable declarations are pushed to the start of the function.
Therefore in reality the following is happening:
function bar(){
var foo;
if (!foo) {
foo = foo;
}
alert(foo);
}
Therefore you would need to change this to use window.foo so that you're referring to the global property rather than the function's property:
var foo = 1;
function bar(){
var foo;
if (!window.foo) {
foo = window.foo;
}
alert(foo);
}
bar();
Hoisting is slightly tricky. Function declarations are hoisted with the function assignment, but variable declarations are hoisted without the variable assignment. So the execution order of code is actually:
var foo;
var bar = function bar(){
var foo; // undefined
if (!foo) { // true
foo = foo; // foo = undefined
}
alert(foo);
}
foo = 1;
bar();
You could either use window.foo if you want to refer to the global variable foo, or better, just use a different variable name:
var foo = 1;
function bar(){
var baz = foo;
alert(baz);
}
bar();
The below code outputs 12, I understand that, because the var foo =
12; replaces the previous declaration of the variable.
var foo = 1;
function bar(){
if (!foo) {
var foo = 12;
}
alert(foo);
}
bar();
You are right because local variable overriding the global one.
In the below code, it alerts 1 , which means the variable declared
outside the function is accessible inside the function.
var foo = 1;
function bar(){
alert(foo);
}
bar();
You are correct. foo is declare in global scope so is accessible fron anywhere.
But, in the below code, why it alerts undefined ?? I thought, it will
alert 1, I am just assigning the previously declared variable to the
new one.
var foo = 1;
function bar(){
if (!foo) {
var foo = foo;
}
alert(foo);
}
bar();
This is a bit different. You are declaring a global variable and a local one with the same name. When your JavaScript program execution enters a new function, all the variables declared anywhere in the function are moved (or elevated, or hoisted) to the top of the function.
Another example:
var a = 123;
function f() {
var a; // same as: var a = undefined;
alert(a); // undefined
a = 1;
alert(a); // 1
}
f();
In javascript, until the ES5 specification, the scope is implemented only in terms of function body. The concept of block scope doesn't exist (really, will be implemented in the next javascript with the let keyword).
So, if you declare a variable var something; outside from function body, it will be global (in browsers global scope is the scope of the window object).
global variables
var something = 'Hi Man';
/**
* this is equal to:
**/
window.something = 'Hi Man';
If your code doesn't run in strict mode, there is another way to declare a global variable: omitting the var keyword. When the var keyword is omitted the variable belongs (or is moved) to the global scope.
example:
something = 'Hi Man';
/**
* this is equal to:
**/
function someFunction() {
something = 'Hi Man';
}
Local Variables
Because the non-existence of block scopes the only way to declare a local variable is to define it in a function body.
Example
var something = 'Hi Man'; //global
console.log('globalVariable', something);
function someFunction() {
var something = 'Hi Woman';
console.log('localVariable', something);
/**
* defining variable that doesn't exists in global scope
**/
var localSomething = 'Hi People';
console.log('another local variable', localSomething);
}
someFunction();
console.log('globalVariable after function execution', something);
try {
console.log('try to access a local variable from global scope', localSomething);
} catch(e) { console.error(e); }
As you can see in this example, local variables don't exist outside from their scope. This means another thing... If you declare, with the var keyword, the same variable in two different scopes you'll get two different variables not an override of the same variable (name) defined in the parent scope.
If you want to "override" the same variable in a child scope you have to use it without the var keyword. Because of the scope chain if a variable dosn't exist in a local scope it will be searched on their parent scope.
Example
function someFunction() {
something = 'Hi Woman';
}
var something = 'Hi Man';
console.log(1, 'something is', something);
someFunction();
console.log(1, 'something is', something);
Last thing, variable hoistment.
As I wrote below, at the moment, there isn't any way to declare a variable in some point of your code. It is always declared at the start of it scope.
Example
function someFunction() {
// doing something
// doing something else
var something = 'Hi Man';
}
/**
* Probably you expect that the something variable will be defined after the 'doing
* something else' task, but, as javascript works, it will be defined on top of it scope.
* So, the below snippet is equal to:
**/
function someFunction1() {
var something;
// doing something
// doing something else
something = 'Hi Man';
}
/**
* You can try these following examples:
*
* In the someFunction2 we try to access on a non-defined variable and this throws an
* error.
*
* In the someFunction3, instead, we don't get any error because the variable that we expect to define later will be hoisted and defined at the top, so, the log is a simple undefined log.
**/
function someFunction2() {
console.log(something);
};
function someFunction3() {
console.log('before declaration', something);
var something = 'Hi Man';
console.log('after declaration', something);
}
This happens because in javascript there are two different steps of a variable declaration:
Definition
Initialization
And the function3 example becomes as following:
function3Explained() {
var something; // define it as undefined, this is the same as doing var something = undefined;
// doing something;
// doing something else;
something = 'Hi Man';
}
IMHO it doesn't have anything to do with function declaration and hoisting ,
declaring the var with var inside function you are creating a variable in the function's isolated scope, this is why you get undefined.
var foo = 1;
function funcOne() {
var foo = foo;
alert('foo is ' + foo);
};
funcOne();
var bau = 1;
function funcTwo() {
bau = bau;
alert('bau is ' + bau);
};
funcTwo();
fiddle

Lexical scope in javascript function

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.

Local and global scope of variables in JavaScript

I have tried reading other posts on the subject but no luck yet. In this code below why doesnt f2() have access to the var defined in f1(). Is not the var "name" a global to the function f2()? Should not f2() see the var "name"?
function f1() {
var name = "david";
function f2() {
document.writeln(name);
}
document.writeln(name);
}
f2(); // does not write out "david".
your f2() is only defined inside f1() scope. you can't call it globally
Javascript is function level scoped, not block scoped. A function has access to it's parent's function variables but not to variables defined in functions within it. You could return f2 from f1 and call it that way
function f1() {
var name = "david";
document.writeln(name);
return f2
function f2() {
document.writeln(name);
}
}
var f2 = f1();
f2();
You need to read up on Javascript Closures.
Here is a version of your snippet which demonstrates how you can access variables from outer function in an inner function (if you want to call inner function globally).
function f1()
{
var name = "david";
return function()
{
console.log(name);
}
}
var f2 = f1();
f2();

Categories

Resources