Functions Considered as Objects in JavaScript [duplicate] - 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.

Related

Functions that call eachother [duplicate]

This question already has answers here:
Are variables statically or dynamically "scoped" in javascript?
(7 answers)
What is the scope of variables in JavaScript?
(27 answers)
Closed 2 years ago.
I am looking for someone to explain me something since I can't find a clear answer. My question is about functions that call themselves. I saw that it is possible to build a list of functions that are 'chained' together and for example the first function calls the second one then the second one calls another one. My confusion is : Lets say that you have a second function that has a variable let a = 12; if i call that function on the first function, will i have access to that variable or whatever that second function might have inside? How can i pass info to another function? can a function can be dependent on another function in order to complete a task? Thanks in advance guys.
Edit to make it more clear what I mean:
function first(){
second();
// will i have access to whatever there is inside function second since i am calling it here ? or it doesn't work that way?
}
function second(){
let a = 12;
third();
}
function third(){
fourth()....
}

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

How do Anonymous functions work [duplicate]

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.

Why shouldn't I make functions within a loop in Javascript? [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
In JavaScript, what are specific reasons why creating functions within a loop can be computationally wasteful?
(2 answers)
Closed 8 years ago.
I checked over my script the other day with JSFiddle and got a warning on one of the lines: Don't make functions within a loop.
for (x = 0; x < 10; x++) {
if (moment(now) > moment(then)) {
doIt(x); // do it now
} else {
timeTillEnd = moment(then) - moment(now);
setTimeout(function () {
doIt(x); // do it later
}, timeTillEnd); // <-- flagged here
}
}
Why shouldn't I make functions within a loop in Javascript?
Also: Could the usage of a function in the particular situation shown here be problematic?
What you are trying to do is probably wrong, the x variable might not be what you expect it to be. See the following link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Creating_closures_in_loops.3A_A_common_mistake
And they are also relatively expensive to create.
Each function comes with the closure of the variables it uses, that is an unnecessary overhead if you are doing "normal imperative programming" and just want to make the code look clearer by defining inner functions for sub-tasks:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Performance_considerations
In your case, it seems that you actually need a function with its closure, since you are deferring some computation, but make sure that you do the proper value capture.
Because it can lead to unexpected closure behaviour (the captured variable will have the value assigned in the last iteration of the loop). You will also get a new instance of the function for each loop which is wasteful of resources.
Modern browsers take a third argument for setTimeout which is the argument to the function. See here. This also gets rid of the problems with closures.

Categories