Newbie Questions on Scoping and Hoisting? [duplicate] - javascript

This question already has answers here:
What is the temporal dead zone?
(3 answers)
Are variables declared with let or const hoisted?
(7 answers)
Closed 1 year ago.
I am learning Javascript and I got into the hoisting/scoping part. I got some questions that I really hope somebody can help me to clarify and here is my example:
So these works normally due to hoisting - the firstName variable is in Global Scope or function can be called before we declare the function:
function test() {
console.log(firstName);
}
const firstName = 'a';
test();
OR
const firstName ='a';
test();
function test (){
console.log(firstName)
}
However, if I swap the order of firstName and test(), the code does not work anymore:
function test() {
console.log(`${firstName}`)
};
test();
const firstName = 'a';
According to the hoisting, I thought the firstName variable is in the Global Scope. Thereby, the test function should have been able to look up at the variable firstName when it is executed.
But why in the case above, it does not work?
Is there anything wrong with my understanding of hoisting/scoping?

Variables declared with let and const are also hoisted, but unlike for
var the variables are not initialized with a default value of
undefined. Until the line in which they are initialized is executed,
any code that accesses these variables will throw an exception.
MDN DOCS

Related

Why the function's log is the function itself? [duplicate]

This question already has an answer here:
Why is the named IIFE logged instead of the variable with the same name?
(1 answer)
Closed 2 years ago.
I have encountered a problem that if the IFEE function's name is the same with variable's name in it. the output is the function itself. Why?
var b = 10;
(function b() {
b = 20;
console.log(b);
})();
Named function expressions create a read only variable in their own scope which matches their name and references themselves.
This is useful for writing recursive functions.

Difference between function declerations [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 2 years ago.
What is the difference between this (a 'standalone' function):
function standaloneFunction () {
console.log('standaloneFunction runs, success')
}
standaloneFunction()
...and this (a function inside a variable):
let variableFunction = function variableFunction () {
console.log('function inside let has same name as the variable, runs? - yep, does.')
}
variableFunction()
Is it a problem that the variable and the function share the same name?
it doesnt seem so - i speculate this is because it has something to do how variables
and functions are saved in memory? Functions in their entirety, and variables only their declaration?
When i do console.log(this), i can't find the 'variableFunction' in the execution
context of 'this' - however, 'standaloneFunction' does appear.
Have you, as a beginner, also asked yourself such questions? Am i being too picky about such details?
Should i already use es6 syntax?
Please also don't hold back with any advice regarding articulating my question.
Thanks to everyone who has taken their time to read this.
The first is a function declaration, which will be hoisted. The second is a named function expression, but I think an anonymous function expression would be better in this case since there’s no need to name the function, e.g. let variableFunction = function() {…}.
Please see What is the difference between a function expression vs declaration in JavaScript?

Javascript -What happens if a variable and a function have the same name? [duplicate]

This question already has answers here:
Function and variable with the same name
(2 answers)
Closed 5 years ago.
Might be a kind of easy question, but I have a question on the issue of having the same name for a variable and a function.
If there's a variable,
var add = 1;
and a function,
function add(x,y) {return x+y;}
and there're two console.log,
console.log(add)
console.log(add(1,2))
I've expected those 2 console.log would work properly since add contains the Number and add() is classified as a Function, but the second one prints an error. So they aren't considered the same.
But the result says I'm wrong.
Can anyone explain what's going on in my code?
Variables and function definitions(not expressions) are hoisted to up, it means that wherever in scope you wrote your function or variable they will be moved to the start of the scope. First goes functions definitions then variables. So it means that functions will be overwritten by variables.
var add = 1;
function add(x,y) {return x+y;}
console.log(add);
The order doesn't matter. Later will be the variable and will overwrite
function add(x,y) {return x+y;}
var add = 1;
console.log(add);

Javascript Hoisting, Function delaration [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 7 years ago.
In javascript, what's the purpose of assigning variable to function declaration?
var test = function(){console.log("Hello world")}
over
function test(){ console.log("Hello world")
Also, I don't understand the code below does not work. Is it because hoisting does not care about variable assignment? (cares only about variable declaration)
vartest();
var vartest = function(){
console.log("Hello var function")
}
The first part is not answerable. There's no "single purpose" and there are varied use cases for this.
The second part is simpler. Hoisting can be described as "pulling up declarations". This means that variables and functions are effectively always declared at the top of their scope. That does not mean they are assigned values at the top. Values are assigned at the original location of the "pre-hoisting" declaration. However, since named functions are not assigned a value, the hoisting effectively moves the declaration and implementation as a whole to the top of the scope.
This does not happen for functions assigned to variables, and hence the code "does not work".

Javascript variable declaration, why is this legal? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.

Categories