I'm curious how a variable can be an integer inside a for loop but become NaN immediately outside the loop.
var sumNum = 0;
for (var i = data.length - 1; i >=0; i--) {
sumNum += data[i].stored_value;
// check value inside loop
console.log(sumNum);
}
// check value outside loop
console.log(sumNum);
Result:
The first console.log(sumNum) prints increasing integers as we iterate and add up stored_value's in array. But the second console.log(sumNum) prints NaN.
I read a related thread (Variable becomes Nan when i try to use it outside of the .each function) explaining how this could happen if variable is instantiated inside the loop, but in my case the variable is created globally first.
Could anyone share some insight on how this can happen?
add a check of number in following code
if(isNaN(data[i].stored_value) == false) {
sumNum += data[i].stored_value;
}
Because if you add a non numeric value (may be some blank value) in some variable it becomes NaN
Related
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
In case I run the following loop and (intentionally) use var in my assignment of i, why is i equal to 4 and not 3 in the outer scope of the for-loop? Why and when does the final increment happen?
for (var i = 0; i <= 3 ; i++) console.log(i);
console.log(i)
Result:
0
1
2
3
4 //<- outer console.log
i is 4 when the condition i <= 3 fails (hence the for loop stops) and you console.log 4.
take a look at the flow chart:
Let's start a verbose description of the loop from the last iteration (when i is 3):
block is going to execute the console.log(3)
i is incremented by 1 so now i is 4
Check is i (aka 4) smaller or equal than 3?
No, it's not. The loop stops.
Next line simply console.log(4);
Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in.
Total number of iterations that happen in your loop are 4. Starting from 0.
As soon as i becomes 4 in the 4th iteration because of i++ and this condition fails:
i<=3;
That's why you get 4 outside the loop.
Your loop consists of three things
for (var i = 0; i <= 3 ; i++)
In the first part (before the semi-colon), you're creating a new variable.
In the second part, you declare a condition against which the for-loop is checked.
In the third part, you increment the variable by 1.
The way a for-loop works, is that it reads the variable (first check i = 0). Then it checks if i <= 3 (which in the first run is true).
Then it executes the code between the brackets {} of the for-loop.
Rinse and repeat. The for-loop keeps running for as long as your condition holds true.
As to the ++ operator, it will first read your variable 'as-is' and then increment that same variable. In doubt, go through the basics
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.
This function counts number of all characters of a string into a string. I am not fully understanding the if statement here and how it works.
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string[i];
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
I thought freq[character] is the property of the object such as A B how does it work with if(freq[character]) also how does the increment of freq[character]++ works?
I have made test like this to try and understand it.
var v = {};
v.h = 3;
v["h"]++;
v["h"] = v["h"] + 1;
v.h++;
v.h = v.h + 2;
console.log(v);
console.log(v["h"]);
I think I can guess the if statement works that if the property exists but I thought JS has an object property calls .hasOwnProperty shouldn't this be used instead?
As for the increments, to my test, it works but I just don't get the reason.
Can someone give me a hand to elaborate this?
Thanks in advance
In javascript, objects are associative arrays. And vice versa. There is no difference between the two concepts.
So defining this variable as an empty object:
var freq = {};
... is actually creating an associative array (like a dictionary or map) with no keys added yet.
Moving on, let's take an input string like eek. The code here will look at the first letter and treat freq[character] the same as freq['e'], which is the same as freq.e.
In this code, the initial value of any letter in the freq object is undefined. So that initial if() check for the first "e" in our string actually looks like this:
if(undefined)
Javascript has the concept of "truthy" and "falsy" values; anything in javascript can be evaluated as a boolean, and (in most cases) a sensible result is achieved. Looking at undefined, Javascript will simply treat this a falsy value, fall to the else block, and therefore execute this code:
freq[character] = 1;
As already established, this is the same thing as freq.e = 1;
Now when the loop continues to the next letter (also an "e"), javascript will end up evaluating the expression if (1). Javascript treats this and all other non-zero numbers as "truthy", so this time will execute the following line:
freq[character]++;
Again, that's the same as freq.e++, where freq.e had a value of "1" that can now be incremented to "2".
One more time through the loop for the final letter "k". This time we get freq.k, which is still undefined. Undefined is falsy, so control falls to the else block, and freq.k is set to "1".
Now you can see how we can start to increment letters in the array as you find them in the string, even though it appears that you never defined an array in the first place, never set any values to anything other than "undefined", and never had a real boolean value to check against.
if (freq[character]) checks if the value is "truthy". That is, it's not false, null, undefined or 0. The first time we encounter any character the value will be undefined, since the object literal is created empty, so the "truthy" check will fail and control will fall to the else block.
So when we first see a specific letter set the value to 1 (which is now "truthy").
Any subsequent encounters of that letter just increment the value, which would be equivalent to say freq[character] = freq[character] + 1;. The increment syntax is just a shorthand.
if (freq[character]) checks if the object freq has a property on it with the value of character as the name. The result of this expression evaluates to true or false.
It can be more explicitly stated, as the following non-exhaustively illustrates:
if (freq[character] == null)
or
if (typeof freq[character] === 'undefined')
The danger in not being explicit when evaluating if an object is undefined or null, is if it is actually set to a different type that evaluates to true or false (0, 1, '0', true, false).
the difference (speed, performace, side effects, ...) between implementations of the for loop:
between
var i;
for(i = 0; i < length; i++){ //Do something}
// more code
and
for(var i = 0; i < length; i++){ //Do something}
// more code
and
for(i = 0; i < length; i++){ //Do something}
// more code
and between
var e;
for( e in array){ //Do something}
// more code
and
for(var e in array){ //Do something}
// more code
and
for(e in array){ //Do something}
// more code
There is no difference.
JavaScript variables have only function scope, and although you can place a var statement in the initialisation part of a for loop in reality the declaration is "hoisted" to the top of the scope such that when your second case examples run they're treated exactly like the first cases.
EDIT: Since you updated the question after I answered, the third syntax that you added where you don't use the var keyword means the variable i (or e) will be created as a global - unless it already exists as a global in which case the existing variable will be overwritten. Global variable access is slower than local variable access.
NOTE: my interpretation of the question is that it is not comparing a standard for loop with the for..in variant, it is just compared the different variable declaration methods with each other for a standard for loop, then doing the same again for a for..in loop.
There is no difference in relation to the declariation of your counter variable..
BUT ALWAYS DECLARE YOUR VARIABLES WITH var
Otherwise they pollute javascript's already dirty global scope...
As far as for...in vs traditional for look here...
(Which is my answer to the duplicate question...)
Yes, there is a difference between for loop and for/in loop in javascript. Here is what is different
consider this array
var myArr = ["a", "b", "c"];
Later, I add an element to this array, but in a different way, like so:
myArr[myArr.length + 1] = "d";
At this point of time, this is what the array looks like, if you console.log it
["c", "b", "a", undefined × 1, "d"]
Now, let us loop through the array using for and for/in loop and see what the difference is:
first, lets try the for loop
for(var i = 0; i != myArr.length; i++) { // note, i used " != " instead of " < ". Yes this is faster.
console.log(myArr[i]);
}
// output will look like this:
// "a"
// "b"
// "c"
// undefined × 1
// "d"
// - This still shows the undefined value in the array.
Now, lets look at the for/in loop
for(key in myArr) {
console.log(myArr[key]);
}
// array will look like:
// "a"
// "b"
// "c"
// "d"
// This will skip the undefined value.
Difference 1: The javascript interpreter will skip all values that are null or undefined when using the for/in loop. Also, the for/in loop will convert all values if it encounters a primitive value, to its equivalent wrapper object. Where as the for loop doesn't do this.
Difference 2: When using the for loop, we declared the variable i within the loop, this variable will be scoped within a function, if the for loop is written within that function. Which means, until the function ends, the variable i is still available, even outside of the for loop, but within that function. Where as, in case of the for/in loop, the scope of the "key" variable dies immediately after the for/in loop stops executing, which means, there is less memory utilization.