Javascript function declaration - different behaviour? [duplicate] - 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.

Related

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?

Why javascript function parentheses can not access the outside? [duplicate]

This question already has answers here:
Why a Name Function Expression not available outside function body [duplicate]
(3 answers)
How do JavaScript closures work?
(86 answers)
Closed 7 years ago.
I'm curious, why not just javascript function scope it? Why just add a parenthesis can not access it? My guess is that the parentheses and javascript related operations, but do not know exactly why this child principle and design?
(function test(){
console.log( test );
})();
test();//Uncaught ReferenceError: test is not defined IE8- is ok
or
(function test(){
console.log( test );
});
test();//Uncaught ReferenceError: test is not defined IE8- is ok
When you wrap a function in parentheses like you did, it does put it in a new scope.
It also acts like a return value, which is why it can be called as an IIFE, or Immediately Invoking Function Expression.
Another way to re-write it, which will make more sense is like so:
var myFunc = (function test(){
alert('Hello!');
});
myFunc(); // Works!
test(); // Doesn't work!
To learn more about this, you should read about IIFE - Immediately-invoked function expression.
The short version - the function runs in its own scope, unless you pass parameters to it, like so:
(function test(x) {
alert(x); //alerts "yey!";
})("yey!");

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.

Function excuted before creation [duplicate]

This question already has answers here:
Why can I use a function before it's defined in JavaScript?
(7 answers)
Closed 9 years ago.
I am no JavaScript expert, but I found some code like this
a();
function a(){
alert('a');
}
and I was surprised to find it works (I think something like that will not work in Python). I expected that the function a can't be executed before being created. How does interpreter work and why functions can be called before declaration?
This happens because of variable hoisting.
See this answer for more info
JavaScript 'hoisting'
Some docs about this:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting
If you type it like this, it won't work:
a();
a = function(){
alert('a');
}
Code that is within functions and objects will be run whenever that
function or object is called. If it is called from code that is
directly in the head or body of the page then its place in the
execution order is effectively the spot where the function or object
is called from the direct code.
See the reference here.
And in our case the function will give the error as you can see the example here.
It's because function a() is declared via Function Declaration syntax, and Function Declaration are executed right after the script is parsed. With other syntax, Function Expression, like this:
var b = function(){
alert('b');
}
it won't work (see example).
More info: http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

difference between javascript function declaration [duplicate]

This question already has an answer here:
Anonymous function vs normal function
(1 answer)
Closed 9 years ago.
I know this type of question gets asked a lot, but I haven't seen any question with this type of declaration
(function(){
myFuncName=function(myVar){
// some logic
};
}());
how does that differ from
function myFuncName(myVar){
// some logic
}
The first one is an anonymous function and there is no way you can reference to and call it later on, so you just executes instantly ( ) once it had been created!
(function(){
alert(1)
}())
The second one is a reference function that you can call it anytime later. It wont gets executed unless you call it explicitly
What your doing is creating an anonymous function that also has a closure in it. Read more about closures here.
Basically a closure means that you have declared a function inside of another function. Which will let you access local variables after the first function exits.
Normally you would not be able to do this since they would be out of scope.
As for the other part. You can find a very useful guide to what's happening here Why do you need to invoke an anonymous function on the same line?.
To sum it up though, you have created an anonymous self-invoking function expression.
The self-invoking comes from the fact that () immediately follows the function expression.
Here's a link which explains the the function declarations in javascript.

Categories