JavaScript Loop returns unexpected result - javascript

Can anyone tell me why this logs 11, instead of 9?
function foo() {
function bar(a) {
i =3;
console.log( a + i );
}
for (var i=0; i<10; i++) {
bar( i *2 );
//I know, infinite loop
}
}
foo();
If i is hard-coded in bar(){}, shouldn't the logged result be 9?
This is part of a Scope class and I am lost.
Thanks.

In the first iteration, i is 0 which is smaller than 10. 0 (2 * i) is passed as a to bar. i gets set to 3, then the sum is 3.
In the next iteration, i is incremented to 4 (which is still smaller than 10), then 8 (2 * i) is passed as a to bar. i gets reset to 3, then the sum is 11.
The next iteration is the same, i is incremented from 3 to 4 again and so on.
Your misunderstanding seems to be that the value of a doesn't change because i gets changed, the multiplication is evaluated first. Or you just missed the i++ statement in the loop header.

#Bergi has the right answer, I just want to expand on it a bit. For primitive types like a string or number the parameter is passed by value. Here you are passing i into bar as the value a. Any changes to i or a will not effect the other's value. This also will not give you an infinite loop as the values for i in this case are [0, 4,5,6,7,8,9]
Now if i had been wrapped inside of an object that was passed to foo then you would have the problem you are asking about. Objects passed to javascript functions are passed by reference, so changes to the object in bar also happen in foo.

Related

Updating JavaScript Map value object property with spread and increment operators [duplicate]

My interest is in the difference between for and while loops. I know that the post-increment value is used and then incremented and the operation returns a constant pre-increment.
while (true) {
//...
i++;
int j = i;
}
Here, will j contain the old i or the post-incremented i at the end of the loop?
Since the statement i++ ends at the ; in your example, it makes no difference whether you use pre- or post-increment.
The difference arises when you utilize the result:
int j = i++; // i will contain i_old + 1, j will contain the i_old.
Vs:
int j = ++i; // i and j will both contain i_old + 1.
Depends on how you use them.
i++ makes a copy, increases i, and returns the copy (old value).
++i increases i, and returns i.
In your example it is all about speed. ++i will be the faster than i++ since it doesn't make a copy.
However a compiler will probably optimize it away since you are not storing the returned value from the increment operator in your example, but this is only possible for fundamental types like a int.
Basic answer for understanding.
The incrementation operator works like this:
// ++i
function pre_increment(i) {
i += 1;
return i;
}
// i++
function post_increment(i) {
copy = i;
i += 1;
return copy;
}
A good compiler will automatically replace i++ with ++i when it detect that the returned value will not be used.
In pre-increment the initial value is first incremented and then used inside the expression.
a = ++i;
In this example suppose the value of variable i is 5. Then value of variable a will be 6 because the value of i gets modified before using it in a expression.
In post-increment value is first used in a expression and then incremented.
a = i++;
In this example suppose the value of variable i is 5. Then value of variable a will be 5 because value of i gets incremented only after assigning the value 5 to a .
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argp)
{
int x = 5;
printf("x=%d\n", ++x);
printf("x=%d\n", x++);
printf("x=%d\n", x);
return EXIT_SUCCESS;
}
Program Output:
x=6
x=6
x=7
In the first printf statement x is incremented before being passed to printf so the value 6 is output, in the second x is passed to printf (so 6 is output) and then incremented and the 3rd printf statement just shows that post increment following the previous statement by outputting x again which now has the value 7.
i++ uses i's value then increments it but ++i increments i's value before using it.
The difference between post- and pre-increment is really, in many cases subtle. post incremenet, aka num++, first creates a copy of num, returns it, and after that, increments it. Pre-increment, on the other hand, aka ++num, first evaluates, then returns the value. Most modern compilers, when seeing this in a loop, will generally optimize, mostly when post increment is used, and the returned initial value is not used. The most major difference between the 2 increments, where it is really common to make subtle bugs, is when declaring variables, with incremented values: Example below:
int num = 5;
int num2 = ++num; //Here, first num is incremented,
//then made 6, and that value is stored in num2;
Another example:
int num = 5;
int num2 = num++; //Here, num is first returned, (unfortunately?), and then
//incremented. This is useful for some cases.
The last thing here I want to say is BE CAREFUL WITH INCREMENTS. When declaring variables, make sure you use the right increment, or just write the whole thing out (num2 = num + 1, which doesn't always work, and is the equivalent of pre-increment). A lot of trouble will be saved, if you use the right increment.
it does not matter if you use pre or post increment in an independent statement, except for the pre-increment the effect is immediate
//an example will make it more clear:
int n=1;
printf("%d",n);
printf("%d",++n);// try changing it to n++(you'll get to know what's going on)
n++;
printf("%d",n);
output:
123

Ternary operator doesn't handle post-increments as expected

So this may be a silly question, but I've been running into this syntax mistake every now and again and can't seem to learn my lesson - because I simply don't understand why this doesn't work.
For some reason the ternary operator won't handle increments or decrements.
In the console, I found these results:
// Firstly
var iteration = undefined;
// Expected increment, unexpected result
iteration = iteration == undefined ? 0 : iteration++; //returns 0 every time
// Then I thought maybe ternary doesn't return assignments
iteration = iteration == undefined ? 0 : iteration+=1; //increments iteration
// Works as expected
iteration = iteration == undefined ? 0 : iteration+1; //increments iteration
While searching for answers I found another user had the same experience with the unexpected behavior.
After more searching I found that the pre-increment works fine:
iteration = iteration == undefined ? 0 : ++iteration; //increments iteration
And came across this answer when trying to determine why the pre-increment works.
It does make sense to me why it works and post-increment doesn't - kinda. I suppose at some point the incremented value could be overwritten by the initial value if the ternary order of operations works that way, but that's all I can think of.
But really the expected behavior that I would have from the post-increment would be for iteration to be returned, and then for it to be iterated...after.
For example, this bit of code:
var bar = undefined;
//foo is set immediately and bar is incremented after it is returned
foo = bar == undefined ? bar=0 : bar++; //sets foo to be what bar was before the increment
Hopefully you have been able to bear with me here. I do understand that at this point after finding many reliable and straight forward ways to get the job done that I don't need an answer, but I'm just stumped why it works this way.
Question:
Why does the ternary operator not update the post-increment (or postfix) value returned - after it has been returned?
A comment on this answer states that
counter++ evaluates to the current value of counter, then increments it. You would be assigning the old value of counter back to counter after you've incremented.
but I still don't why the order of operations behaves this way.
Another helpful Pre-increment vs Post-increment for C++ (ironically hilarious answer)
Whether the interpreter runs across an expression invoking pre- or post-increment, the variable is reassigned immediately, before the expression is resolved. For example:
iteration = iteration == undefined ? 0 : iteration++;
is like
function doPostIncrement() {
const preIncrementValue = increment;
increment = increment + 1;
return preIncrementValue;
}
iteration = iteration == undefined ? 0 : doPostIncrement();
Also, assignments resolve to values, so
iteration = iteration == undefined ? 0 : iteration+=1; //increments iteration
is like
function addOneToIncrementAndReturnIncrement() {
increment = increment + 1;
return increment;
}
iteration = iteration == undefined ? 0 : addOneToIncrementAndReturnIncrement();
It's not actually a function call, but it's not that dissimilar, in that the reassignment is done before the function resolves, or before the pre / post-increment expression resolves.
In an assignment expression, the entire right hand side gets evaluated first, and its resulting value is assigned to the left hand side. That means the post increment expression needs to be evaluated and turned into a value first, which will be assigned to the left hand side afterwards. The post increment operator doesn't know what larger expression it's a part of. It will be evaluated atomically. I.e., it won't first return its value, then complete the assignment operation, and then complete the post increment operation. When evaluating the expression iteration++, the value of iteration will be incremented and the expression results in the original value of iteration, all at once.

How does the Javascript closure with function works?

Hi i have been exploring closures and javascript core concepts i couldn't understand why does the console.log(factory[i]) outputs undefined i have pushed my function inside there right? And if i call temp outside the loop it says undefined whereas if i call inside the loop it returns am bit confused can anyone explain me?Here is my code
var fruits=["apple","orange"];
var factory=[];
for(var i=0;i<fruits.length;i++)
{
var temp=function()
{
console.log(fruits[i]);
}
factory.push(temp());
}
temp();
console.log(factory);
for(var i=0;i<factory.length;i++)
{
temp(i);
console.log(factory[i]);
}
https://jsfiddle.net/kh3okLca/
You are not passing function but the result of the executed function temp() as it don't return anything its undefined. change factory.push(temp()); to factory.push(temp);
The temp() outside return undefined because by that time loop has executed and the value of i is 2 check this following piece of code which logs value of i.
var fruits=["apple","orange"];
var factory=[];
for(var i=0;i<fruits.length;i++)
{
var temp=function()
{
console.log(fruits[i],"console",i);
}
factory.push(temp);
}
temp();
console.log(factory,"factory");
for(var i=0;i<factory.length;i++)
{
temp(i); //i resets to 0 here in same scope
console.log(factory[i](i),"factoryi"); //this doesnt return anything so its undefined but statements are executed
}
Here is the output you have.
//next two executed due to factory.push(temp()) in first if loop
& there is a console.log there inside the function
apple
orange
//here i++ in first loop will be 3, but array have only two element, so it is undefined
undefined
// due to console.log(factory)
// temp function is actually returning undefined,
[undefined, undefined]
// due to temp(i) in second if block
apple
// but factory array is stil empty so factory[i] will be undefined
undefined
from temp orange
undefined
Closure are nothing but function with preserve data. Till now a function is treated as peace of code which takes input and produces some output ,for every function call this code remain same, but closure gives you opportunity to save some data with the function which can be changed so that for each function call it will react differently, keep that in mind everything will be easy .
Suppose you have a function that finds rate of interest , but this functions is used by three teams whose interest rates are different, So in general what we do we pass the team name with the principle amount , each and everytime we have to pass the team name , So by using closure we can three instance of a function for each team (team name as a preserve data ) and now only send the principle amount and get the interest calculated according to the team, I a moment i will add example also,

Can someone explain me the flow of this JavaScript function? (Closure concept)

I'm reading "Eloquent JavaScript". Chapter 3 introduces "Closure" concept and gives you a couple of examples. One of these is next one:
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
var twice = multiplier(2);
console.log(twice(5));
// → 10
I think I understood the concept. If first I execute console.log(twice), since variable number is undefined, what I get is [Function]. What I don't understand is how twice(5) works. Why local variable number is initialized with value 5?
Also, why if I execute console.log(multiplier(2,5)) I don't get 10 as a result?
Thanks.
Because multiplier returns a function, so twice is equal to the returned function, NOT the multiplier function.
However, when multiplier is called the factor variable is passed and used within the returned function.
So to make it easier to understand, consider that twice is basically:
var twice = function(number) {
return number * 2;
};
Where factor has been replaced by the value you passed in when calling multiplier(2).
I think I understood the concept. If first I execute console.log(twice), since variable number is undefined, what I get is [Function].
When you use console.log(twice) you are not actually calling the function twice, you are simply logging the value of it. So the output of [Function] is not because number is undefined, it is because you are outputting the actual function rather than the result of it.
Also, why if I execute console.log(multiplier(2,5)) I don't get 10 as a result?
Here you are calling the multiplier by providing 2 arguments, though you have only defined the function to accept one parameter (factor). In javascript, this won't cause an error, but you will just get the first value mapped in factor (factor = 2).
Note: There are ways to still access all the supplied arguments even if you don't have parameters defined for them (here's an example)
Something that would be possible to get a result of 10 which might be of interest is to use the following code:
var result = multiplier(2)(5); // result = 10
multiplier is a function which returns anonymous function which accepts an argument(number)
var twice = multiplier(2);
Basically is :-
var twice = function(number) {
return number * 2;
};
If you execute
console.log(multiplier(2,5))
you call the function giving two parameters, whereas
function multiplier(factor) {}
only takes one parameter.

Need Help Understanding Javascript Closure

I am learning about javascript closures and am having difficulty understanding the concept. If someone would be kind enough to guide me through this example, i.e., where inputs and outputs are going, I'd appreciate it.
var hidden = mystery(3);
var jumble = mystery3(hidden);
var result = jumble(2);
function mystery ( input ){
var secret = 4;
input+=2;
function mystery2 ( multiplier ) {
multiplier *= input;
return secret * multiplier;
}
return mystery2;
}
function mystery3 ( param ){
function mystery4 ( bonus ){
return param(6) + bonus;
}
return mystery4;
}
results;
Thank you.
Let's analyze this step by step.
The first call is to mystery with an argument of 3.
What does mystery do? It defines a variable secret with the value 4 and then it adds 2 to input.
So after the first two lines of mystery, you have:
secret = 4;
input = 5;
Then you have a nested function called mystery2 which takes in an argument called multiplier. In the first line it multiplies input to multiplier, and then returns secret * multiplier. We don't know the values of multiplier, but we do know the values secret and input. You might be wondering how that is. Well, in JavaScript when you create a closure, it is lexically bound to the current scope. This is just a fancy way of saying that the closure "knows" about all local variables that were created in the same scope that the closure itself was created. This behavior applies to nested functions as well which is why they can behave as closures in JavaScript. So what this means is that mystery2, when it is eventually called, will have secret set to 4 and input set to 5. So this mystery2, which knows about these two values, is returned from mystery. So after execution, the variable hidden doesn't contain a value, instead it contains a reference to an instance of mystery2 where the values of secret and input are the ones I mentioned earlier.
What is the advantage of this? The advantage is that you can have multiple copies of mystery2, which "know" different values of input based on what was passed into mystery. So here, mystery is sort of behaving like a constructor for mystery2.
Now we have hidden pointing to an instance of mystery2. So in this case hidden is sort of an alias for our own special copy of mystery2.
In the next line, you call mystery3 and pass in hidden as an argument. What happens inside mystery3? Well mystery3 accepts a parameter called param, then it does something similar to mystery; it returns a function. What does this function do? It accepts a parameter called bonus. Then it does param(6) + bonus.
What does that mean?
What is param? It is the argument that was passed into mystery3. Since mystery4 behaves like a closure, it "knows" about param. But actually, what is param? Well, param is hidden, which points to our special instance of mystery2! Now here is where we actually evaluate mystery2: we call it with an argument of 6, which will be the value of multiplier. So now you have multiplier *= input. The value of input that mystery2 "knows" is 5. So we basically have 6 * 5, which means that multiplier is now set to 30. Then we return secret * multiplier, which is 4 * 30, which is 120. So what this means is that param(6) returns 120, which we then add to bonus. Keep in mind that this will happen only when we actually execute mystery4.
When do we execute mystery4? Well after we call mystery3, we return a copy of mystery4, which is then assigned to jumble. After that we call jumble(2). So what is jumble? It is essentially this:
function mystery4(bonus) {
return param(6) + bonus
}
What is param? Well, that is basically mystery2:
function mystery2 ( multiplier ) {
multiplier *= input;
return secret * multiplier;
}
Let's go over the calculations again. When we call param(6), we basically have multiplier set to 6 inside mystery2. mystery2 "knows" that input is 5 (it is what we calculated inside mystery). So multiplier *= input, means that multiplier is now 30. Then we do secret * multiplier, which is 4 * 30, which is 120. So the return value of param(6) is 120. To this value we add bonus inside mystery4. We called mystery4 with an argument of 2, so we have 120 + 2, which means that the final result is 122.
Hope this helps you out!

Categories

Resources