How to call this function in Javascript?
As it takes n as its outer function's parameter and it also needs another parameter i in its function inside, but how to call it?
function foo(n) {
return function (i) {
return n += i } }
Call the returned value of the function:
foo(1)(2);
It a classic closure example: it does return a function which has access to the n variable.
var counter = foo(0);
counter(1); // 1
counter(2); // 3
counter(5); // 8
This is a function that returns a function. Often you would want a reference to that function, Like this
foofn = foo(7);
result = foofn(7);
You could also just call the function right away
result = (foo(7))(7);
What the function does? Well that wasn't really your question...
This is the way we usually use JavaScript closures, first function creates a scope to keep the n variable safe to be used in the inner function:
var n = 11;
var myfunc = foo(n);
now you can call your myfunc function, with a simple i argument, whereas it uses n without you needing to pass it directly to your function:
myfunc(10);
so if you want to just call it, once it is created, you can do: foo(11)(10);
But in these cases we don't usually call them like this, they are usually supposed to be used as a callback or something like it.
Related
I'm quite clear with the concept of closure in JavaScript but at some point i got confused when i need to solve the questions.
clos() => print("AB")
clos()() => print("ABC")
clos()()() => print("ABCC")
clos()()()() => print("ABCCC")
clos()()()()('xyz') => print("ABCCCxyz")
I have to implement above method in javascript
Can someone help me in implementing the above use case.
Solution Tried
function clos(...n){
let counter = 0;
const initial = "AB"
return function(param) {
counter = counter + 1;
return initial + "C".repeat(counter)
};
}
What you are trying to implement is not possible. However, there's one alternative that you can try, which will work.
Here's the code:
function c() {
this.counter = 0;
const initial = 'AB';
this.recursive = function(param) {
this.counter += 1;
return typeof param === 'undefined' ? initial + 'C'.repeat(counter - 1) + param : this.recursive;
}
return this.recursive
}
As you can see, instead of declaring a temporary variable, we are binding to the function via the this keyword the counter variable.
The question would be, how can the this keyword be used inside the recursive function, since it is not defined anywhere? Well, the reason is because the recursive function it is an anonymous function. From the mdn docs, regarding the name of a function:
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
Anonymous functions do not have a "self", therefore the this keyword does not work in them, it is not defined. What they use instead, it is they closure's self, in this case the c function, which does have a self as it is not an anonymous function, and it has the counter prop defined.
Finally, explaining the code a bit, JS must return a value. In this case, you want to keep returning functions and in the last call return a string. It is not possible to know if which is the last call of the returning function. What we do instead is to pass an argument to the last call, which is what is checked in the ternary operator:
If param is not undefined, meaning that a string has been passed, we will keep returning a function.
Otherwise, we return the resulting value.
See that we increment the counter value on every call.
I'm following a tutorial by Tyler McGinnis on execution contexts, call stacks and closures.
https://www.youtube.com/watch?v=Nt-qa_LlUH0&feature=emb_title
I'm a bit confused with the closure example. I understand a closure is when a function is inside another function. I also understand that the inner function has access to the parent functions arguments (As explained in the video).
My confusion is in the code below is when makeAdder(5) is invoked is the inner function not invoked aswell on the first invokation? Tyler appears to suggest makeAdder is popped off the call stack when first invoked just leaving the inner function untouched.
The second part I don't understand when we call add5(2) this is invoking makeAdder(5) no? How do we add 2 arguments when the parent function only accepts one?
If someone could walk it through step by step of how it's all invoked that would be great!
var count = 0;
function makeAdder(x) {
return function inner(y) {
return x + y;
}
}
var add5 = makeAdder(5);
console.log(add5); // what the call to makeAdder returns
count += add5(2);
console.log(count);
when makeAdder(5) is invoked, is the inner function not invoked as well on the first invocation?
No, it isn't. Only makeAdder is invoked at that time, and makeAdder is not making any calls itself. It merely returns an object, and that object happens to be a function. And returning a function is done without actually invoking it.
when we call add5(2) this is invoking makeAdder(5) no?
It is not invoking makeAdder(5). Earlier on add5 was the result of calling makeAdder(5), and so add5 is that inner function. The special thing happening here is that when you call add5, an "execution context" is restored, which represents the state of affairs inside makeAdder at the moment it returned the function. This practically means that when add5 (the inner function) references the x variable, it will find the value in x it had at the moment makeAdder had been called earlier on.
How do we add 2 arguments when the parent function only accepts one?
Indeed, when we call the parent function, the second argument is not known yet, and we don't need to know it at that moment, since the inner function is not yet executed at that moment. The important thing with the call of the parent function, is that we establish the value of x, which will "live on", even though it can only be accessed by calling the inner function.
And when we call the inner function, we provide the second argument that is needed. The inner function can then combine the "magical" reference it has to the x value (provided when we made the parent call), with the normal argument it receives itself.
A simple way to look at this is as a function that returns a function--which can be called like a normal function because it is. So the first call of the function return type is a function.
Look the following example
function add(x,y){
return x+y;
}
function subtract(x,y) {
return x-y;
}
function calculator(type){
if(type ==='add'){
return add ; //here we are returning a function - the above add function
}
if (type==='subtract')
{
return subtract; // we are returning a function - the above subtract function
}
return null;
}
var fn = calculator('add'); // this call will return the function add which can be called as in below
var result = fn(4,5);
console.log(result) ; ///should print 9
Likewise the first call
var add5 = makeAdder(5);
returns a function which is exactly
function inner(y) { return x+5);
Then you can call add5(2) which essentially execute the above function.
Can someone please explain why we can simply pass a method name to a higher order function and everything works just fine. I know in something like Java I have to call the method words on each element individually. I was told that in Javascript if method signature matches we can simply pass in the name of the function with () and it will work. It is great but I want to know whats going on in the background. Why are we able to do this in javascript ?
function words(str) {
return str.split(" ");
}
var sentences = function(newArr){
return newArr.map(words);
}
In many languages you can pass a reference to a function as an argument to a function. That then allows the host function to use that argument and call that function when appropriate. That's all that is going on in Javascript. When you pass the name of a function without the () after it, you're just passing a reference to the function. That enables the host function to use that function as an argument and call it some time later.
In your specific example, .map() expects you to pass in a function that it will call once for each item in an array. So, you pass the name of a function that will then get called multiple times, once for each item in the array. That function you pass has a bit of a contract that it has to meet. It will be passed three arguments (value, index, array) and it must return a value that will be used to construct a new array.
In Javascript, since there is no argument type checking by the language, it is the developer's responsibility to make sure the arguments of the function you are passing match what the caller of that function will actually pass to it and you have to consult documentation of the calling code itself to know what arguments will be passed to it. You can name the arguments anything you want (that is entirely internal to your function implementation), but the order and the quantity of the arguments is determined by the caller and you must declare your function to match what the caller will provide.
Once thing that confused many in Javascript.
If you pass just a function name, you are passing a reference to the function (something that the host function can call at some later time).
array.map(myFn) // passes a function reference
Or, use an inline function (same outcome):
array.map(function(value, index, arr) {
// code goes here
})
If you put parens at the end of the function name, then the function is executed immediately and the return value of that function execution is what is passed:
array.push(myFn()); // pushes the result of calling myFn()
You are calling the words function repeatedly. You're calling it for each iteration of the map function.
The map function takes a callback which it runs for every iteration. That callback is usually in the form of
function (elementOfNewArr, indexOfNewArr, newArr) { }
Because functions are objects, you can store them on a variable and use that new variable name to call that function, instead of its original one. That's mostly the use of functions as objects. You can toss them around.
let foo = function () { return 'jasper!'; }
let boo = foo;
let ron = boo; // ron() will now return 'jasper!'
So, what you've done is plop in your callback function, though it was defined elsewhere. Since callback functions, like all functions are objects, you can declare that callback function, "saving" it to whatever variable you want and use it in anywhere that you can use it normally.
This is super useful if you have to use the same function in more than one place.
What I believe you are misunderstanding is that functions themselves can be treated the same as other variables in javascript. Consider this example:
var newArr = [1,2,3,4];
newArr.map(function(item){
return item * item;
});
In the above example, a function is passed as an argument to the map() function. Notice that it is described anonymously (no function name given). You can accomplish the exact same thing like this:
var newArr = [1,2,3,4];
function squared(item){
return item * item;
}
newArr.map(squared);
These two examples achieve the same thing, except in the second example, rather than writing the function in place, we define it earlier in the code. If it helps, you can even create the function in the same way as you would any other regular variable:
var squared = function(item){
return item * item;
};
You can pass this function around the same way. If you want to know the difference between defining functions in these ways try var functionName = function() {} vs function functionName() {}
I understand that immediate functions' closures are used to create private variables; but I am not sure of the differences, if any, between the two below patterns:
var fn = function() {
var p = param;
...
};
and
var fn = (function(p) {
...
})(param);
In both cases, p's scope is limited to fn. So why do I sometimes see the second pattern?
Thanks in advance.
The two code snippets you posted do not do the same thing.
In the first one, you are creating a variable fn which stores a reference to a function object. In the second code snippet, you are actually calling the anonymous function, and fn will store the return value.
EDIT
It seems you are unsure of the answers so I'll elaborate. Let's use an example to explain the use of each. I'm going to make up a simple function to demonstrate:
var param = 5;
var fn = function(p) {
return p * 2;
};
When this is done, you will be able to use fn to call the function. So, you could later say:
var someVar = fn(param); // someVar will be equal to 10
On the other hand, your second example:
var param = 5;
var fn = (function(p) {
return p * 2;
})(param);
fn will store the numeric value 10
NOTE
In my answer, I changed your first function to include p as an argument.
I'm not sure if I understand your question, nor if you understand what you are doing?
In your first example, you create an anonymous function, and then store it to the variable fn, but in your second example, you create an anonymous function, run it, and store the output the the variable fn. So unless you're returning p in the second example, it should not be visible at all.
You are free to correct me, if I'm wrong ;)
I'm new to the Javascript world and trying to figure out this assignment my teacher assigned. Here is his description of what is expected:
Build a function that will start the program. Please call it start()
From the start() function, call a function called getValue()
The getValue() function will get a number from the user that will be squared.
Also from the start function, call a function called makeSquare()
The makeSquare() function will square the number that was received by the user in the getValue() function.
Make sure that you display the results of squaring the number inside of the makeSquare() function.
Here is what I have so far:
function start() {
getValue();
getSquare();
}
function getValue() {
var a = prompt("Number please")
}
function getSquare() {
var b = Math.pow(a)
document.write(b)
}
start()
This assignment doesn't have to be working with any HTML tags. I've only got the prompt box to work, nothing else does though. Am I using variables in a way that can't be used?
You were close. But it seems that you don't understand scoping and how exactly to use the pow function.
Math.pow:
Math.pow takes two parameters, the base and the exponent. In your example, you only provide the base. That will cause problems as the function will return the value undefined and set it to b. This is how it should have looked (if you wanted to square it):
Math.pow(a, 2);
Scoping:
Every function has it's own scope. You can access other variables and functions created outside the function from within the function. But you cannot access functions and variables created inside another function. Take the following example:
var c = 5;
function foo() { // we have our own scope
var a = c; // Okay
}
var b = a; // NOT okay. a is gone after the function exits.
We could say that a function is private. The only exception is that we can return a value from a function. We return values using the return keyword. The expression next to it is the return-value of the function:
function foo() {
return 5;
}
var a = foo(); // a === 5
foo() not only calls the function, but returns its return-value. A function with no return-value specified has a return value of undefined. Anyway, in your example you do this:
function getValue() {
var a = prompt("Number please")
}
and access it like this:
// ...
var b = Math.pow(a)
Do you see the error now? a is defined in the function, so it can't be accessed outside of it.
This should be the revised code (Note: always use semicolons. I included them in for you where necessary):
function start() {
getSquare();
}
function getValue() {
var a = prompt("Number please");
return a;
}
function getSquare() {
var b = Math.pow(getValue(), 2); // getValue() -> a -> prompt(...)
document.write(b);
}
start();
As this is an homerwork, I won't give you direct answer, but here's some clue.
In javascript variables are functions scoped. That mean that var a inside getValue is only available in there.
You can return a value from a function.
Functions are first class object in javascript, so you can pass them as parameter to other function and finally call them inside that function.
Am I using variables in a way that can't be used?
Yes, that's where your problem lies. Variables in most programming languages have a scope that determines where they're available. In your case, a and b are local variables of the functions getValue() and makeSquare() respectively. This means they're not available outside the function they're declared in.
Generally speaking, this is a good thing. You should use restricted scopes for your variables to make the "flow" of data through your program clearer. Use return values and parameters to pass data between functions instead of making your variables global:
function start() {
var a = getValue();
makeSquare(a);
}
// Return a value entered by the user
function getValue() {
return prompt("Number please")
}
// Write the square of the `a` parameter into the document
function makeSquare(a) {
var b = Math.pow(a)
document.write(b)
}
Your getValue() needs to return the value, so that you then can pass it to the getSquare() function.
In my opinion, you should always end each line with ;
You will probably need to parse the user input into a number. For that you can use parseFloat(string).
Math.pow takes two arguments, so to get the square, you would have to pass 2 as a second argument when calling it.
I edited your code with some clarifying comments:
function start() {
// Catch the value returned by the function
var value = getValue();
// Pass the returned value to the square-function
getSquare(value);
}
function getValue() {
// Parse the user input into a number, and return it
return parseFloat(prompt("Number please"));
}
// Let the square-function take the user input as an argument
function getSquare(a) {
// Math.pow takes a second argument, which is a number that specifies a power
var b = Math.pow(a, 2);
document.write(b);
}
start();
Another, less good way
In JavaScript, variable-scoping is based on functions. If a variable is declared using the var keyword, it is only available to that function, and its child-functions. If it is declared without the var keyword, or declared outside any function, it becomes a global variable, which will be accessible by any code run on that page.
That said, you could get rid of the var keyword inside the getValue() function, which would make the variable a global. You could then access it from within getSquare() the way you tried in your example.
This is generally not a good idea though, since you would "pollute" the global namespace, and you would be running the risk that you accidentally have another script using a global variable with the same name, which would cause all kinds of trouble, when the scripts start to work with the same variable.
You can try this.
<script type="type/javascript">
function start(){
makeSquare(getvalue());
}
function getvalue(){
return prompt("enter a number");
}
function makeSquare(a){
var result=Math.pow(a,2);
alert(result);
}
start();
</script>