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.
Related
In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences between these ways of incrementing a variable?
Same as in other languages:
++x (pre-increment) means "increment the variable; the value of the expression is the final value"
x++ (post-increment) means "remember the original value, then increment the variable; the value of the expression is the original value"
Now when used as a standalone statement, they mean the same thing:
x++;
++x;
The difference comes when you use the value of the expression elsewhere. For example:
x = 0;
y = array[x++]; // This will get array[0]
x = 0;
y = array[++x]; // This will get array[1]
++x increments the value, then evaluates and stores it.
x++ evaluates the value, then increments and stores it.
var n = 0, m = 0;
alert(n++); /* Shows 0, then stores n = 1 */
alert(++m); /* Shows 1, then stores m = 1 */
Note that there are slight performance benefits to using ++x where possible, because you read the variable, modify it, then evaluate and store it. Versus the x++ operator where you read the value, evaluate it, modify it, then store it.
As I understand them if you use them standalone they do the same thing. If you try to output the result of them as an expression then they may differ. Try alert(i++) as compared to alert(++i) to see the difference. i++ evaluates to i before the addition and ++i does the addition before evaluating.
See http://jsfiddle.net/xaDC4/ for an example.
I've an explanation of understanding post-increment and pre-increment. So I'm putting it here.
Lets assign 0 to x
let x = 0;
Lets start with post-increment
console.log(x++); // Outputs 0
Why?
Lets break the x++ expression down
x = x;
x = x + 1;
First statement returns the value of x which is 0
And later when you use x variable anywhere, then the second statement is executed
Second statement returns the value of this x + 1 expression which is (0 + 1) = 1
Keep in mind the value of x at this state which is 1
Now lets start with pre-increment
console.log(++x); // Outputs 2
Why?
Lets break the ++x expression down
x = x + 1;
x = x;
First statement returns the value of this x + 1 expression which is (1 + 1) = 2
Second statement returns the value of x which is 2 so x = 2 thus it returns 2
Hope this would help you understand what post-increment and pre-increment are!
var a = 1;
var b = ++a;
alert('a:' + a + ';b:' + b); //a:2;b:2
var c = 1;
var d = c++;
alert('c:' + c + ';d:' + d); //c:2;d:1
jsfiddle
var x = 0, y = 0;
//post-increment: i++ returns value then adds one to it
console.log('x++ will log: ', x++); //0
console.log('x after x++ : ', x); //1
//pre-increment: adds one to the value, then returns it
console.log('++y will log: ', ++y); //1
console.log('y after ++y : ', y); //1
It is clearer and faster to use ++i if possible :
++i guarantees that you are using a value of i that will remains the same unless you change i
i++ allows to use a value of i which will change in the "near future", it is not desirable if possible
Of course, it's not really much faster, only a little.
In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences between these ways of incrementing a variable?
Same as in other languages:
++x (pre-increment) means "increment the variable; the value of the expression is the final value"
x++ (post-increment) means "remember the original value, then increment the variable; the value of the expression is the original value"
Now when used as a standalone statement, they mean the same thing:
x++;
++x;
The difference comes when you use the value of the expression elsewhere. For example:
x = 0;
y = array[x++]; // This will get array[0]
x = 0;
y = array[++x]; // This will get array[1]
++x increments the value, then evaluates and stores it.
x++ evaluates the value, then increments and stores it.
var n = 0, m = 0;
alert(n++); /* Shows 0, then stores n = 1 */
alert(++m); /* Shows 1, then stores m = 1 */
Note that there are slight performance benefits to using ++x where possible, because you read the variable, modify it, then evaluate and store it. Versus the x++ operator where you read the value, evaluate it, modify it, then store it.
As I understand them if you use them standalone they do the same thing. If you try to output the result of them as an expression then they may differ. Try alert(i++) as compared to alert(++i) to see the difference. i++ evaluates to i before the addition and ++i does the addition before evaluating.
See http://jsfiddle.net/xaDC4/ for an example.
I've an explanation of understanding post-increment and pre-increment. So I'm putting it here.
Lets assign 0 to x
let x = 0;
Lets start with post-increment
console.log(x++); // Outputs 0
Why?
Lets break the x++ expression down
x = x;
x = x + 1;
First statement returns the value of x which is 0
And later when you use x variable anywhere, then the second statement is executed
Second statement returns the value of this x + 1 expression which is (0 + 1) = 1
Keep in mind the value of x at this state which is 1
Now lets start with pre-increment
console.log(++x); // Outputs 2
Why?
Lets break the ++x expression down
x = x + 1;
x = x;
First statement returns the value of this x + 1 expression which is (1 + 1) = 2
Second statement returns the value of x which is 2 so x = 2 thus it returns 2
Hope this would help you understand what post-increment and pre-increment are!
var a = 1;
var b = ++a;
alert('a:' + a + ';b:' + b); //a:2;b:2
var c = 1;
var d = c++;
alert('c:' + c + ';d:' + d); //c:2;d:1
jsfiddle
var x = 0, y = 0;
//post-increment: i++ returns value then adds one to it
console.log('x++ will log: ', x++); //0
console.log('x after x++ : ', x); //1
//pre-increment: adds one to the value, then returns it
console.log('++y will log: ', ++y); //1
console.log('y after ++y : ', y); //1
It is clearer and faster to use ++i if possible :
++i guarantees that you are using a value of i that will remains the same unless you change i
i++ allows to use a value of i which will change in the "near future", it is not desirable if possible
Of course, it's not really much faster, only a little.
In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences between these ways of incrementing a variable?
Same as in other languages:
++x (pre-increment) means "increment the variable; the value of the expression is the final value"
x++ (post-increment) means "remember the original value, then increment the variable; the value of the expression is the original value"
Now when used as a standalone statement, they mean the same thing:
x++;
++x;
The difference comes when you use the value of the expression elsewhere. For example:
x = 0;
y = array[x++]; // This will get array[0]
x = 0;
y = array[++x]; // This will get array[1]
++x increments the value, then evaluates and stores it.
x++ evaluates the value, then increments and stores it.
var n = 0, m = 0;
alert(n++); /* Shows 0, then stores n = 1 */
alert(++m); /* Shows 1, then stores m = 1 */
Note that there are slight performance benefits to using ++x where possible, because you read the variable, modify it, then evaluate and store it. Versus the x++ operator where you read the value, evaluate it, modify it, then store it.
As I understand them if you use them standalone they do the same thing. If you try to output the result of them as an expression then they may differ. Try alert(i++) as compared to alert(++i) to see the difference. i++ evaluates to i before the addition and ++i does the addition before evaluating.
See http://jsfiddle.net/xaDC4/ for an example.
I've an explanation of understanding post-increment and pre-increment. So I'm putting it here.
Lets assign 0 to x
let x = 0;
Lets start with post-increment
console.log(x++); // Outputs 0
Why?
Lets break the x++ expression down
x = x;
x = x + 1;
First statement returns the value of x which is 0
And later when you use x variable anywhere, then the second statement is executed
Second statement returns the value of this x + 1 expression which is (0 + 1) = 1
Keep in mind the value of x at this state which is 1
Now lets start with pre-increment
console.log(++x); // Outputs 2
Why?
Lets break the ++x expression down
x = x + 1;
x = x;
First statement returns the value of this x + 1 expression which is (1 + 1) = 2
Second statement returns the value of x which is 2 so x = 2 thus it returns 2
Hope this would help you understand what post-increment and pre-increment are!
var a = 1;
var b = ++a;
alert('a:' + a + ';b:' + b); //a:2;b:2
var c = 1;
var d = c++;
alert('c:' + c + ';d:' + d); //c:2;d:1
jsfiddle
var x = 0, y = 0;
//post-increment: i++ returns value then adds one to it
console.log('x++ will log: ', x++); //0
console.log('x after x++ : ', x); //1
//pre-increment: adds one to the value, then returns it
console.log('++y will log: ', ++y); //1
console.log('y after ++y : ', y); //1
It is clearer and faster to use ++i if possible :
++i guarantees that you are using a value of i that will remains the same unless you change i
i++ allows to use a value of i which will change in the "near future", it is not desirable if possible
Of course, it's not really much faster, only a little.
I'm trying to understand how to find all the combinations of a string using a double loop but the solution I've come across is too complicated for my understanding. The function does what I need but I have beginner understanding of setting up a single or double for loop.
I'm hoping for a general step by step explanation of what is going on but for specific questions: what functions are "i < Math.pow(2,n)-1", "((i & (1 << j)) == 1 << j)", and "var comb = ''; (temporary storage?)" serving?
subsets = function(str) {
var n = str.length;
for (var i=1; i< Math.pow(2,n)-1; i++) {
var comb = '';
for (var j=0; j<n; j++) {
var use = ((i & (1 << j)) == 1 << j);
if(use)comb+=str.charAt(j);
}
console.log(comb);
}
}
subsets("age");
Output: a ag ae g ge e
To get a random combination of the string, we could set up a boolean array, storing if one of the characters should be displayed or not, e.g:
"a","g","e"
[true,false,true]
=>"ae"
So the number of possible variations is
2 /*true/false*/ ** str.length
written in old style:
Math.pow(2,str.length)
So the main for loop iterates over all possible combinatons except the first one (as i starts with 1),as that would be an empty string and the last one (-1) that would be "age". While i is an integer which simply counts up, we could also imagine that its a boolean array (in a bitwise view):
integer
bits
boolean array
1
001
[false,false,true]
2
010
[false,true,false]
3
011
[false,true,true]
4
100
[true,false,false]
...
6 < 2 ** 3 -1
110
[true,true,false]
Now the inner loop:
for (var j=0; j<n; j++) {
var use = ((i & (1 << j)) == 1 << j);
if(use)comb+=str.charAt(j);
}
Just goes over our letters and checks if the boolean flag is true, so at i = 5 the boolean array would be:
[true,false,true]//101
and that is converted to
"ae"
How it looks bitwise:
A true one ("a"):
101 // i
&001 //1<<j where j is 0
=001
===
001 //1<<j
A false one ("g"):
101
&010 //1<<j where j is 1
=000
!==
010 //1<<j
A true one ("e"):
101 // i
&100 //1<<j where j is 2
=100
===
100 //1<<j
So it checks if the boolean array (i) is true at js index, if so it adds that letter. BTW shorter:
if(i & (1<<j))
var i=1; i< Math.pow(2,n)-1; i++
What the Math.pow(2, n) - 1 is saying is run this loop until (2^n)-1, where 'n' is the length of the string. So with the input 'age', the first for loop will run while i, starting at 1 and incrementing by 1 each loop, is less than (2^3)-1. Therefore, this first loop will run 6 times.
var comb = ''
Is exactly what you think it is - storage for what to log that populates as the for loops do their thing!
As for (i & (1 << j)) == 1 << j), that's where we get into Bitwise operators! Unfortunately, I don't understand these nearly well enough to explain them :(
Math.pow is a power function. The first argument is the base, and the second argument is the exponent, so Math.pow(2, n) is equivalent to 2^n. In the loop, i< Math.pow(2,n) means the boundary of the for loop is while i is less than 2^n, where n is the string length.
var comb = ''; is initializing an empty string. This string is concatenated later in the loop so this declaration serves to establish that variable for concatenation.
It's a code based on binary (0/1)
operators in javascript explain << it's a "Shift a into binary representation of b bits to the left, by inserting zeros by the right"
and & : Returns a 1 for each bit position for which the corresponding bits of the two operands are 1.
If u had some problem to undestand a code, Try it on paper step by step with simple example.
Try example str = "a", after try "on" ...
For "a" the beginning is
var n = str.length; // 1
for (var i=1; i< Math.pow(2,n)-1; i++) { // for i=1;i<2^1-1 =2-1=1;i++
var comb = '';
for (var j=0; j<n; j++) {//for j=0;j<1;j++
var use = ((i & (1 << j)) == 1 << j);// use = 1 & (1 << 0 insert 0 times 0)) == 1 << 0= (1 & 1)== 1=true (1==1)
if(use)comb+=str.charAt(j);//comb='' + a.charAt(0)= comb= '' + "a"='a'
... You continue the loops.
binary is a method to write number with 0/1 :
Example 00101(binary)
U have 5 digits then the 1rst 0 = 0*2^(number of place of digit from right-1) = 0*2^4=0
Then 00101(binary) = 0*2^4 + 0*2^3 + 1*2^2 + 0*2^1 + 1*2^0
= 0 + 0 + 1*4 + 0 + 1*1
= 5 in current using (decimal)
U find lot of explanation on binary with Google
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);
}