Why does Chrome debugger get undefined when accessing variables in Closure? [duplicate] - javascript

This question already has answers here:
Why does Chrome debugger think closed local variable is undefined?
(7 answers)
Closed 4 years ago.
Code:
function test4() {
var x = 10;
var y = 100;
// inner referred x only
function inner () {
console.log(x);
debugger;
}
// inner2 referred y to make sure y is in the scope of inner
function inner2 () {
console.log(y);
}
return inner;
}
var foo = test4();
foo();
y is in the scope of inner even only inner2 which never been used refer to it. I checked the result in scope and x, y are there:
But when I checked variables in watch panel and console, I can't get all of them:
It's weird that y is in the scope but get not defined when using debugger.
So, is it means that debugger can not access variable that not used in current context even it's in the closure or it just a bug? (My chrome version is 51.0.2704.103 m)
It's similar to Why does Chrome debugger think closed local variable is undefined? but not the same. Because inner2 in my code make sure that y is in the closure. And actually my question is opposite to Louis's answer under that question.

You are a first-hand observer of the internal mechanics of scope-optimization. Scope optimization is checking to see which variables are used in the current scope and optimizing out access to unused variables. The reason for this is because in the machine code generated from JIT compilation of javascript, the whole concept of variable naming is lost. But, to maintain javascript compliance, the JIT compiler associates an array of used local variables to each javascript function. Observe the following code.
(function(){
"use strict";
var myVariable = NaN; // |Ref1|
var scopedOne = (function(){
var myVariable = 101; // |Ref2|
return x => x * myVariable;
})();
var scopedTwo = (function(){
var myVariable = -7; // |Ref3|
return x => x / myVariable;
})();
console.log("scopedOne(2): ", scopedOne(2));
console.log("scopedTwo(56): ", scopedTwo(56))
})();
As seen above, Javascript is a scoped stack-based language. If Javascript was not a scoped language, then the variables used in the functions would depend on the values of the variables at the location where the function was being executed. For instance, without a scope, scopedOne would use the value of myVariable at |Ref1| (NaN) instead of at |Ref2| (101) and would log NaN to the console. Back to the main point, in the machine code, when the debugger comes in, it can only figure out where the actual locations in memory are of the used variables since only those memory locations have persisted to machine code as only those variable have been used. The memory locations of the rest of the variables remain a mystery to it. As you have observed, this has the secondary side-effect of making unused variables in the scope "invisible" to that function. However, there is a solution.
To circumvent this problem, simply wrap the debugger; statement in an eval to force the browser to do an expensive variable lookup of all the variables in the scope. Basically, the browser has to go back to the original source code, examine it for the original names of the variables in the scope, and figure out where the values of the variables are stored by the JIT-generated machine code. Open up developer tools and run the snippet below. Then go to the prior level in the "Call Stack" panel and observe how the visibility of the value of the variable y changes from visible inside eval to invisible outside eval.
function test4() {
var x = 10;
var y = 100;
// inner referred x only
function inner () {
console.log(x);
eval("debugger;");
}
// inner2 referred y to make sure y is in the scope of inner
function inner2 () {
console.log(y);
}
return inner;
}
var foo = test4();
foo();

Related

Different handling of 'this' in Node.js and Browser

I have Node.js v8.10.0 locally installed. I wrote a simple script to play with 'this':
var x = 1;
var fn = function (a) {
var x = a;
console.log(`local x = ${x}`);
console.log(`global x = ${this.x}`);
}
fn(10);
When I execute script via Node.js I get following result:
local x = 10
global x = undefined
When I execute script in Chrome I get the following result:
local x = 10
global x = 1
Could you please explain to me, why Node.js doesn't see x in global scope?
Could you please explain to me, why Node.js doesn't see x in global scope?
It does, if you run it in Node console. If you run it in as a file, x is in the file's scope, not global scope.
By the way, in Node, you can use global to explicitly see the global scope, just like you'd use window in a browser. Thus,
console.log(global == this)
will give you two different answers depending on whether you run it in a file or in a console.
Also, try to migrate to let and const. This is extra confusing because var behaves differently in global scope and elsewhere. In console and in browser, your outer var x is in global scope, so it defines a global variable (window.x and global.x). In a Node file, var x is not in a global scope, so it does what it normally does when not in global scope: defines a local variable x (not this.x, not global.x, just x). Thus, you have two local variables, the inner one shadowing the outer one, which makes the outer one inaccessible. Meanwhile, this.x has never been defined.
In chrome this is a object of Window as if you do this.constructor.name you get Window as a constructor name so while accessing this.x it will look for the global variable x and does not reference to the function scope.
var x = 1;
var fn = function (a) {
var x = a;
console.log(`local x = ${x}`);
console.log('Constructor ', this.constructor.name);
console.log(`global x = ${this.x}`);
}
fn(10);
However, in NodeJS, this will always refer to the function prototype (not the global scope). Thus, you do not have any value x associated with the prototype of the function so it gives you undefined.

Access variable in if block

var func = function () {
var i: number = 0;
if (i == 0) {
var y: number = 1;
}
document.body.innerHTML = y.toString(); // js/ts should complain me in this line
};
func(); // output: 1
As you can see, I've declared variable y inside if block. So, I think it couldn't be referenced outside the scope.
But, when I've tried to run the code, the output is 1.
Is it an issue in typescript/javascript?
Variables in Javascript are hoisted, meaning that var y is moved to the top of the function as if it were declared there.
Initialization, however is not hoisted, so if you change i to be something other than 0, the variable y will still exist, but it will have the value undefined.
This means that the function is exactly equivalent to:
var func = function () {
var i: number = 0;
var y: number;
if (i == 0) {
y = 1;
}
document.body.innerHTML = y.toString(); // js/ts should complain me in this line
};
To get the behavior you expect, you need to use let, which is a part of ECMAScript 2015 (ES6). It is block scoped, as you expect. It will also effectively work so that it is accessible only from the point of definition onwards, which is also probably as you would expect.
If you re-declare a JavaScript variable, it will not lose its value.
The second reference might pave way for a new variable syntax. Actually if you recall variable declaration is not neccessary in javascript. Simpe
y=1;
also works.
The second time when you reference y, outside if block, in my opinion, it tries a re-declaration and retains the old value.
Reference - http://www.w3schools.com/js/js_variables.asp
& http://www.w3schools.com/js/js_scope.asp
Javascript has function scope afaik. Any variable declared within a function, should be accessible from anywhere within the function. So, if you have a function checking if i==0, then you can achieve what you are trying to achieve.
This is as it is supposed to be. Javascript scopes by function, not by block. (This does make it unlike many popular languages)
Variables declared like var myVar = 10; will seep into nested functions but not the other way around. Variables declared like myVar = 10; will go global.
I couldn't find anything which suggested that typescript was any different.
Variables declared inside of an if statement are not scoped to the if statement. They're scoped to the current execution context. There's the Global execution context and then when a function is run, it creates it's own execution context. Inside of your function, you created the variables y and i. It doesn't matter that y was created inside of the if statement, because once it runs, y is created in the scope of the function. So then you do y.toString(), which can access y because it's scoped to the function not the if statement. That's why you get the output of 1. This is not an error, it's by design.

How come no 'var' needed inside js function? [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 7 years ago.
Is "var" optional?
myObj = 1;
same as ?
var myObj = 1;
I found they both work from my test, I assume var is optional. Is that right?
They mean different things.
If you use var the variable is declared within the scope you are in (e.g. of the function). If you don't use var, the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches. It is then very similar to a global variable. However, it can still be deleted with delete (most likely by someone else's code who also failed to use var). If you use var in the global scope, the variable is truly global and cannot be deleted.
This is, in my opinion, one of the most dangerous issues with javascript, and should be deprecated, or at least raise warnings over warnings. The reason is, it's easy to forget var and have by accident a common variable name bound to the global object. This produces weird and difficult to debug behavior.
This is one of the tricky parts of Javascript, but also one of its core features. A variable declared with var "begins its life" right where you declare it. If you leave out the var, it's like you're talking about a variable that you have used before.
var foo = 'first time use';
foo = 'second time use';
With regards to scope, it is not true that variables automatically become global. Rather, Javascript will traverse up the scope chain to see if you have used the variable before. If it finds an instance of a variable of the same name used before, it'll use that and whatever scope it was declared in. If it doesn't encounter the variable anywhere it'll eventually hit the global object (window in a browser) and will attach the variable to it.
var foo = "I'm global";
var bar = "So am I";
function () {
var foo = "I'm local, the previous 'foo' didn't notice a thing";
var baz = "I'm local, too";
function () {
var foo = "I'm even more local, all three 'foos' have different values";
baz = "I just changed 'baz' one scope higher, but it's still not global";
bar = "I just changed the global 'bar' variable";
xyz = "I just created a new global variable";
}
}
This behavior is really powerful when used with nested functions and callbacks. Learning about what functions are and how scope works is the most important thing in Javascript.
Nope, they are not equivalent.
With myObj = 1; you are using a global variable.
The latter declaration create a variable local to the scope you are using.
Try the following code to understand the differences:
external = 5;
function firsttry() {
var external = 6;
alert("first Try: " + external);
}
function secondtry() {
external = 7;
alert("second Try: " + external);
}
alert(external); // Prints 5
firsttry(); // Prints 6
alert(external); // Prints 5
secondtry(); // Prints 7
alert(external); // Prints 7
The second function alters the value of the global variable "external", but the first function doesn't.
There's a bit more to it than just local vs global. Global variables created with var are different than those created without. Consider this:
var foo = 1; // declared properly
bar = 2; // implied global
window.baz = 3; // global via window object
Based on the answers so far, these global variables, foo, bar, and baz are all equivalent. This is not the case. Global variables made with var are (correctly) assigned the internal [[DontDelete]] property, such that they cannot be deleted.
delete foo; // false
delete bar; // true
delete baz; // true
foo; // 1
bar; // ReferenceError
baz; // ReferenceError
This is why you should always use var, even for global variables.
There's so much confusion around this subject, and none of the existing answers cover everything clearly and directly. Here are some examples with comments inline.
//this is a declaration
var foo;
//this is an assignment
bar = 3;
//this is a declaration and an assignment
var dual = 5;
A declaration sets a DontDelete flag. An assignment does not.
A declaration ties that variable to the current scope.
A variable assigned but not declared will look for a scope to attach itself to. That means it will traverse up the food-chain of scope until a variable with the same name is found. If none is found, it will be attached to the top-level scope (which is commonly referred to as global).
function example(){
//is a member of the scope defined by the function example
var foo;
//this function is also part of the scope of the function example
var bar = function(){
foo = 12; // traverses scope and assigns example.foo to 12
}
}
function something_different(){
foo = 15; // traverses scope and assigns global.foo to 15
}
For a very clear description of what is happening, this analysis of the delete function covers variable instantiation and assignment extensively.
var is optional. var puts a variable in local scope. If a variable is defined without var, it is in global scope and not deletable.
edit
I thought that the non-deletable part was true at some point in time with a certain environment. I must have dreamed it.
Check out this Fiddle: http://jsfiddle.net/GWr6Z/2/
function doMe(){
a = "123"; // will be global
var b = "321"; // local to doMe
alert("a:"+a+" -- b:"+b);
b = "something else"; // still local (not global)
alert("a:"+a+" -- b:"+b);
};
doMe()
alert("a:"+a+" -- b:"+b); // `b` will not be defined, check console.log
They are not the same.
Undeclared variable (without var) are treated as properties of the global object. (Usually the window object, unless you're in a with block)
Variables declared with var are normal local variables, and are not visible outside the function they're declared in. (Note that Javascript does not have block scope)
Update: ECMAScript 2015
let was introduced in ECMAScript 2015 to have block scope.
The var keyword in Javascript is there for a purpose.
If you declare a variable without the var keyword, like this:
myVar = 100;
It becomes a global variable that can be accessed from any part of your script. If you did not do it intentionally or are not aware of it, it can cause you pain if you re-use the variable name at another place in your javascript.
If you declare the variable with the var keyword, like this:
var myVar = 100;
It is local to the scope ({] - braces, function, file, depending on where you placed it).
This a safer way to treat variables. So unless you are doing it on purpose try to declare variable with the var keyword and not without.
Consider this question asked at StackOverflow today:
Simple Javascript question
A good test and a practical example is what happens in the above scenario...
The developer used the name of the JavaScript function in one of his variables.
What's the problem with the code?
The code only works the first time the user clicks the button.
What's the solution?
Add the var keyword before the variable name.
Var doesn't let you, the programmer, declare a variable because Javascript doesn't have variables. Javascript has objects. Var declares a name to an undefined object, explicitly. Assignment assigns a name as a handle to an object that has been given a value.
Using var tells the Javacript interpreter two things:
not to use delegation reverse traversal look up value for the name, instead use this one
not to delete the name
Omission of var tells the Javacript interpreter to use the first-found previous instance of an object with the same name.
Var as a keyword arose from a poor decision by the language designer much in the same way that Javascript as a name arose from a poor decision.
ps. Study the code examples above.
Everything about scope aside, they can be used differently.
console.out(var myObj=1);
//SyntaxError: Unexpected token var
console.out(myObj=1);
//1
Something something statement vs expression
No, it is not "required", but it might as well be as it can cause major issues down the line if you don't. Not defining a variable with var put that variable inside the scope of the part of the code it's in. If you don't then it isn't contained in that scope and can overwrite previously defined variables with the same name that are outside the scope of the function you are in.
I just found the answer from a forum referred by one of my colleague. If you declare a variable outside a function, it's always global. No matter if you use var keyword or not. But, if you declare the variable inside a function, it has a big difference. Inside a function, if you declare the variable using var keyword, it will be local, but if you declare the variable without var keyword, it will be global. It can overwrite your previously declared variables. - See more at: http://forum.webdeveloperszone.com/question/what-is-the-difference-between-using-var-keyword-or-not-using-var-during-variable-declaration/#sthash.xNnLrwc3.dpuf

if a function's lexical environment is created at the time the function is *defined*, then why can a free variable be declared *after* the function?

EDIT: thanks for the answers, I think I get it now. It requires an understanding of scope and hoisting. Below is a new example that I think illustrates both well:
var a = function (){
alert(x);
}
var x = 1;
(function(){
var x = 2;
a();
})();
The above alerts 1. Lexical scope is illustrated by the fact that this alerts 1 and not 2, and hoisting is illustrated by the fact that the "var x = 1" line comes after the declaration of a and definition of the anonymous function with the "alert(x)". Allegedly, hoisting means that the above is equivalent to the below (source: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html):
var x;
var a = function (){
alert(x);
}
x = 1;
(function(){
var x = 2;
a();
})();
So since x is effectively initialized before the function definition, the x in "alert(x)" is the same x that subsequently gets set to 1.
Since JS uses lexical scope, the line "var x = 2" does not override the x associated with a.
Is that about right?
---original question---
I've spent pretty much all day trying to figure this out. I've read a few articles on scope and closures in Javascript, but this still eludes me.
I'm told that a function's lexical environment is created when the function is defined, not when it is executed.
So if there is no variable called x declared anywhere in my program, then what is the closure environment for the anonymous function that a points to when I do this?:
var a = func(){
var y = 7; //just for illustrative purposes
alert(x);
});
My understanding is that an environment is a mapping of variable names to values...so it would be
y: 7
x: ?
Is that correct? The following code alerts "10":
(function (){
var a = function(){
alert(x);
};
var x = 10;
a();
})();
My guess would be that when a is called, the JS checks the closure environment for a mapping for x and finds none, and subsequently checks the local environment and finds the x set to 10 by "var x = 10". Is that right?
If that were the case, then I would expect the following would also work, and yet it does not:
var a = function(){
alert(x);
};
(function (){
var x = 10;
a();
})();
What I would expect to happen is that, when a is executed, and "alert(x);" is run, it checks the closure environment for x, finds none, then checks the outer environment where "var x = 10" is and finds that x. But instead I get an error that x isn't defined.
Maybe it would help if I could know what 'preparatory' work is done by the interpreter when the anonymous function that a is set to is initially defined--i.e. when the interpreter encounters the x in "alert(x)".
Thanks
the JS checks the closure environment for a mapping for x and finds none
In fact it does find one. The position of the var statement does not matter, the name x is still bound to the closure of the outer function. You can think of the declarations being collected during the parsing step and moved to the front (this process is called hoisting).
Thr process of walking up the scopes surrounding an expression in the source code is called lexical binding.
For your second example to work you'd need dynamic binding, which JS does not support (except for globals).
Think of closure as a stack. Each function has a map/hash in that stack. Here's an example where each level has a value of x that is overwritten by a sub-closure.
function a(){
var x = 2;
function b(){
var x = 3;
function c(){
var x = 4;
}
}
}
When referencing a value of x, the js processor looks in the current closure. Finding undefined, it walks up the closure stack attempting to find a value. Only when reaching the top level or 'global' scope does it give up and give the value of 'undefined'.
Your example here:
var a = function(){
alert(x); //no value of x in this closure
};
//no value of x in this closure either
(function (){
var x = 10; //this is a completely separate stack
a(); //no value of 'a' in this closure, but there is one in global scope
})();
I can see the confusion on the 'a' function not knowing about the 'x' in the anonymous function. Closure scopes are defined 'as written' not 'as called'. You can't inject or mess with variables in a functions closure scope from outside that closure scope. It is one of the things about js that drives me crazy and that I wish were different. I'd so love to have a set of keywords for messing with closure scope...

scope and availability of a variable inside a function

I am learning javascript and my question might not be used practically anywhere but for interview purpose I want to understand this clearly. below is the code. the first alert alerts 'undefined' and the second one is '4'. the second one is understandable. I want to know why the first alert doesn't alert '5' and undefined? whats the concept behind the same?
Thanks.
var x = 5;
function check(){
alert(x);
var x = 4;
alert(x);
}
check();
var is always hoisted (moved) to the begining of the scope. Your code is equivalent to this:
var x = 5;
function check(){
var x;
alert(x);
x = 4;
alert(x);
}
check();
As you can clearly see, the local x hides the global x, even if the local one doesn't have a value yet (so the first alert shows undefined).
A little extra: conditionals or other blocks don't influence hoisting the var declaration.
var x = 1;
(function() {
x = 3;
if (false) {
var x = 2; // var will be moved to the begining of the function
}
})()
console.log(x) // 1
JavaScript has some concepts that take a little getting used to for sure and sometime the answer for what seems to be a simple question is long winded but i will try to be as quick and concise as possible.
In JavaScript, variables are scoped by functions and you have two places that a variable can be scoped(have context) either 'globally' or 'locally'. The global context in a web browser is the 'window' so in your code example var x = 5; is a global variable. The local context in your code is within your check function so var x = 4; is a local variable to the check function. If you had more functions those would have their own function scope(context) and so on. As a word of caution if you forget the word "var" when declaring a variable inside a function it will become a 'global' variable, be careful. Now that we have the 'global', 'local' scope down what happens before a Javascript programs runs?
A few things happen in the Javascript Engine before your code is executed but we will only look at what happens to variables. Variables are said to be 'hoisted' to the top of their functional context or scope. What that means is that the variable declaration is 'hoisted or moved to the top and assigned the value 'undefined' but not initialized the initialization remains in the same spot they were. This hoisting also makes the variable available anywhere within the function it was defined.
So it looks something like this:
//to be accurate this is hoisted to its functional scope as well
var x;
x = 5;
function check() {
//declaration of 'x' hoisted to the top of functional scope,
//and assigned undefined
var x;
//this will alert undefined
alert(x);
//initialization of variable remains here
x = 4;
//so after the initialization of 'x' this will alert 4
alert(x);
}
check();
Happy Coding!!!
As an aside: They have a new feature named 'let' that you can implement to add block-level scoping in I believe EMCAScript 6 but is not implemented in all the browsers as of yet so that is why i placed it in an aside.

Categories

Resources