How does "makeAddFunction" in Eloquent JS work? - javascript

I'm trying to learn Javascript by reading Eloquent Javacript. I'm on the chapter dealing with functions and I'm stuck trying to figure out how the code below works. I don't see how the add function ever gets called. I see them calling addTwo and addFive but those names are different than add. The result of this code being run is 9. Can someone please explain this to me.
function makeAddFunction(amount) {
function add(number) {
return number + amount;
}
return add;
}
var addTwo = makeAddFunction(2);
var addFive = makeAddFunction(5);
show(addTwo(1) + addFive(1));

In makeAddFunction, a function is created, called add. This function is returned.
makeAddFunction is called twice with 2 different parameters, and stored in two variables, addTwo and addFive.
Calling addTwo() and addFive() is calling the functions created by add(), with the "amounts" 2 and 5 respectively.
addTwo(1) + addFive(1) == (1 + 2) + (1 + 5) == 9
Sometimes these types of 'closures' are called Builders, or Factories. The makeAddFunction 'builds' a special version of add based on the parameter you pass to makeAddFunction.
The addTwo function would look like:
function addTwo(number) {
return number + 2;
}

The makeAddFunction create a closure that sets amount as whatever number you pass in and returns a function that will add that amount to whatever number you pass to the new function and return it.

My best advice is you try to learn a bit about Javascript closures. Really. I might not be the answer you are looking for, but it is the best you can do if you want to understand what's happening there.
Get yourself a copy of any good javascript book. Let me suggest 'Javascript - The Good Parts' by Douglas Crockford.
For some of us, Javascript closures were not something we grokked. I hope it's easier for you.
Anyway, makeAddFunctionis a function creator. It creates new functions which are tied to the parameter you passed to makeAddFunction. Therefore, the addTwo variable receives and stores a new function, which you can invoke later by appending parentheses to it, i.e. addTwo().
The parameter you pass to addTwo, i.e. 1on invokation addTwo(1) is passed to the add function, because addTwo is nothing more than an add function where the amount var has a fix value of 2.

var addTwo = makeAddFunction(2);
When you call makeAddFunction(2) initially, the amount var is within its function scope where add can see it. addTwo now is set to the add function that makeAddFunction(2) returned.
addTwo(1)
Remember addTwo is now set to what makeAddFunction(2) returned, which is the function add, and amount is set to 2 within makeAddFunction(2)'s scope. add just returns its argument (1), plus the amount (2) in makeAddFunction(2)'s scope.
The same goes for addFive(5).
Javascript Ninja or The Good Parts are good reads that explain closures in detail. I'd highly suggest picking up those.

Follow the SO Linked/Related Questions on the right. Anyway ..
This is explained the article, albeit with a lot of fluff. Anyway, with a bit of fluff-cutting here is a "annotated" version:
.. functions [do] not just package up [some code to run], but also an environment. [..] a function defined inside another function retains access [to lexical variables (like "amount")] that existed in [the outer function] at the point when [the inner function] was defined.
Thus, the [inner] add function in the above example, which is created when makeAddFunction is called, captures an environment [including the "amount" variable of the outer function]. It packages this environment, together with [the code to run], into a value [(which is a fancy way to say functions are just objects)], which is then returned from the outer function.
When this returned function ([which has been assigned to] addTwo and addFive) is called, [the called function has access to] the captured environment ([and the "amount" variable which still contains the value initially passed to makeAddFunction]). These two values ([which are currently named by] "amount" and "number") are then added, and the result is returned.
I am not found of the original usage of "value" and have edit those parts a good bit - in JavaScript, variables (not values) are bound in closures.

Javascript relies pretty heavily on higher-order functions. Functions can be returned, assigned to variables, and passed around as values. This comes in handy in a lot of situations, especially when dealing with evented programming (JS's direct lineage from the its most prolific implementation in the browser.)
http://en.wikipedia.org/wiki/Higher-order_function
What you are seeing is a function that creates a function. It could be considered a "factory" for a function with one preset argument.

Related

how does "multiply(arr, n-1)*arr[n-1]" work?

I have this problem on freeCodeCamp as I'm learning JavaScript.
I'm trying to understand this block of code.
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n-1)*arr[n-1];
}
}console.log(multiply([2,2,4],3));
As a whole, I understand what this code above does. But not this line below.
multiply(arr, n-1)*arr[n-1];
There's already a about post this specific problem here, but I have read all of the comments and I did not understand.
What I don't understand specifically is (arr, n-1). Exactly what does that do? The rest of the line I can understand after a long time thinking, it's just that little piece that I can't make sense of.
What I don't understand specifically is "(arr, n-1)". Exactly what does that do?
This is the argument list for the function call of the multiply() function. You cannot understand this in isolation because it belongs to the function call.
In other words, the syntactic element is not (arr, n-1), it is multiply(arr, n-1).
A parameter is kind of like a "hole" that you leave in a function definition. Parameters allow you to make functions re-usable in different contexts.
For example, a function like this:
function doubleTheValueSix() {
return 2 * 6;
}
is not very useful because it can be used for only one very specific thing. However, we can make it more useful by parameterizing it:
function doubleAnyArbitraryValue(n) {
return 2 * n;
}
is much more useful. Here, n is called the parameter and (n) is called the parameter List. In this case, there is only one parameter in the parameter list, but there can be arbitrary many, including – as we have seen above – zero.
An argument is what you pass to a function call to "fill in" the "hole" left by the parameter in the function definition.
So, in this code here:
doubleAnyArbitraryValue(42)
The literal 42 is the argument which gets bound to the parameter n inside the function body of doubleAnyArbitraryValue. In other words, everywhere n appears in the function body, it gets replaced with 42.
So, in this case, 42 is the argument and (42) is the argument list.
What this means in your particular code snippet is the following:
Look up the name multiply in the local scope. It could be a function defined in the local scope (or in an enclosing scope), a const, a let, or a var defined in the local scope (or in an enclosing scope).
Call the object you found in step #1, passing the result of evaluating the expressions in the argument list as arguments:
Evaluate the expression arr (which essentially means: look up the name arr in the local scope; it could be a const, a let, or a var defined in the local scope (or in an enclosing scope)).
Evaluate the expression n-1:
Look up the name n in the local scope; it could be a const, a let, or a var defined in the local scope (or in an enclosing scope).
Apply the Binary Arithmetic Subtraction Operator - to the result of step 2.1.1 and the Numeric Literal 1.
You can find the details about how function calls work in subsection 13.3.6 Function Calls of the ECMAScript Language Specification. (Note, the version I linked to is the Living Document which always shows the current state of the next release, but that doesn't matter in this case – how function calls work fundamentally hasn't changed since ECMAScript was still called LiveScript in 1995 and even before that when it was still called Mocha.)

function creation as a parameter?

I have tried asking this on specialty forums, and no one answers this for me, But I am hoping someone here can. Below is the snippet of code in question, and I know how it all works except for 2 bits of it.
this.data = allItems().filter(function(item) {
return this.includes(item);
}, this);
As stated above, I understand all but two bits of the code above: What is this type of function called? a call back? There is no function called "item" or a variable within the main function called "item". Lastly, why is "this" a part of the snippet?
Sorry if this isn't enough information, I am trying to be as thorough as I can with this question as I am not familiar with this style of scripting. I have done some research on this subject, and the closest explanation as I can get is a private function, but as I mentioned above, there is no function called "item" anywhere.
Javascript is a bit of a strange language. For those of us that learned a compiled programming language first, it shares a visual aesthetic but the behind-the-scenes are very different.The first thing to understand is that in javascript every function as a special reference called this. It references the current iteration of the function.
Think of it like this: there is a class called Human, which defines a set of properties common to all humans -- we have a height and weight, a name, eye color, hair color, etc. But me, being 5'8", 200 lbs, hazel eyed, and bald is not the same description as you, or any other human being. While there could definitely be another human with those characteristics, we are not the same.
var Human = function(name, height, weight, eye_color) {
this.name = name;
this.height = height;
this.weight = weight;
this.eye_color = eye_color;
}
var me = new Human('Jhecht', '5.8', 200, 'hazel');
alert(me.name); //Alerts 'Jhecht'
var you = new Human('Gatene', '6.0', 190, 'brown');
alert(you.name); //Alerts 'Gatene'
The this in the code ensures that the variables me and you mark us as individuals. This way, even though we can both have things in common, it is understood that we are not the same. It also makes it so that you can check on that information later. Without the this I would just be setting each variable equal to itself (name=name) which gives me no way to look at its contents later. If I removed the this.name and replaced it with name, I would no longer get my expected result if I tried to call alert(me.name)(I would most likely get an undefined value) When used on event listeners for HTML elements, this will refer to the HTML element, unless you tell it otherwise.
Functions in javascript are also a little less rigid (and I don't feel like that's the correct word, but it's the best one I've got) than functions in other languages. Notice in my code above I set my function like so:
var Human = function(name, height, weight, eye_color) ...
I could have also created that function like so:
function Human(name, height, weight, eye_color)...
and the outcome would be the same.
So in your code snippet, let's go through line by line.
this.data = allItems().filter(function(item) {
return this.includes(item);
}, this);
this.data is saying "the data variable on this instance of the function call this code is from" is equal to allItems() which presumably returns an array of items, is filtered down by a function. Since Javascript allows for something called 'anonymous' functions, aka functions without a name, we create an anonymous function (non-named function) which accepts a named argument of item.
the function being passed to the .filter method in line 1 will return the result of the includes method (most likely defined somewhere previously in your code), which was being passed the value of our argument from line 1, item.
Ends the function definition with }. the next portion goes back to what I said before, this refers to the current function call, unless you instruct it not to. the , this); is the programmer saying "on this function, which I declared above, I want this to refer to the object I am using currently."
This part is tricky, and it will definitely take some time to understand so if you're not entirely sure don't worry too much about it.
The filter function accepts a parameter. It is expected that this parameter will be a function with at least 1 parameters (item)
Your code snippet is passing an anonymous function as this parameter:
function(item) {
return this.includes(item);
}
thus fulfilling the expectations of the filter function
What is this type of function called? a call back?
It's an anonymous function (because it has no name), which is being passed as an argument to filter, and yes, it could be and is called a callback.
There is no function called "item" or a variable within the main function called "item".
You're misunderstanding basic function syntax. function(item) does not refer to anything called item, a function or otherwise. It is defining an anonymous function with item as its single formal parameter.
Lastly, why is "this" a part of the snippet?
Read the documentation for filter, and in particular the thisArg parameter, the second parameter, which specifies the value to use as this when the callback function is called. In this case, this is being specified, which is the this of the surrounding context, which is the same object which holds the property data, as well as the method known as includes.
It could be more easily written without using the thisArg parameter by using arrow functions, as
this.data = allItems().filter(item => this.includes(item));

Why do objects have to be initialized first before use ? Constructor function vs Object.create [duplicate]

This code always works, even in different browsers:
function fooCheck() {
alert(internalFoo()); // We are using internalFoo() here...
return internalFoo(); // And here, even though it has not been defined...
function internalFoo() { return true; } //...until here!
}
fooCheck();
I could not find a single reference to why it should work, though.
I first saw this in John Resig's presentation note, but it was only mentioned. There's no explanation there or anywhere for that matter.
Could someone please enlighten me?
The function declaration is magic and causes its identifier to be bound before anything in its code-block* is executed.
This differs from an assignment with a function expression, which is evaluated in normal top-down order.
If you changed the example to say:
var internalFoo = function() { return true; };
it would stop working.
The function declaration is syntactically quite separate from the function expression, even though they look almost identical and can be ambiguous in some cases.
This is documented in the ECMAScript standard, section 10.1.3. Unfortunately ECMA-262 is not a very readable document even by standards-standards!
*: the containing function, block, module or script.
It is called HOISTING - Invoking (calling) a function before it has been defined.
Two different types of function that I want to write about are:
Expression Functions & Declaration Functions
Expression Functions:
Function expressions can be stored in a variable so they do not need function names. They will also be named as an anonymous function (a function without a name).
To invoke (call) these functions they always need a variable name. This kind of function won't work if it is called before it has been defined which means Hoisting is not happening here. We must always define the expression function first and then invoke it.
let lastName = function (family) {
console.log("My last name is " + family);
};
let x = lastName("Lopez");
This is how you can write it in ECMAScript 6:
lastName = (family) => console.log("My last name is " + family);
x = lastName("Lopez");
Declaration Functions:
Functions declared with the following syntax are not executed immediately. They are "saved for later use" and will be executed later, when they are invoked (called upon). This type of function works if you call it BEFORE or AFTER where is has been defined. If you call a declaration function before it has been defined Hoisting works properly.
function Name(name) {
console.log("My cat's name is " + name);
}
Name("Chloe");
Hoisting example:
Name("Chloe");
function Name(name) {
console.log("My cat's name is " + name);
}
The browser reads your HTML from beginning to end and can execute it as it is read and parsed into executable chunks (variable declarations, function definitions, etc.) But at any point can only use what's been defined in the script before that point.
This is different from other programming contexts that process (compile) all your source code, perhaps link it together with any libraries you need to resolve references, and construct an executable module, at which point execution begins.
Your code can refer to named objects (variables, other functions, etc.) that are defined further along, but you can't execute referring code until all the pieces are available.
As you become familiar with JavaScript, you will become intimately aware of your need to write things in the proper sequence.
Revision: To confirm the accepted answer (above), use Firebug to step though the script section of a web page. You'll see it skip from function to function, visiting only the first line, before it actually executes any code.
Some languages have the requirement that identifiers have to be defined before use. A reason for this is that the compiler uses a single pass on the sourcecode.
But if there are multiple passes (or some checks are postponed) you can perfectly live without that requirement.
In this case, the code is probably first read (and interpreted) and then the links are set.
I have only used JavaScript a little. I am not sure if this will help, but it looks very similar to what you are talking about and may give some insight:
http://www.dustindiaz.com/javascript-function-declaration-ambiguity/
The body of the function "internalFoo" needs to go somewhere at parsing time, so when the code is read (a.k.a parsing) by the JS interpreter, the data structure for the function is created and the name is assigned.
Only later, then the code is run, JavaScript actually tries to find out if "internalFoo" exists and what it is and whether it can be called, etc.
For the same reason the following will always put foo in the global namespace:
if (test condition) {
var foo;
}

Definition of 'closures'

Let me ask one question. It's about closures in JavaScript, but not about how they work.
David Flanagan in his "JavaScript The Definitive Guide 6th Edition" wrote:
...Technically, all JavaScript functions are closures: they are objects, and they have a scope chain associated with them....
Is this correct? Can I call every function (function object + it's scope) a "closure"?
And stacks' tag "closures" says:
A closure is a first-class function that refers to (closes over) variables from the scope in which it was defined. If the closure still exists after its defining scope ends, the variables it closes over will continue to exist as well.
In JavaScript every function refers to variables from the scope in which it was defined. So, It's still valid.
The question is: why do so many developers think otherwise? Is there something wrong with this theory? Can't it be used as general definition?
Technically, all functions are closures. But if the function doesn't reference any free variables, the environment of the closure is empty. The distinction between function and closure is only interesting if there are closed variables that need to be saved along with the function code. So it's common to refer to functions that don't access any free variables as functions, and those that do as closures, so that you know about this distinction.
It's a tricky term to pin down. A function that's simply declared is just a function. What makes a closure is calling the function. By calling a function, space is allocated for the parameters passed and for local variables declared.
If a function simply returns some value, and that value is just something simple (like, nothing at all, or just a number or a string), then the closure goes away and there's really nothing interesting about it. However, if some references to parameters or local variables (which, mostly, are the same) "escape" the function, then the closure — that space allocated for local variables, along with the chain of parent spaces — sticks around.
Here's a way that some references could "escape" from a function:
function escape(x, y) {
return {
x: x,
y: y,
sum: function() { return x + y; }
};
}
var foo = escape(10, 20);
alert(foo.sum()); // 30
That object returned from the function and saved in "foo" will maintain references to those two parameters. Here's a more interesting example:
function counter(start, increment) {
var current = start;
return function() {
var returnValue = current;
current += increment;
return returnValue;
};
}
var evenNumbers = counter(0, 2);
alert(evenNumbers()); // 0
alert(evenNumbers()); // 2
alert(evenNumbers()); // 4
In that one, the returned value is itself a function. That function involves code that makes reference to the parameter "increment" and a local variable, "current".
I would take some issue with conflating the concept of a closure and the concept of functions being first-class objects. Those two things really are separate, though they're synergistic.
As a caveat, I'm not a formalist by basic personality and I'm really awful with terminology so this should probably be showered with downvotes.
I would try to answer your question knowing you were asked about what closures are during the interview (read it from the comments above).
First, I think you should be more specific with "think otherwise". How exactly?
Probably we can say something about this noop function's closure:
function() {}
But it seems it has no sense since there are no variables would bound on it's scope.
I think even this example is also not very good to consider:
function closureDemo() {
var localVar = true;
}
closureDemo();
Since its variable would be freed as there is no possibility to access it after this function call, so there is no difference between JavaScript and let's say C language.
Once again, since you said you have asked about what closures are on the interview, I suppose it would be much better to show the example where you can access some local variables via an external function you get after closureDemo() call, first. Like
function closureDemo() {
var localVar = true;
window.externalFunc = function() {
localVar = !localVar; // this local variable is still alive
console.log(localVar); // despite function has been already run,
// that is it was closed over the scope
}
}
closureDemo();
externalFunc();
externalFunc();
Then to comment about other cases and then derive the most common definition as it more likely to get the interviewer to agree with you rather than to quote Flanagan and instantly try to find the page where you've read it as a better proof of your statement or something.
Probably your interviewer just thought you don't actually know about what closures are and just read the definition from the book. Anyhow I wish you good luck next time.
The definition is correct.
The closure keeps the scope where it was born
Consider this simple code:
getLabelPrinter = function( label) {
var labelPrinter = function( value) {
document.write(label+": "+value);
}
return labelPrinter; // this returns a function
}
priceLabelPrinter = getLabelPrinter('The price is');
quantityLabelPrinter = getLabelPrinter('The quantity is');
priceLabelPrinter(100);
quantityLabelPrinter(200);
//output:
//The price is: 100 The quantity is: 200
https://jsfiddle.net/twqgeyuq/

Need help to understand this immediately invoked function example

This is a fragment of code I've found from a tutorial, but I can't understand clearly it's purpose. Here is the example:
app.js
var oojs = (function(oojs){
return oojs;
}(oojs || {}));
The first part I'm confused is why it is called with the same parameter as it's argument?
The second doubt is why if there is no "oojs" should call the function with an object literal as parameter? Is this necessary?
Finally why it should return the same as it's function name (oojs).
Maybe it's a way to create an object, but if someone could help me the need of this I will really appreciate.
This is just scoping rules in JavaScript. Whenever a new function is created, a new variable scope is created. The parameter name oojs is indeed the same identifier as the outside parameter oojs but it's more local.
Here is a simplified example
function foo(x){
console.log(x + 2);
}
var x = 3; // this is a different x, it belongs to the outer scope, and not the function
foo(x); // logs 5, since x is passed to the function, then x + 2 is logged
In this code example, the idea is to only change oojs if it doesn't exist, and then set it to the return value of the immediately invoked function expression. It's similar to a composing module pattern. Personally, I find the syntax rather confusing to read when a lot of lines are involved.

Categories

Resources