Example 1
function makeCounter() {
let count = 0;
return function() {
return count++;
};
}
let counter = makeCounter();
alert( counter() );
alert( counter() );
Above alerts 0 and 1 respectively.
Example 2
function makeCounter() {
let count = 0;
return function() {
return count+1;
};
}
let counter = makeCounter();
alert( counter() );
alert( counter() );
This alerts 1 and 1 respectively
In programming count++ is equivalent to count+1 , then why is the difference in above two examples. I know its something related to closure property and hoisting. But understand perfectly. Could you guys help.
Note: Please let me know whether I should change the title of the question if it does not make sense.
The expression count++ evaluates count, adds 1, stores the result in count, but the overall result (the net value of count++) is the original value of count.
The expression count + 1 evaluates count, adds 1, and returns the result. The value of count is not changed.
Interestingly, while it's possible to mimic ++count (pre-increment) with an alternative expression
var inc = (count += 1);
there's really no way (I can think of) to mimic count++ cleanly without using a function, because there's no getting around the need for a temporary storage location:
var inc = () => { let tmp = count; count += 1; return tmp }();
The operator semantics of post-increment ++ dates from C in the 1970s and probably earlier, and has been copied by many other languages, including JavaScript. Folklore (as I remember it, being an old person) held that the pre- and post-increment operators were inspired by addressing modes available in the DEC PDP-11 instruction set, but that's always seemed fairly unlikely to me.
In your first example, you are post incrementing, i.e. adding 1 after the declaration and use. If you used ++count (pre incrementing) you would get 1 and 2 in your alerts.
In your second example, you do not store the value of count+1 back into count, so on the second time around, count is still 0 and you get the same result again.
Related
I solved kata on codewars. Acctually I did this by accident and I don't understand why this code works. May you explain it?
Kata:
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
39 --> 3 (because 39 = 27, 27 = 14, 1*4 = 4 and 4 has only one digit)
My solution:
function persistence(num) {
let count = 0;
const arr = [...num.toString()];
const sumArr = arr.reduce((res, val) => (res *= val));
if (arr.length > 1) {
**// Why? How this line works?
// Why it doesn't crashes?
// Why it returns correct counter value and calls the function?**
count += 1 + persistence(sumArr)
}
return count;
}
persistence(39); //3
Why if I do like this, the counter do not save the result:
if (arr.length > 1) {
count += 1
persistence(sumArr) }
Basically, the persistence(sumArr) function acts as a recursive function and returns count of 0 for a base condition that is when the number is single digit. For 39, count is 1+persistence(27)
For 27, count is 1+persistence(14) and for 14, 1+ persistence (4) which is nothing but 1+0 and recursively it adds up to be 3
count is a local variable, only reachable within the scope of persistence(), so when you do a recursive loop, you create a new variable called count but it's in a new scope - the method that you called - it just happens to have the same name as persistence().
It would be totally different if count were a global variable, outside of the scope of the method.
let count = 0;
function persistence(num) {
...
}
Calling persistence() again within persistence() would then use the same variable, not a new one.
This is recursion!
Whenever a function is called by the caller, that function (a.k.a callee) is pushed into the call stack. All the arguments, local variables needed for that function is present there. This is also known as stack frame. The callee is popped out of the stack when it returns to the caller.
In your case both the caller and the callee happened to be the same function. This is called recursion. During recursion, variables local to that function aren't shared. A new stack frame is set up for each callee.
if (arr.length > 1) {
count += 1
persistence(sumArr)
}
Here, the count that you are returning from the callee isn't getting added up with the count of the caller.
If we visualize what is happening then:
persistence(37) = 1 + persistence(27) = 1 + 1 + 1 + 0 // [putting value returned from persistence(27)]
persistence(27) = 1 + persistence(14) = 1 + 1 + 0 // [putting value returned from persistence(14)]
persistence(14) = 1 + persistence(4) = 1 + 0 // [putting value returned from persistence(4)]
persistence(4) = 0
Can I confirm that the reason code snippet 2 (&3) work is because something like: when variableA is fully, or partly, assigned to variableB, variableB always gets what variableA is at the time variableB is (last) initialised?
The aim: to make a function that continually prints "red0", "red1" "red2" etc.
In the first snippet, when we come to log out colorNum, colorNum doesn't dynamically update its num value. It's as if colorNum captures what num at the last moment colorNum was initialised.
num = 0;
colorNum = "red" + num;
function printObject() {
console.log(colorNum);
num++;
}
setInterval(printObject, 2000);
Here colorNum is continually reinitialised. So the updated value of num is captured in colorNum because colorNum is reinitialised after num is updated.
let num = 0;
let colorNum = "red" + num;
function printObject() {
colorNum = "red" + num;
console.log(colorNum);
num++;
}
setInterval(printObject, 2000);
Similarly the return expression of fun is a new expression every-time fun is called. The return expression captures the value of num at the point in time the return expression is created.
num = 0;
fun = function(){
return "red" + num;
}
function printObject() {
console.log(fun());
num++;
}
setInterval(printObject, 2000);
In languages like JavaScript (which is to say, most common programming languages), assigning a primitive value from one variable to another establishes absolutely no permanent relationship between them. The assignment operator is an immediate imperative, after which the two variables sail off into the night.
Also, note that the assignment
colorNum = "red" + num;
is evaluated by first computing the value of the right-hand side. The string constant "red" and the value of num are concatenated. After that has happened, before that result value is assigned, there is no remaining trace of num. All the runtime has is the result value from the concatenation, and that value has nothing whatsoever to do with the variable num.
Now, reference assignment is a different story, to some extent, or at least superficially, but as far as the language actually works it's the same story. So in
let x = { a: "hello" };
let y = x;
y.a = "goodbye";
console.log(x.a);
the value of property "a" in the only object involved will change. However, if subsequently:
let x = { a: "zebra" };
y.a = "giraffe";
console.log(x.a);
it'll still be "zebra" because assigning a new object reference to x has absolutely no effect on y.
From older languages like C, from which JavaScript syntax is at least loosely derived, an assignment expression is literally a request to copy a value stored in memory from one place to another. It looks like algebra but it does not work like pencil-and-paper algebra. JavaScript is conceptually a higher level language, but the semantics are still the same.
You're right in your assumption. In code snippet 2 and 3 num gets added every time. In 1 it is only added 1 time. At the moment of assignment the variable's value is taken. Whether it changes later doesn't matter.
Note that if you study Javascript a bit longer, you'll notice a different behaviour for Object and other types where assignment doesn't mean later changes to the original are disregarded, but this is a more advanced topic.
There is nothing like partial assignment; either you assign or don't assign.
In the first example, where you write colorNum = "red" + num;, you are not partially assigning num to colorNum. Rather you are using num in creating a new string, and then you are assigning that new string to the colorNum variable. So, as long as you don't update the colorNum with new value, it continues to hold the old value (As long as we are dealing with primitive values like numbers, strings, boolean, etc. This changes when we are dealing with objects which are usually passed around as references).
In example 2 & 3, you are updating the value of colorNum variable every time and hence they are working fine.
In your code examples there is no "magic" behind the variables assignment. The only difference is the order of commands.
Normally, all commands run synchronously, so one-by-one (we are not looking into parallel now). Of course, there are some differences between programming languages, for example in JavaScript all variable and function definitions (var) goes to the start of the code.
Let's return to your code.
Your first example:
num = 0;
colorNum = "red" + num;
function printObject() {
console.log(colorNum);
num++;
}
setInterval(printObject, 2000);
Actually it has var before variable creation. Also I will add line numbers, so it will be easier to understand the order of commands:
/* 1 */ var num = 0;
/* 2 */ var colorNum = "red" + num;
/* 3 */
/* 4 */ function printObject() {
/* 5 */ console.log(colorNum);
/* 6 */ num++;
/* 7 */ }
/* 8 */
/* 9 */ setInterval(printObject, 2000); // 9
First of all, functions and variables created, so first commands will be in line 1, 2, 4 (we create function, but do not run it, just create).
After command in line 1 we will have num equal to 0.
After command in line 2 we will have colorNum equal to "red" + num that is "red" + 0 that is "red0"
Now we come to line 9. Here we calling function printObject every 2 seconds, so...
...when 2 seconds passed we call function printObject, so:
we run command in line 5 and print to console our colorNum that is still equal to "red0"`
line 6 increase num by 1, so now we have num equal to 1
... another 2 seconds passed and we call function again, so:
we run command in line 5 and print to console our colorNum that is still equal to "red0"(because we did not change the value insidecolorNumafter it was set in line2`)
line 6 increase num by 1, so now we have num equal to 2
and so on... We print always the same colorNum as it was created on line 2 and we never change it again, so console.log will use its original value
Ok, now I will be quicker. Your second example has one additional line inside the function: colorNum = "red" + num;. That is very good, because now we change the value of colorNum before we print it to console.
Your third example has different idea of getting the value that we will print to console. You have added another function, that calculates the value. So your code:
num = 0;
fun = function(){
return "red" + num;
}
function printObject() {
console.log(fun());
num++;
}
setInterval(printObject, 2000);
Is equal to:
num = 0;
function printObject() {
console.log("red" + num);
num++;
}
setInterval(printObject, 2000);
This is because your function fun has only one line of code: "red" + num, so I can replace this function call with this line.
Actually, you even do not need to have a separate line for num++, or even the printObject can be "inlined":
var num = 0;
setInterval(() => console.log("red" + num++), 2000);
I'm trying to wrap my head around some Functional Programming basics.
So, by using a higher order function I can create a counter that can increment:
function counter( start ) {
var count = start;
return function() {
return ++count;
}
}
var myCounter = counter( 2 );
myCounter();
myCounter();
However, what would be the correct (in terms of Functional Programming) way of implementing a bi-directional counter? I came up with the following, but it seems too much like a cheap object for me:
function bicounter( start ) {
var count = start;
var mutate = function(amount) {
return function() { count += amount; }
};
return {
increment: mutate(1),
decrement: mutate(-1)
}
}
var myCounter = bicounter( 2 );
myCounter.increment();
myCounter.decrement();
Functional programming quite literally means “programming with functions”. Here, we are talking about a mathematical function and not a subroutine. What's the difference?
This is a function (the Ackermann function):
A mathematical function is pure (i.e. it has no side effects). A mathematical function does only one thing: it maps an input value to an output value. It doesn't change the value of any variable.
This is a subroutine which computes the result of the Ackermann function:
function A(m, n) {
var stack = [], exit;
do {
if (m > 0) {
m = m - 1;
while (n > 0) {
stack.push(m);
n = n - 1;
}
n = 1;
} else {
m = stack.pop();
n = n + 1;
}
} while (m !== exit);
return n;
}
A subroutine may or may not be pure. For example, the above subroutine is impure because it modifies the variables m, n and stack. Thus, although it computes the result of the Ackermann function which is a mathematical function, yet it's not a mathematical function.
Now, consider your counter function:
function counter(count) {
return function () {
return ++count;
};
}
var countup = counter(0);
alert(countup()); // 1
alert(countup()); // 2
alert(countup()); // 3
Is this functional programming? The short answer is, it's debatable because you are indeed using higher-order functions. However, your counter function isn't a mathematical function. Hence, in the strict definition of functional programming (i.e. programming with mathematical functions) your program isn't really functional.
Note: I think most of the confusion arises because in JavaScript first-class subroutines are called functions. Indeed, they can be used as functions. However, they are not mathematical functions.
Actually, your program is object-oriented. Every time you call counter you are creating a new abstract data type representing a counter object. Since this object has only one operation defined over it, you can get away with returning that operation itself from the counter function. Hence, your intuition is absolutely correct. This is not functional programming. It's object-oriented programming.
So how would you implement a counter using functional programming?
In functional programming, everything can be defined as a function. That's strange. What about numbers? Well, numbers can be defined as functions too. Everything can be defined as a function.
However, to make things simpler let's assume that we have some primitive data types like Number and that we can define new data types using structural typing. For example, any object that has the structure { count: Number } (i.e. any object with a single property named count which is of the type Number) is a value of the type Counter. For example, consider:
var counter = { count: 5 }; // counter :: Counter
The typing judgement counter :: Counter reads as “counter is a value of the type Counter”.
However, it's usually better to write a constructor to construct new data structures:
// Counter :: Number -> Counter
function Counter(count) {
return { count: count };
}
var counter = Counter(5); // counter :: Counter
Note that the value Counter (which is a function of the type Number -> Counter, read as “Number to Counter”) is different from the type Counter (which is a data structure of the form { count: Number }). Types and values can have the same name. We know that they're different.
Now, let's write a function that returns the value of a counter:
// count :: Counter -> Number
function count(counter) {
return counter.count;
}
It's not very interesting. However, that's because the Counter data type itself is not very interesting. In fact, the Number data type and the Counter data type are isomorphic (i.e. we can convert any number n into an equivalent counter c using the function Counter and we can convert the counter c back into the number n using the function count, and vice versa).
Hence, we could have avoided defining a Counter data type and used a Number itself as a counter. However, for pedagogical purposes let's use a separate data type for Counter.
So, now we want to update the value of counter using a function named increment. Hold on. Functions can't change the values of variables in functional programming. How do we update the value of counter? Well, we can't update the value of counter. However, we can return a new counter with an updated value. This is exactly what we do in functional programming:
// increment :: Counter -> Counter
function increment(counter) {
return Counter(count(counter) + 1);
}
Similarly, we can define the decrement function:
// decrement :: Counter -> Counter
function decrement(counter) {
return Counter(count(counter) - 1);
}
Notice that if we had used a Number as a Counter then the increment and decrement operations for a counter c would be defined as c + 1 and c - 1 respectively. That further strengthens our understanding that a counter is just a number.
That's all dandy but what's the point of functional programming?
Currently, it seems as though functional programming is more difficult than normal programming. After all, sometimes you really need to mutation to write interesting programs. For example, can you do this easily using functional programming?
function bicounter(count) {
return {
increment: update(+1),
decrement: update(-1)
};
function update(amount) {
return function () {
return count += amount;
};
}
}
var counter = bicounter(0);
alert(counter.increment()); // 1
alert(counter.decrement()); // 0
Actually, yes you can do that using the State monad. I'll switch to Haskell for want of a better functional programming language than JavaScript:
import Control.Monad.State
type Counter = Int
counter :: Counter
counter = 0
increment = modify (+1)
decrement = modify (subtract 1)
alert = get >>= (liftIO . print)
program = do
increment
alert
decrement
alert
main = evalStateT program counter
This is a runnable Haskell program. Quite succinct isn't it? This is the power of functional programming. If you're sold on the idea of functional programming then you should definitely consider learning Haskell.
var avg = function()
{
var sum = 0;
for (var i = 0, j = arguments.length; i < j; i++)
{
sum += arguments[i];
}
return sum / arguments.length;
}
When I try to call this like:
var average = avg(2,3,5);
average; // It works fine;
But how do I call it without assigning to a variable?
If anybody can give any suggestion it will be delightful..Thanks.
You'd simply call it like this:
avg(2, 3, 5);
If you want to see the result, put it in an alert call:
alert( avg(2, 3, 5) );
You don't need to put the result from calling the function in a variable, you can do whatever you like with it.
For example, use it as the value in an alert:
alert(avg(2,3,5));
You can use it in another expression:
var message = "The average is " + avg(2,3,5);
You can use it directly in another call:
someFunction(avg(2,3,5));
You can even throw the result away by not doing anything with it, even if that's not useful in this specific situation:
avg(2,3,5);
If you don't put the result into a variable or in a compatible context, this function cannot output anything, which makes it difficult to use unless you make it output the result. Try this :
var avg = function()
{
var sum = 0;
for (var i = 0, j = arguments.length; i < j; i++)
{
sum += arguments[i];
}
var retvalue = sum / arguments.length;
consoloe.log("avg: "+retvalue);
return retvalue ;
}
Then it may help you to see whenever the function is called or not.
You need to understand the concept of expressions.
Every expression as a whole represents one value. An expression can be made up of multiple subexpressions that are combined in some manner (for example with operators) to yield a new value.
For instance:
3 is an expression (a literal, to be specific) that denotes the numeric value three.
3 + 4 is an expression, made up of two literal expressions, that as a whole yields the value 7
When you assign a value to a variable – as in var average = – the right hand side of the =-operator needs to be an expression, i.e. something that yields a value.
As you have observed, average will have been assigned the value five. It thus follows, that avg(2, 3, 5) must itself be an expression that evaluated to the value 5.
average itself is an expression, denoting the current value of said variable.
The most important thing to take away from this is, that avg() is in no way connected to var average =. avg() stands on its own, you can just think it like an ordinary value such as 5 (there are other differences of course).
If you have understood the concept of expressions and values, it should be clear that if you can do
var average = avg(2,3,5);
average; // It works fine;
You can also do
avg(2,3,5);
I am to write up some code using Javascript. Here is what we are to do:
"Implement a javascript Fibonacci numbers using closures. Specifically, write an function that stores two consecuitive Fibonacci numbers, initially 0 and 1. The function also defines and returns a nested function getNext(). The getNext() function updates the two stored Fibonacci numbers to the next two Fibonacci numbers and returns the current one. E.g. on the first call to getNext() the return value is 0, on the next call it is 1, then 1 again, then 2, etc."
I kind of understand this but not really. Could someone maybe help clarify? Thanks!
The basic idea behind closures is that, since closers bind all local data by value, you can use them to initialize and then modify variables that are only local to that "instance" of the generated function.
Since this seems like homework, I'm going to answer a different question using closures: Use closures to get perfect squares (1, 4, 9, etc.), one at a time.
function makeSquareIteratorFunction() {
var squareRoot = 1;
var getNext = function() {
// Calculate the number you need to return
var square = squareRoot * squareRoot;
// Apply side effects. In this case just incrementing the counter, but with
// Fibonacci you will need to be a little more creative :-)
// You might also prefer to do this first. Depends on your approach.
squareRoot = squareRoot + 1;
// Return the value
return square;
};
// Return the function object, which can then be called later
return getNext;
}
// Usage
var getNextSquare = makeSquareIteratorFunction();
alert(getNextSquare()); // 1
alert(getNextSquare()); // 4
alert(getNextSquare()); // 9
Now, it's worth pointing out that the local variables defined in the outer function (makeSquareIteratorFunction) are localized and bound to the closure. So if you call makeSquareIteratorFunction() multiple times, the later ones will be independent of the first one:
var getNextSquare1 = makeSquareIteratorFunction();
alert(getNextSquare1()); // 1
alert(getNextSquare1()); // 4
var getNextSquare2 = makeSquareIteratorFunction();
alert(getNextSquare2()); // 1 (!) because it's a new closure, initialized the same way
alert(getNextSquare1()); // 9 (!) because it was "on" 4 last time
Hopefully that helps explain it a little? If not, leave a comment. :-)
I just wanted to post a little bit more up to date answer - the fibonacci closure is more readable written using modern JavaScript
function fibonacci() {
let x = 0;
let y = 1;
let z = 0;
return function getNext() {
[z, x, y] = [x, y, x + y];
return z;
};
}
let fun = fibonacci();
for (let i = 0; i < 10; i++) {
console.log(fun());
}
var fibonacci = (function () {
var arr = [0, 1];
return function () {
var num = arr[arr.length - 1],
len = arr.length;
arr.push(arr[len - 1] + arr[len - 2]);
return num;
};
}());
//test
var i;
for (i = 0; i < 10; i++) {
console.log(fibonacci());
}
//1,1,2,3,5,8,13,21,34,55
See the description in http://sarathsaleem.github.com/JavaScriptTasks/
I did this as an answer to this question
Write a function which will return you first two times 1, then 2, then 3, then 5 and so on (Fibonacci numbers). Don’t use any global variables.
fibonacci = ([f0, f1] = [0, 1]) => () => ([f0, f1] = [f1, f0 + f1])[0];
I just wanted to give a more up to date answer written using modern JavaScript.