This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 8 years ago.
I am trying to understand anonymous functions but having a hard time. The function below is an anonymous function but I'm not sure how it would get called or used. I have looked all over the web but have not gotten a good explanation of how/when to use it. Please help.
var area1 = (function() {
var width = 5;
var height = 2;
return width*height;
}());
Thanks for any clarification that can be provided.
That is an immediately executed function expression. The function is defined, then executed right away (by the () after it).
The code has the same effect as:
var area1 = 10;
You can't use the function after that statement, because it only exists as an intermediate value, and the variable area1 is assigned the result of executing the function.
Related
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:
How do JavaScript closures work?
(86 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 2 years ago.
I am new to JavaScript (and StackOverflow) and am hoping to get some help on a problem that has bothered me for some time. I understand that functions are considered objects in JS. A function is different from an object in the sense that it can execute code.
This may be a very simple and straightforward question to some of you veteran folks. I don't understand how the code works below. Essentially there is a function count() that returns an anonymous counter function. keepCount points to the anonymous function (an object, of course) that count() returns.
function count() {
var num = 0;
return function(correct) {
if (correct)
num++;
return num;
}
}
var keepCount = count();
keepCount(true); // num is 1
keepCount(true); // num is 2
keepCount(true); // 3
keepCount(true); // 4
console.log(keepCount(true)); // Call it again and print. It is 5.
My question: What is causing the result of num to be 'saved' or recorded with each function call? Isn't num a variable local to count() — the outer function? num does not appear to be a property of the anonymous function. I suspect the answer has something to do with the fact that functions are considered objects in JS, and that a local variable can be continuously updated in the variable object of count(). A new variable object is not produced for count() with each call of the anonymous function.
I would also appreciate comments on the formatting of this question and all. I want to be sure that I am following StackOverflow guidelines properly. I also hope that the details of the question make sense. Please let me know if anyone requires clarification.
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);
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I'm having problems trying to add rows to the variable x. I have not understood how to return a value from an anonymous function called by another function.
var pgClient = new pg.Client(connectionString);
pgClient.connect();
var query = pgClient.query("SELECT * from sceglie");
var x = [];
query.on("row", function(row,result){
result.addRow(row);
x.push(row);
});
console.log(x);
There is no way to do what you are trying to do. Javascript is a synchronous language in that it executes line by line. So this line:
console.log(x)
Will execute right away. The "on" function will only execute when it is called, so your log statement will always have the empty value.
Link to good article explaining JS environment
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.