This question already has answers here:
Surprised that global variable has undefined value in JavaScript
(6 answers)
Closed 2 years ago.
I have been reading some docs lately and came across some inconsistent patterns related to hoisting in JavaScript.
It goes as follows:
In functions,
function abc(){
console.log("worked")
}
abc();
OUTPUT : worked
Also,
abc();
function abc(){
console.log("worked")
}
OUTPUT : worked
This happens due to hoisting as in the execution context the memory is saved initially for abc.
But the same doesnt happen in case of varibles and I was wondering why
For example,
var a = "Hello"
console.log(a)
OUTPUT : Hello
**So why not the same in given below code?
console.log(a)
var a = "Hello"
The above code states "undefined"
when the execution starts for the above code:
a is set to undefined
then undefined is reassigned to the value provided that is "Hello"
But that is not the case, instead it outputs undefined
Why is that?
Thank you for reading.
Any help would be really appreciated.
The code
console.log(a)
var a = "Hello"
is interpreted as if it were written
var a;
console.log(a);
a = "Hello"
Why? That's the way the language is specified to work. Hoisting the whole initialization expression would create problems in many cases.
Related
This question already has answers here:
Is Chrome’s JavaScript console lazy about evaluating objects?
(7 answers)
Weird behavior with objects & console.log [duplicate]
(2 answers)
Closed 1 year ago.
From my understanding, all properties created are given the value of undefined after the execution phase of the Execution Context - then, during the creation phase, the JS engine goes through the script, line by line, and assigns a value if it finds an = operator. With this in mind:
console.log(window);
var myVar = 1;
From the above snippet, why does the myVar property, within the global object, show a value of 1? I would have thought it would show a value of undefined, as this is what it was set to during the execution phase? If I try to access the property directly, like:
console.log(window.myVar);
var myVar = 1;
I DO see the value as undefined... it's only when I log the entire global object I'm seeing the value as 1. Am I missing something here?
Note - this is simply for learning purposes.
this has nothing to do with the window object, this is called hoisting
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.
another example would be
function test(){
console.log(myVar);
var myVar = 1;
}
test()
this would still log myVar as undefined. while omitting the myVar would throw an Exception..
Edit:
this only happens in the chrome console, it would be undefined otherwise.
This question already has answers here:
What is the temporal dead zone?
(3 answers)
Closed 2 years ago.
a= 10; console.log(a); let a; => Cannot access 'a' before initialization
above code gives error for initialization, even if a is declared before use. Please explain how this gives an error if a is already hoisted and get declared "a=10" before using it.
That also means if a variable is declared with let or const, hoisting doesn't have any practical impact ?
if I run below code
let a; console.log(a); => undefined
in this case I am able to print a i.e. undefined, without initializing it.
What is happening in core ?
When you type:
a=10
then you are defining a global variable. It is deprecated and not recommended style of coding in almost all languages.
To prevent declaring global variables es6 introduced let and const.
Now when you are using let or const your interpreter checks that when you typing
let a;
you do not have a used before this declaration. This is the reason for the error.
Update:
You typed:
let a; console.log(a); => undefined
it is ok because a is declared, memory is reserved, the symbol a is registered, but the value is not assigned, so when you evaluate the value assigned to symbol a it is undefined.
Please compare it with case:
console.log(c);
You will get an error:
Uncaught ReferenceError: c is not defined
because the symbol c was never declared.
Now when you will assign values to a it will be done in local scope, but when you will assign values to c it will create global variables.
To improve your understanding please read about all methods of defining variables and look at all edge cases. A great article is under the link:
https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/
This question already has answers here:
Why does JavaScript variable declaration at console results in "undefined" being printed?
(4 answers)
Closed 4 years ago.
In chrome Developer tools, when I type
a = 3 logs 3 but
var a = 3 logs undefined.
Why does the first statement return 3 but not the second one?
Because that's the way it is.
A statement beginning var is a declaration. Declarations don't, in and of themselves, have a value. They tell the computer to do something (to create a variable, optionally with some initial value).
But assignment expressions are different. a = b evaluates to (or "has") the new value of a, in order to allow chaining, such as a = b = c = d.
Could they have made it so that var a = b was an expression and evaluated to something? Sure, probably. But it would hold absolutely no useful value to butcher the language grammar in such a manner.
Read up about statements and expressions in programming languages.
Because undefined is the result of the var statement.
Statements don't actually have a "result" that can be used in your code, but a program has a final result, and your single line of code in the console is evaluated as a program.
This question already has answers here:
Global JavaScript Variable Scope: Why doesn't this work?
(5 answers)
Javascript function scoping and hoisting
(18 answers)
Closed 8 years ago.
I need to understand how the JavaScript engines in browsers read functions. Consider the code below:
var g = 5;
alert(g); //alerts 5
function haha() {
alert(g); // alerts NOTHING. Why is this? Why not alert 5? var g = 45 hasn't yet occurred
var g = 45;
alert(g); // alerts 45
};
haha();
alert(g); // alerts 5. Because g = 45 is a local variable.
Fiddle
The effect you're seeing where alert(g) in the haha function alerts undefined is from variable hoisting.
The haha function is actually executed as:
function haha() {
var g;
alert(g);
g = 45;
alert(g);
}
This is because variable and function definitions are hoisted to the top of their scope in JavaScript.
The effect can lead to some rather unintuitive behavior, such as what you're seeing. The simple solution is to always declare your variables and functions before any executing code so that the written code matches what's being executed.
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
I ran across these two examples. Example 1 is not valid JavaScript - it throws an error. The second example is valid and works fine. Is there any chance someone can explain why 1 throws an error?
Example 1:
var
laugh
;
laugh();
laugh = function () {
console.log( "Hahaha!!!" );
};
Example 2:
laugh();
function laugh() {
console.log( "Hahaha!!!" );
}
It's something called "hoisting" is javascript. Some blog post on the topic: http://jamesallardice.com/explaining-function-and-variable-hoisting-in-javascript/
Assuming you mean that option 1 is invalid and option 2 is valid:
this is a classic pitfall in JS. basically, in your first function, you declare the variable laugh as an anonymous function, but that doesn't turn it into a function which you can execute by laugh(). however, in the second example, you explicitly declare the function laugh, which you CAN execute by laugh().
edit for below comment: as a correction: you CAN execute the function, but you need to declare it BEFORE executing. else it is undefined. JS makes a list of all functions during compile so they can be executed before they are declared,, but variables are declared and assigned at runtime, so they need to be assigned BEFORE executing.
edit2: vkurchatkin has a good link to what i'm talking about.