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

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

Related

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

Why can I not .bind(this) when a function is directly declared

Given the following:
function x() {
this.abc = 1;
function f1() {
alert(this.abc);
}.bind(this)
var f2 = function b() {
alert(this.abc);
}.bind(this);
}
What I would like is for the "this" of the outer function to be available inside the f1 and f2 functions.
Why is it that VS2013 tells me there's a syntax error with the bind(this) on function f1() ?
There's a difference between a function declaration statement and a function instantiation expression. Both involve the keyword function, but a declaration statement cannot immediately be used as a reference to a function. A function instantiation expression is part of the expression grammar, so it can be used freely in that context as a reference to a function because that's what it evaluates to.
You can of course do this:
(function a() {
}).bind(this);
though without using the return value from .bind() it's not very useful.
If the first token in a statement is function, then you've got a function declaration statement. If the first token is not function, then you've either got another sort of keyword-introduced statement (for, return, var, try, whatever), or else you've got an expression statement. In that expression (or in any expression in another context), your function instantiations are part of the expression grammar and the value can be used as a reference to a function.
Here's another way to think about the problem. Let's pretend that there is only one way to instantiate a function in JavaScript, and that's the function expression. That is, let's pretend that any use of the function keyword means to instantiate a function and return a reference to that function as it's value.
Now, thinking generally about expressions and the things that participate in expressions, the point is to compute some sort of value. When you need the value 5 as part of an expression, you put 5 in its place and that's that. By itself, 5 is a valid expression, so this is not a syntax error:
5;
What does that do, however? It does nothing. Similarly, in our make-believe JavaScript without function declaration statements,
function foo(a, b) {
return a + b;
};
would also do nothing at all. What would happen is simply that the function would be instantiated but thrown away because the value — the reference to the instantiated function — is not saved as the value of a variable or passed to some function or anything else. In this make-believe JavaScript, you'd use
var foo = function(a, b) {
return a + b;
};
all the time.
The language design does have function declaration statements, however. As a simplifying approach, the language just recognizes a statement whose first token is the keyword function as a completely different sort of statement than an expression statement that happens to contain a function instantiation. There are other ways in which the problem could have been addressed (such as the use of a different keyword), but I suspect that there'd still be confusion.
Note that there are JavaScript programmers who strongly prefer using var declarations for functions. It's a matter of style really.

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.

How does "makeAddFunction" in Eloquent JS work?

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.

Javascript: difference between the different forms of functions

# Version A - Function Declaration Statement
// Some JavaScript code
function a() {
// code within function
}
//Some more JavaScript code
# Version B - Function Expression
// Some JavaScript code
var b = function () {
// code within function
};
// Some more JavaScript code
I've been reading JavaScript: The Definitive Guide and I wanted to make sure I'm understanding how these 2 versions are being processed by JavaScript. I'll explain my understanding for each version below:
Version A
JavaScript scans the script at the global scope and identifies all variable and function definitions and hoists them to the top. Variable assignments and function evaluations won't happen yet.
For the function a(), JavaScript will then package up the global context and associate it with the scope chain of the function. At this point, the function a() will know all the variable and function definitions in Step 1.
JavaScript does NOT evaluate the function a() and therefore doesn't know anything about the local context within the function. This will remain true until the function is invoked.
Version B
Same as step 1 from above - JavaScript scans the script at the global scope and identifies all variable and function definitions and hoists them to the top. Because the variable b is hoisted to the top, the script is equivalent to this:
var b;
// Some JavaScript code
b = function (){ /* code within function */ };
// Some more JavaScript code
When JavaScript comes to variable b's assignment, it sees that an anonymous function object is being defined. When JavaScript defines the function, it will package up the context in which the function is defined (in this case, it's the global context) and associate it with the scope chain of the function. At this point, the anonymous function will know all the variable and function definitions in Step 1 which includes var b being undefined.
Because JavaScript sees that the function is being used as an expression in a variable assignment, it will evaluate the function expression. When it evaluates the function expression, it will again hoist all variable and function definitions within the local scope to the top and if there are any function declaration statements within this function expression, it'll package this local context and add it to the scope chain of this function.
A function object is returned when the function is evaluated and then the function object is assigned to var b.
If you could comment on each of the versions and let me know if my understanding is accurate, that'd be great.
Theory is nice, but in real life browsers use their own dialect (as a result of using their own engine and added browser-candy).
For instance IE doesn't care that your script-tag specifies 'text/javascript'. It'll use its own JScript anyway.
So (to devise a polyglot EcmaScript dialect) it helps to also understand that the theory might not work in the same manner in real life.
For example, a Named function expression is treated as BOTH — function declaration AND function expression in IE(JScript):
typeof g; // "function"
var f = function g(){};
See this link for some of those examples:
http://kangax.github.com/nfe/#jscript-bugs
Actually, here is a rather complete and 'semi-official' (by Pratap Lakshman from MS) overview of JScript deviations from ES3:
http://wiki.ecmascript.org/lib/exe/fetch.php?media=resources:jscriptdeviationsfromes3.pdf
Lastly I'd want to point to this very helpful video where Douglas Crockford explains things some more thorough in 'Crockford on JavaScript - Act III: Function the Ultimate':
http://youtu.be/ya4UHuXNygM
Hope this helps!

Categories

Resources