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.
Related
I found that there are these two ways that a variable property value can be updated on a function call
Example 1:
function bar( arg ) {
return arg + 1;
}
var foo = {
num: 1
};
foo.num = bar( foo.num );
console.log( foo.num );
Example 2:
function bar( arg ) {
arg.num = arg.num + 1;
}
var foo = {
num: 1
};
bar( foo );
console.log( foo.num );
I want to know what are the proper naming convention for each of the method calls.
Also can anyone explain, how it is possible to update the original variable value inside a closed function operation as shown in example 2?
Primitive parameters (such as a number) are passed to functions by
value; the value is passed to the function, but if the function
changes the value of the parameter, this change is not reflected
globally or in the calling function.
If you pass an object (i.e. a non-primitive value, such as Array or a
user-defined object) as a parameter and the function changes the
object's properties, that change is visible outside the function.
Source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
Well in javascript objects are passed by reference so when you pass a object to a function you're passing it's memory reference not a copy.
So when you update value in the function it updates the value at reference.
function bar(arg) {
arg.num = arg.num + 1;
}
var foo = {
num: 1
};
bar(foo);
console.log(foo.num);
When you pass a primitive value it is passed by value. It passes a copy of value so whatever changes you do in close function will not affect the original value.
function bar(arg) {
arg = arg + 1;
}
var foo = 1
bar(foo);
console.log(foo);
I want to know what are the proper naming convention for each of the methods.
There are no naming conventions for functions (I would only call them methods if they are directly associated to an object), except thar the name is camelCase. However there is a convention in functional programming that functions that return something are pure (they do not change anything, but just return something new, like your first function), and functions that return nothing are impure, they change something. Wether you strictly follow that pattern depends on your codingstyle, I follow that often but not always. It is also a bit harder in JS as JS is not typed.
also can anyone explain, how it is possible to update the original variable value inside a closed function operation as shown in example 2?
It is impossible. If you pass a number, it is passed as a value, you have no way to find out where that number belongs to. Thats a good thing as you can always keep track which function is able to mutate an object. bar(foo) is, bar(foo.num) is not.
I am currently trying to perform some simple actions on a variable that I've given the value of zero. First of all, I am declaring a variable and giving it a value (0). Secondly, I am creating a function which is supposed to increment the value of my variable when the function is invoked. This is my code:
var orderCount = 0;
function takeOrder(orderCount) {
return orderCount++;
}
takeOrder(orderCount);
takeOrder(orderCount);
alert(orderCount);
The exptected result of the code snippet above would be "2", since the function is invoked twice and the number 0 therefore should be incremented twice.
I have also tried incrementing the variable "orderCount" with the following code instead of the one posted above:
function takeOrder(orderCount) {
return orderCount + 1;
}
Neither works. What am I doing wrong?
Remove orderCount from your parameter list, and don't include it as an argument when calling the function. By specifying it as a parameter, you're shadowing (hiding) the global variable that takeOrder closes over.
var orderCount = 0;
function takeOrder() {
// ^----- don't include `orderCount` as a parameter
return orderCount++;
}
takeOrder(); // <== don't specify it when calling the
takeOrder(); // <== function (though it would just be ignored)
alert(orderCount);
Couple of facts:
Parameter of the function acts like a function-scoped variable. You
can re-assign it, increment it etc. All these changes are gone once function finishes its execution.
Local variables named the same as "global" ones hide the latter
inside function body and therefore make all in-function changes isolated from the outside world.
Changing the parameter name will not help either, because the value of the global variable will be placed on the function call stack. In fact, passing any variable is not helpful at all.
Typical solution is to not use parameters at all and make your function change variable in the outside scope directly.
It is, however, possible to emulate passing a "reference" to a variable. If you really want your function to not know the global variable name:
var order = { count: 0 };
var anotherOrder = { count: 0 };
function takeOrder(order) {
order.count++;
}
takeOrder(order);
takeOrder(order);
takeOrder(anotherOrder);
console.log("Order:"+order.count);
console.log("Another order:"+anotherOrder.count);
Simply call the function without passing the parameter
var orderCount = 0;
function takeOrder() {
return orderCount++;
}
takeOrder();
takeOrder();
alert(orderCount);
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.
I have looked at many examples but still cant figure how the return statement works.
function One() {
var newVal = 0;
Too();
console.log(newVal);
}
function Too(newVal) {
++newVal;
return(newVal);
}
Shouldn't this print 1 to the console? What I'm really trying to do is to have function Too increase newVal by 1 every time it's called. But I cant even figure out how to get the return statement to work. I should mention I don't want to use global variables. Thanks for any help.
Shouldn't this print 1 to the console?
No. The newVal inside Too is not the newVal inside One. They're completely separate.
What I'm really trying to do is to have function Too increase newVal by 1 every time it's called.
It can't, JavaScript doesn't have any mechanism for passing variables by reference like some other languages do (C#'s ref and out arguments, for instance). The closest you can come is to pass in a reference to an object and modify the object's state (which is really quite different and I won't go into it here as it would confuse things :-) ).
None of which has anything to do with the return statement.
The simplest way to do what you were describing is this:
function One() {
var newVal = 0;
newVal = Too(newVal);
console.log(newVal);
}
function Too(arg) {
++arg;
return arg;
}
Here's what happens when we call One:
A local variable called newVal is created.
Its value is set to 0.
A copy of its value is passed into the function Too as an argument. This has no link back to the newVal variable.
Too is called, accepting that value in its arg argument (arguments in JavaScript are effectively local variables).
Too increments the value in arg.
Too returns a copy of the value held by arg as its return value.
The return value of Too is assigned to the variable newVal.
We output that value (by passing it into console.log).
No, it shouldn't. The return statement establishes what the value of the function invocation will be in the calling environment when control returns there. Since your calling environment doesn't use the return value, there's no net effect.
Here's how you'd get the value back:
newVal = Too(newVal);
If you want to make a function that acts as a counter, such that each time you call it you get a new number back, you can do something like this:
var counter = function(initial) {
var c = initial || 0;
return function() {
return c++;
};
}(0);
What that does is use an anonymous function to set up a persistent environment for another function, which is returned from the outer one when it's (immediately) invoked. The returned function can then be called to return a new value from its private counter (the variable "c"):
var currentCount = counter();
alert(currentCount); // 0, the first time
currentCount = counter();
alert(currentCount); // 1, and so on
If a function return a value you need to call that function in your console.log or capture the returned value.
function One() {
var newVal = 0;
console.log(Too(newVal));
}
function Too(newVal) {
++newVal;
return(newVal);
}
I'm starting learning javascript for a project, I've found a script that does a part of what I need to do, I'd like to know how it works, both for me and in case it needs to be modified.
Originally it was used inside the page, now I've put it in a file on its own and does not work anymore, so I'm dividing it in parts, because I fail to get the whole thing.
Here is what bother me most for now:
1) Is this a declaration of a function? What is its name? How can it be invoked?
(function() {
//some code
})();
2) No clue of what is going on here
var VARIABLE = VARIABLE || {};
3) Am I defining the implementation of methodCall here? Something like overriding a method in Java?
VARIABLE.methodCall = function(parameter) {
console.log("parameter was: " + parameter);
};
Thank you in advance for your help.
1) creates an unnamed function and executes it. this is useful for creating a scope for local variables that are invisible outside the function. You don't need to invoke it aside from this, the '()' at the end does that for you.
2) if variable is null/undefined, set it to an empty object.
3) yes, that should work as you expect, you can call VARIABLE.methodCall(parameter)
in response to your comment, here is a common example
function foo (VARIABLE) {
var VARIABLE = VARIABLE || {};
}
(function() {
//some code
})();
simply runs //some code, but variables in it will not remain, since the function() { } block introduces a new inner scope.
function() { } notation is called a closure, it allows variables be functions. For example,
(function() { })() is a common JavaScript idiom. After the ), there is (), which invokes the expression before as function, so (callback || function(x) { return x; })(x) is allowed.
var a = function a() { return 1; }
var VARIABLE = VARIABLE || {}; uses the short-circuit OR, If VARIABLE is not defined, VARIABLE will be set to {}, an empty object. (otherwise, if VARIABLE exists, it will not change)
x = A || B means "If A evaluates to TRUE, x is A, otherwise, x is B.".
VARIABLE.methodCall, as you said, adds methodCall to VARIABLE, without erasing other values in VARIABLE