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

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.

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.

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);

How do we explain javascript hoisting here? [duplicate]

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Why is no ReferenceError being thrown if a variable is used before it’s declared?
(3 answers)
Closed 5 years ago.
I wonder why the two code snipped below generate two different results as in reference below the two have to be the same as were are in global scope and placing var would not make a difference.
I was under the impression due to what explained below and the Javascript hoisting the two generate same output, but don't! why?
What is the purpose of the var keyword and when to use it (or omit it)?
console.log(a)
var a = 90;
// undefined
vs
console.log(a)
a = 90; // no var keyword
// Uncaught ReferenceError: a is not defined
When you put var keyword, what it does is it moves the var part as a declaration on that scope and makes it undefined. In the first case, with var:
console.log(a)
var a = 90;
// undefined
Gets rewritten as:
var a = undefined;
console.log(a)
a = 90;
// undefined
So, you get the undefined here, vs. your second case has it the same way, where there's no declaration or key in window object named a. Hope this is understandable.
The point here is, when you use a var keyword, immediately that's defined as undefined at the top of the scope before anything.

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".

What is this format of function called? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
What is the purpose of a self executing function in javascript?
(21 answers)
Closed 7 years ago.
function animator(shapes, $timeout) {
(function tick() {
var i;
var now = new Date().getTime();
var maxX = 600;
var maxY = 600;
var now = new Date().getTime();
$timeout(tick, 30);
})(); // What is this for?
}
Here I don't understand the functionality. I am new to this kind of script. Inside of the main function is like ()(). What is this for?
This is an IIFE, Immediately-invoked function expression.
Why use an IIFE?
Why?: An IIFE removes variables from the global scope. This helps
prevent variables and function declarations from living longer than
expected in the global scope, which also helps avoid variable
collisions.
Why?: When your code is minified and bundled into a single file for
deployment to a production server, you could have collisions of
variables and many global variables. An IIFE protects you against both
of these by providing variable scope for each file.
I don't know if it has a separate name, it's just immediately executed.
Instead of function a(){..}; a() you can do (function(){..})()
Useful for scoping the vars inside, while placing/executing it right where you want it, also you don't have to invent a name for it.
(function(){console.log('test')})() will call function immediately. So if you will write this statement then it will be called immediately and prints test on console.
This is a self-invoking function as #lix pointed out.
Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started) automatically, without being called.
Function expressions will execute automatically if the expression is followed by ().

Categories