These are 2 examples which must have attained same result:
Example 1
<script>
console.log(a);
var a = 10;
console.log(a);
</script>
Rendered
<script>
var a = "";
console.log(a); //will result undefined
a = 10;
console.log(a); //will result 10
</script>
Result
undefined
10
Example 2
<script>
console.log(a);
a = 10;
console.log(a);
</script>
Expectation of Rendering
<script>
var a = "";
console.log(a); //should result undefined
a = 10;
console.log(a); //should result 10
</script>
Result
Now, as per JS Hoisting in Scenario 2, the variable if not declared must have been automatically declared onto top of its scope and still result should have been the same. Why is it not? Where is the concept failed?
The second case is different, because
a = 10
... does not declare a hoisted variable. It creates a property in the window object (even if the code would have been inside a function). This is not a declaration, and thus something that is not hoisted. So before you create that property, it does not exist.
Note that what you listed as rendered code is not entirely correct. A hoisted variable does not get a value, so for your first example it should look like this:
var a; // undefined!
console.log(a); // will output undefined
a = 10;
console.log(a); // will output 10
Note that if this code is not part of a function body, var a also creates the window.a property, and this happens at the hoisted declaration.
And for your second example, the rendered code could look like this
console.log(a); // Error: does not exist.
window.a = 10;
console.log(a); // will output 10
JavaScript hoists declarations, not initializations, see this page.
If you add a 'var a;' somewhere in your second example, it should work fine!
On example 2, at the time you run the first console log, a is really undefined.
a = 10 sets a new property a to the window object and there's no 'hoisting' when setting a property to an object that already exists.
when we will execute a source code .IN hoisting, The declaration variable goes over console.log().Then the variable allowcated a memory but does not access it. When I declaration a variable in memory. Then we give by default undefined value in place of that variable. (as like ,in html,place Holder works like this.
--- So you have not declared any variable. Hosting will not work here.
--- Can't access a here..Because when you define a variable.
Then you must be defined a variable.here u can not make variable so output: cannot access a
Related
if i write something like this:
var a = 1;
function lol(){
console.log(a);
}
lol();
it outputs 1 as intended, as i initialized a=1 in global scope. So i thought in function it initialized its value as well.
But when i write something like this:
var a = 1;
function lol(){
var a = a + a;
console.log(a);
}
lol();
it outputs NaN, which confuses me, cuz i thought the variable has already been initialized in global scope.
Here's my thoughts, don't know if it's correct or not, so i'm asking: i think the keywords like var/let/const, each time it's mentioned, it kind of re-initialize the variable or what? and since the second var is in block scope, so when mentioned with var, the variable a goes initialized again and thus becomes undefined, outputs NaN.
am i correct? plz help.
You initialize the variable then just use the same variable
var a = 1;
function lol(){
a = a + a;
console.log(a);
}
lol();
at statement var a = a + a; you are defining altogether different variable which was not initialize before arithmetic operation so it is resulting NaN compiler declared another variable with same name a
Maybe it's happening because of hoisting. Please refer https://developer.mozilla.org/en-US/docs/Glossary/Hoisting#var_hoisting
As per MDN,
JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.
In JavaScript the execution of code takes in 2 phases. In first step it is read and the space is reserved for variables(given value undefined initially) and functions. In the second phase it is executed line by line.
And also I read that the variables declared without var keyword are set as Global variables.
So if I print a variable before defining it inside a function, it should print undefined. Like in the code below:
b();
console.log(a);
console.log(d);
var a = 'Hello World!';
function b() {
console.log(c);
console.log('Called b!');
var c = "variable c is printed";
console.log(c);
console.log(d);
d = "Variable d is printed";
}
I expect the output to be:
undefined
Called b!
variable c is printed
undefined
Variable d is printed
But I get the below output:
undefined
Called b!
variable c is printed
Uncaught ReferenceError: d is not defined
at b (app.js:12)
at app.js:1
So my doubt is, when function b is called, then in the first phase of code execution, variable d should be given space and value undefined initially. And then the execution should begin line by line in the second phase.
And also I read that the variables declared without var keyword are set as Global variables.
Yes, kind of. What happens is that if you do an assignment, like
d = 1;
The engine goes up through all environment records (the place were values of variables are stored at runtime), so in your case it first goes to bs record, and then to the global record. If it finds a variable binding (name -> value) in one of those records (which were created when execution starts, just as you said), it then stores the value there. However if it reaches the global record, and does not find a binding along the way (the variable is undeclared), it just creates a new binding at that global record.
So by the time you do console.log(d), no binding for d exists, and accessing d fails.
In first Phase When try to set space for Variables Find them by Keywords:
var/let/const
When you don't use it in second Phase crashed variables pointer where not exist space for them, In function scope d don't have any space and its a crash point.
this code show what happened:
console.log(a);
a = 'Some Value For A Variable';
to solve it two solution:
1- use Keywords
console.log(a);
var a = 'Some Value For A Variable';
2- Initializing First
a = 'Some Value For A Variable';
console.log(a);
The Best Clear Code is Complex of two Solution:
* use keywords
* call variables after definition
var a = 'Some Value For A Variable';
console.log(a);
Good Luck
This question already has answers here:
Surprised that global variable has undefined value in JavaScript
(6 answers)
Closed 5 years ago.
if i declare variable at top with some value, then using that variable is showing undefined why?
var a = 100;
function test(){
console.log(a);
var a = 1000;
console.log(a);
}
test();
The output is undefined and 1000 why?
In your function, the local variable masks the global one.
var a = 100;
function test(){
console.log(a);
var a = 1000;
console.log(a);
}
test();
The fact that your var statement is in the function as well as global scope doesn't change anything. The global variable is masked for the whole function.
So, for the whole execution of the function, the global variable will reference the local one, and not the global one.
Outside of that function, though, the global variable will still exist
If you want to access the variable inside the function you can use
console.log(window.a);
It's because of the way JavaScript compiles the code.
Firsr it looks for declarations in the scope, then, if inner scopes are present, it looks for their own scope, in this case I'm pretty sure it's like the following:
Global scope will have a variable named a and a value of 100 assigned to it
There is a global function declaration named test, it needs its own scope, let's go for it
2.1. This scope will have a variable named a (uninitialized)
2.2 There is a call for the console object's function named log, it needs to have the variable named a, is that variable in this scope? Well, it looks like it is, but does not have a value assigned now so it is undefined.
2.3 NOW I have something to assign the variable, it's 1000, ok, let's continue.
2.4 There is a call for the console object's function named log, it needs to have the variable named a, is that variable in this scope? Well, it looks like it is, AND its value is 1000 console.log(a) => 1000
There is a call for the test function see 2.1
So, when you call the first console.log(a) the engine knows there is a local scope's variable named a, but it is not yet initialized, that's why you get undefined, then, in the second call, the local scope's a variable has a value of 1000 assigned to it, local scope is higher in hierarchy than parent scope so the value for the log will be 1000.
You might want to read about Hoisting of a javascript variable.
Because of hoisting, var a = 1000; is treated as var a; and a = 1000; as two different statements. The var a; statement, which is variable declaration, is moved to the top inside the function due to hoisting.
Now your function is as good as
var a = 100;
function test(){
var a;
console.log(a);
a = 1000;
console.log(a);
}
test();
var a; statement declares a local variable but is still undefined. So you get undefined on first console.log(a);.
To access the global variable learn how to use this like this.a.
In Javascript variables are hoisted to the top of the scope they are declared within.
However in the following code it seems that the variable myvar is not hoisted.
<html>
<body>
</body>
</html>
<script type="text/javascript">
console.log(typeof myvar);
var myvar = "value";
console.log(typeof myvar);
</script>
The output of the above is:
undefined
string
I expected that the first line would say "string" because myvar is supposed to be hoisted to above it.
Why isn't this so?
Variable declarations are hoisted, the assignments are not.
By using var myvar anywhere in the function you create a locally scoped variable myvar, but if you follow it with = something then the assignment will take place in normal code order.
A dupe of this came up, and Quentin's answer is good (as always), but just to spell it out even more:
The way the JavaScript engine actually processes that code is like this:
// Before any step-by-step code
var myvar;
// Now step-by-step starts
console.log(typeof myvar); // undefined since no value has been written to it
myvar = "value";
console.log(typeof myvar); // "value" because that's its value now
That is, this:
var myvar = "value";
... is actually two separate things that happen at two separate times. The variable declaration (the var myvar part), which happens before any step-by-step code in the scope is run, and the initialization (the myvar = "value" part; it's really an assignment expression by the time it's processed), which happens where that line is in the code.
This question already has answers here:
Surprised that global variable has undefined value in JavaScript
(6 answers)
Closed 3 years ago.
First , let's see the code.
var a=0;
b=1;
document.write(a);
function run(){
document.write(b);
var b=1;
}
run();
I think the result is 01 .but in fact , The result is 0undefined.
Then I modify this code.
var a=0;
b=1;
document.write(a);
function run(){
document.write(this.b); //or document.write(window.b)
var b=1;
}
run();
Yeah, this time it runs as expected. 01 . I can't understand, WHY?
More interesting, I modify the code again .
var a=0;
b=1;
document.write(a);
function run(){
document.write(b);
//var b=1; //I comment this line
}
run();
The result is 01.
So , Can anyone explain this?
Thanks for share your viewpoints.
I simplify this code
b=1;
function run(){
console.log(b); //1
}
two:
b=1;
function run(){
var b=2;
console.log(b); //2
}
three:
b=1;
function run(){
console.log(b); //undefined
var b=2;
}
When you refer to a variable within a function JS first checks if that variable is declared in the current scope, i.e., within that function. If not found it looks in the containing scope. If still not found it looks in the next scope up, and so forth until finally it reaches the global scope. (Bear in mind that you can nest functions inside each other, so that's how you get several levels of containing scope though of course your exmaple doesn't do that.)
The statement:
b=1;
without var declares a global variable that is accessible within any function, except that then in your first function you also declare a local b. This is called variable shadowing.
"But", you say, "I declare the local b after document.write(b)". Here you are running into declaration "hoisting". A variable declared anywhere in a function is treated by the JS interpreter as if it had been declared at the top of the function (i.e., it is "hoisted" to the top), but, any value assignment happens in place. So your first function is actually executed as if it was like this:
function run(){
var b; // defaults to undefined
document.write(b); // write value of local b
b=1; // set value of local b
}
In your second function when you use this.b, you'll find that this refers to window, and global variables are essentially properties of window. So you are accessing the global b and ignoring the local one.
In your third function you don't declare a local b at all so it references the global one.
When you write b = 1, you're creating a property in the global object.
In an ordinary function, b will refer to this global.
Since your function contains var b;, b within the function refers to the local variable. (var statements create local variables throughout the function, no matter where the var is).
However, the executable portion of the var statement (b = 1) is only executed at that point.
The var directive is processed on the pre-execution stage, the b becomes local variable before document.write(b);, so at that time, b is undefined.
Note: assign a value to a variable is at the execution time, so you could image your code is like below.
function run(){
document.write(b);
var b=1;
}
is the same as:
function run(){
var b;
document.write(b);
b=1;
}
Addtion:
This is why Put every var definition at the top of the function is good practice.
This code work fine for me
if(var_name === "undefined"){
alert(var_name+' : undefined');
}