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".
Related
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
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?
This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 5 years ago.
By trying to override a function I occurred in this odd behaviour. I hope to find an answer after having searched and read about function declaration methods without success.
In a script, if I declare this
var someFunction = function(){
alert("a");
}
someFunction();
someFunction = function(){
alert("b");
}
By calling someFunction I will have an output of "a"
But if I declare the two functions in this way
function someFunction(){
alert("a");
}
someFunction();
function someFunction(){
alert("b");
}
My output will be "b"
What is the difference here? I understand the first example is assigning to a variable an anonymous function. But the second example is totally unexpected and new to me.
I tested on all browsers and the output is the same.
The difference is the fact you are calling an anonymous function in the first example, Javascript gets evaluated top to bottom. In the case of an anonymous function it isn't actually executed UNTIL it is called later on.
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 8 years ago.
Just want to clear up some confusion regarding functions in JavaScript. Does a declared function create a variable with the function name in the same function scope and assign the function object to itself?
By code,
function name(){}
does it translate to,
var name = function name(){}
just before execution? If function is an object it should be held some where inside the scope by reference right?
Essentially yes with one exception.
In both your examples, the name function will be assigned to the name variable. In your first example the name variable and function definition will be hoisted to the upper most part of the current scope.
In your second example the name variable will be hoisted to the upper most part of the current scope but the definition will remain at it's current position in code.
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.