The for loop bellow works as it was intended, but I just do not understand why.
for (var i = 10;i--;) {
console.log("i: " + i);
}
console: >> 9,8,7,6,5,4,3,2,1,0
I googled for the falsy values: 0 and -0 .. (what does -0 mean ?) But if 0 is considered to be falsy, why the for loop gets evaluated with it ? Actually the original code sample actually look like this:
for (var i = e.length; i--; )
e[i].apply(this, [args || {}]);
It looks cool, but I just do not get why it works.
In the for condition in
for (var i = 10;i--;) {
console.log("i: " + i);
}
the i is evaluated before being decreased (due to the post-decrement operator). Hence it is 1 in the condition and 0 when you actually print it out.
Roberto Reale explained the reason, but I think this problem can also be solved by using the 3 statements in the for loop:
for (var i = 9; i >= 0; i--) {
console.log("i: " + i);
}
It will display integers from 9 to 0.
Related
Please consider this snippet of code:
var i = 1;
i = i-- + ++i;
My understanding of the order in which the operators & operands are processed is as follows:
i is incremented by 1 (pre-fix increment)
i is added to i( addition )
i is decremented by 1(post-fix decrement)
The value of the right hand side is assigned to i (assignment operation)
If my understanding is correct, i should end up having a value of 3. However, I printed out the result using some online javascript interpreter, and the end value of i is 2.
Where did I get wrong?
var i = 1;
i = i-- + ++i;
this is how the compiler will go about working through this code
create a variable called i
set the value of i to 1
(rhs first element) take value of i (1) decrement value (i is now 0)
(rhs second element) increment value of i (i is now 1)
set the value of i to rhs (2)
JavaScript always evaluates subexpressions in a left-to-right order, and then applies the operator:
// parentheses added for clarity
i = (i--) + (++i); // i = 1
i = 1 + (++i); // i = 0 after i--
i = 1 + 1 ; // i = 1 after ++i
i = 2 ;
Understanding the logic with precedence values:
var i = 1;
i = i-- + ++i;
prefix increment(++i) precedence = 17
postfix decrement(i--) precedence = 16
addition(+) precedence = 14
i = 1 + 1
i = 2
More precedence related info can be found in,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
I have an assignment for school that I need to complete, these are the criteria, Count every number 0 - 35
Count every number 0 - 50, start from 30 and stop at 50
Count by 5's 0 - 50
Count down from 10 to 0
Count down from 100 - 0 by 10's
Count every odd number from 1-30
all doing that with for loops
so here is what i have so far, and for some reason it is not working
<html>
<body>
<script>
for (int i = 0; i < 36; i++){
document.write(i);
}
</script>
</body>
</html>
my question is what am I doing wrong? it comes up with an unexpected identifier but thats all it says.
You can't declare a data type (int) in JavaScript. JavaScript is a loosely-typed language. There are only strings, numbers, booleans as primitive data types and the type you get is dependent on how you implicitly (or explicitly) use them.
Here, the variable i is initialized to 0, which is a valid number. When the JavaScript runtime sees you attempting to add to it, it allows that because it has implicitly known that i should be categorized as a number:
for (var i = 0; i < 36; i++){
document.write(i);
}
// And, just for fun...
var a = 5;
var b = "5";
console.log("a's type is: " + typeof a);
console.log("b's type is: " + typeof b);
// But, you can coerce a value into a different type:
console.log("parseInt(b) results in: " + typeof parseInt(b));
console.log('a + "" results in: ' + typeof (a + ""));
Here's some good reading on the subject.
there is no type called 'int' in javascript use 'var'
for (var i = 0; i < 36; i++){
document.write(i);
}
int is no good in Javascript. Everything is defined as var.
Try:
for (var i = 0; i < 36; i++){
document.write(i);
}
I am trying to get the count of the most repeated letter in a word
function GreatestCount(str)
{
var count = {}
for (var i = 0 ; i<str.length;i++)
{
var char = str[i];
count[char] = (count[char] || 0) + 1;
}
//get the largest number for the letter counts
var max = 0;
for (var c in count) {
if (count[c] > max) max = count[c];
}
return max
}
can someone explain to me why
count[char] = (count[char] || 0) + 1;// this works
count[char] += 1 // this does not work
Because
count[char] += 1
is equal to
count[char] = count[char] + 1
and the first time the code is run, count[char] is undefined so it's pretty much the same as
undefined + 1 // which is NaN
The working version circumvents this case by safely adding with 0 using || operator.
Initially, count is an empty object†, so it doesn't have the char property. Therefore, count[char] returns undefined.
And undefined + 1 produces NaN.
Therefore, you must inititialize it to 0 in order to make it work properly.
†: count is not really an empty object because it inherits properties from Object.prototype. It would be problematic if a char property is defined there. I recommend using count = Object.create(null) instead.
You need to initialize your count[char] to zero before incrementing it.
On first occurrence count[char] is undefined and undefined += 1 !== 1
As other said your variable is not initialize in the beginning
so count[char] +=1 is not working, but when you do (count[char] || 0) you actually tell them that you want to set 0 if the variable is "false". False could mean undefined, NaN, 0.
Consider this code:
var i = 0;
>> undefined
i += i + i++;
>> 0
i
>> 0 // why not 1?
I would expect i to be 1 because of the increment (++) operator. What I think should happen is something like:
i = 0 + 0 + (i = i + 1)
i = 0 + 1
i = 1
Why it's returning zero instead? Could someone explain what happens under the scene?
It's important to realize is that i++ increments i, but returns the original value of i.
This postfix version of the operator (also called post-increment) is documented here:
If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing.
So this evaluates to:
i = 0 + (j = i, i += 1, j);
Note the use of the comma operator above.
What you're describing is much more like the prefix version of the operator (also called pre-increment), ++i, which would evaluate to:
i = 0 + (i += 1);
And which does indeed return 1.
It should be
i += i + (++i);
If you use i++ the increment is after the expression, so it will resolve simply as i
This question already has answers here:
Use of commas versus semicolons?
(4 answers)
Closed 9 years ago.
I have question concerning the difference of using in JavaScript code comma OR semicolon.
Do they have differences and influence how the code works?
In the code below I changed the semicolon after definition of var fib that have value 0 by comma an code didn't run.
Can somebody explain this?
The full code of Fibonacci in which it has occurred is here:
<script>
document.write("<h2>Числа Фибоначчи </h2>");
for (i = 0, j = 1, k = 0, fib = 0; i < 50; i++, fib = j + k, j = k, k = fib) {
document.write("Fibonacci (" + i + ") = " + fib);
document.write("<br>");
}
</script>
for encloses 3 expressions :
the initialization (run before the loop),
the end of loop test (run before each iteration),
and the after iteration statement.
Statements in javascript are separated by ;. If you change the ; to a ,, you don't end the init statement.
The previous answers are indeed correct, but I think this is not about the for - it is about the comma, which is in fact an operator:
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.
- MDC
If you want to learn more about it: Angus C. elaborately explains what it does in his blog.
The part that probably confuses you is the fact that a 'normal' for-loop takes three statements like the following:
for (var i=0; i<5; i++)
{
x=x + "The number is " + i + "<br>";
}
but that your example substitutes these expressions with comma seperated arguments.
var i=0 -> i = 0, j = 1, k = 0, fib = 0
i++ -> i++, fib = j + k, j = k, k = fib
BTW, this is terrible code that reads very hard and is even harder to maintain. Don't use it.