on my quest to learn and improve my JavaScript I came across a script that has a switch / case statement and I noticed some variables are incremented using ++ with the variable before the ++ and then some variables have the ++ after the variable. What's the difference between these? Here's an example of what I'm trying to explain notice the m and y variables.
switch(f){
case 0:{
++m;
if(m==12){
m=0;
y++;
}
break;
}
case 1:{
--m;
if(m==-1){
m=11;
y--;
}
break;
}
case 2:{
++y;
break;
}
case 3:{
--y;
break;
}
case 4:{
break;
}
}
!= will only check value regardless of operands type. but !== is used to compare both value & type of 2 operands that are being compared to each other.
= is used for assigning values to a variable in JavaScript. == is used for comparison between two variables irrespective of the datatype of variable. === is used for comparision between two variables but this will check strict type, which means it will check datatype and compare two values.
The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.
The value i++ is the value of i before the increment. The value of ++i is the value of i after the increment. Example: var i = 42; alert(i++); // shows 42 alert(i); // shows 43 i = 42; alert(++i); // shows 43 alert(i); // shows 43. The i-- and --i operators works the same way.
++i
returns the value of i
after it has been incremented. i++
returns the value of i
before incrementing.
When the ++
comes before its operand it is called the "pre-increment" operator, and when it comes after it is called the "post-increment" operator.
This distinction is only important if you do something with the result.
var i = 0, j = 0;
alert(++i); // alerts 1
alert(j++); // alerts 0
One thing to note though is that even though i++
returns the value before incrementing, it still returns the value after it has been converted to a number.
So
var s = "1";
alert(typeof s++); // alerts "number"
alert(s); // alerts 2, not "11" as if by ("1" + 1)
The same difference as any other c-style ++
incrementor.
foo = ++i
is the same as:
i = i + 1;
foo = i;
foo = i++
is the same as;
foo = i;
i = i + 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With