JavaScript hoisting confusion regarding let [duplicate] - javascript

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/

Related

Why does it throws reference error for b? [duplicate]

This question already has answers here:
Are variables declared with let or const hoisted?
(7 answers)
What is the difference between "let" and "var"?
(39 answers)
Closed 2 years ago.
Recently I attended a interview for Frontend development, The interviewer came up with a problem which made me doubt my confidence on javascript. The question is
function some() {
console.log(a) // undefined
console.log(b) // Reference Error: cannot access b before initialization.
var a = 10;
let b = 15
}
I understood hoisting is happening here, but i am not sure why b throwed reference error. Could anyone please explain ?
Unlike variables declared with var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. Accessing the variable before the initialization results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

How are 'let' variables accessed in devtool's console? [duplicate]

This question already has answers here:
Do let statements create properties on the global object?
(5 answers)
Closed 2 years ago.
If you open chrome devtool and enter the following:
// The iife is irrelevant
let r = (() => { return 2; })();
and then evaluate r you'll see:
r
2
but window.r and globalThis.r both return undefined. I know let is block scoped but where is the r parent object? What block am I in, in the devtool that I can access r directly but it's not on any global object?
Apologies, I'm on my phone, so can't really verify. But I'm pretty sure there is a 'scope' tab as part of the Dev tools. If you're debugging I'm pretty sure you can see variables there in the current scope. But it's not available in the normal console
https://developers.google.com/web/tools/chrome-devtools/javascript#scope
Edit, just re-read your question, and this doesn't really answer your question description, but does kind of answer your question title. So probably going to leave the answer here for future ref
The code is evaluated in global scope.Variable "let" declared Globally (outside any function) have Global Scope.

Why hoisting works differently in variables compared to functions? [duplicate]

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.

Why does a variable assignment not throw a ReferenceError when the variable is not defined - JavaScript [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 3 years ago.
I've tried this in Chrome, Opera, Microsoft Edge, Internet Explorer and Mozilla Firefox and still gotten the same case: A ReferenceError exception is not thrown that the variable I assigned a value is not defined.
The syntax is:
// Where `identifier_name` was not formally declared/ initialized.
(function() {})(identifier_name = 2)
Why does this behavior occur?
Edit: Just to add, this doesn't work if what is being assigned is a property of an object i.e.:
// Throws a ReferenceError that `object_name` is not defined.
(function() {})(object_name.property_name = 2)
Thats what we used to call the horror of implicit globals
You basically create a global variable by accident. You can "use strict";mode to prevent that.
Your second snippet does not work because you are trying to access a variable that was not declared yet, which is different from assigning to a variable that was not declared already (cause that implicitly declares the variable).
You have declared a global variable here in both cases without the 'var' keyword.

Logging Global variable inside the function Block immediately before redeclaration going undefined: Should not it take the Global Variable Value? [duplicate]

This question already has answers here:
Are variables declared with let or const hoisted?
(7 answers)
Closed 5 years ago.
let pages =100;
let pageFunction=()=>{
console.log(pages);
const pages = "20";
//console.log(pages);
}
pageFunction();
Output:
Uncaught ReferenceError: pages is not defined
at pageF (:3:13)
at :1:1
According to Mozilla "The let statement declares a block scope local variable, optionally initializing it to a value." Also "At the top level of programs and functions, let, unlike var, does not create a property on the global object."
See
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let for more information.
This means that in the code you gave you effectively create an implicit global variable pages, as let pages is not really global, but restricted to the scope it is in.

Categories

Resources