Postfix operator in JavaScript [duplicate] - javascript

This question already has answers here:
++someVariable vs. someVariable++ in JavaScript
(7 answers)
Closed 4 years ago.
This is a basic JS question I think, but I just couldn't find an answer that I was satisfied with. I'm learning operators in JavaScript and I can't understand this following postfix example and how it works:
var x = 4;
var y = x++;
For example, when I alert x, it gives me 5. But when I alert y, it gives me 4. And I can't understand the logic behind it.
I understand that, because it's a postfix, x is assigned to y. And y reads just x, without the postfix. But why does then the original x read the postfix instead if I'm applying it to a different var?
If I just did var y = x + 1, the original x would stay unchanged. But that's not the case when I use postfix. Why would I even change the x with this method? Couldn't I just go then var x = 4; x++; ? And not bother changing it via another var?
I apologize if this is too basic and thanks in advance!

It's easier to think of the increment operators as little functions that return something. So x++ is a functions that increments x and returns the original value of x, whereas ++x does the same thing but returns the new value.
This comes in handy from time to time especially in loops where you want precise control of the stopping point. For example, compare:
let i = 0, j = 0;
while (++i < 5) {
console.log(i) // stops at 4
}
while (j++ < 5) {
console.log(j) // stops at 5
}
The difference is because the while loop evaluates one before the increment and the other after.
Similarly in recursive functions you'll often see things like:
function recurse(i) {
if (i == 5) return i
console.log(i)
return recurse(++i)
}
console.log("final: ", recurse(0))
But if you use the postfix return recurse(i++) you get infinite recursion.

Why would I even change the x with this method?
For some funny shortforms like:
const array = [1, 2, 3];
let i = 0;
while(i < array.length) console.log(array[ i++ ]);
Couldn't I just go then var x = 4; x++; ?
Yeah or just prefix, like ++x or just x += 1 which is more appropriate in most cases.

Related

Prefix and postfix operators [duplicate]

This question already has answers here:
javascript i++ vs ++i [duplicate]
(8 answers)
Closed 10 months ago.
let a = 70;
a++; // This returns the value before incrementing.
console.log(a) // returns 71
Can someone explain to me why this doesn't return 70, please?
let b = 70;
++b; // Using it as a prefix returns the value after incrementing.
console.log(b) // returns 71
I understand how prefix works.
I have read explanations and watched videos on this subject but it's still confusing to me. Thank You.
Both versions of them increment the value they're applied to. If you do nothing with the value of the increment expression itself, they're equivalent, both of them doing the same thing as i += 1. The only time it matters is when you use the result of the increment expression:
let a = 70;
console.log(a++); // outputs 70, the old value of a, but a will be 71 afterwards
console.log(a) // outputs 71; no matter how you increment, after the increment, the value has changed
let b = 70;
console.log(++b); // outputs 71; the new value of b is produced
console.log(b) // outputs 71; same as in case a
The difference you are trying to notice is only visible when you use these prefix/postfix operators inline, something like this:
let a = 5;
console.log(a++);
let b = 5;
console.log(++b);
"return" isn't the right term (functions return, expressions do not).
a++ evaluates as the value before incrementing.
You aren't looking at the value the expression evaluates as, you are just looking at the value of the variable after the increment.
let a = 70;
let result_of_a_plus_plus = a++; // This evaluates as the value before incrementing.
let b = 70;
let result_of_plus_plus_b = ++b; // Using it as a prefix increments the value before the expression is evaluated.
console.log({
a,
result_of_a_plus_plus,
b,
result_of_plus_plus_b
});

Why is the argument passed in to my recursive function not updating its value? [duplicate]

This question already has answers here:
What does x++ in JavaScript do?
(4 answers)
Closed 5 years ago.
I'm just playing around with simple recursion and functions. Nothing too serious, but not doing what I expect:
var recursive = function adder (x) {
x = ++x
if (x < 10) {
console.log('x is now: ' + x)
adder(x)
}
return x
}
console.log(recursive(5))
This completes the loop and runs properly, but am wondering why the 'final' output is '6.' Why don't I get the 'final' value of x after all the recursion is done?
x=++x;
x+=1;
x++;
++x;
You need either the pre increment or the increase by operator, or the postincrement without an reassignment. The post increment retuns first, then increments...
alert((1)++)//1
Some ongoing explanations:
var recursive = function adder (x) {
++x;
if (x < 10) {
console.log('x is now: ' + x)
return adder(x); //lets return our added result
}
return x;//if x=10 lets return 10
}
console.log(recursive(5))//will log 10
It mainly didnt work as expected as primitives are passed by value. So there are actually 5 different x variables in 5 different contexts of adder...
Unlike primitives, objects are passed by reference:
function adder(obj){
obj.x++;
if(obj.x<10){
adder(obj);
}
}
var test={x:1};
adder(test);
console.log(test.x);

difference between a++ and ++a in while loop [duplicate]

This question already has answers here:
Why doesn't the shorthand arithmetic operator ++ after the variable name return 2 in the following statement?
(3 answers)
Closed 6 years ago.
i am trying to figure out, why do i end up with different outcome, when i use a++ versus ++a in a while loop? i know that they are postfix and prefix operations but still do not get why i am getting the results i get
var a = 1;
while (a < 3) {
console.log(a);
a++;
}
i ger results: 1, 2, 2 , when using ++a instead of a++ i get different outcome.
var a = 1;
while (a < 3) {
console.log(a);
++a;
}
in this case i get 1,2,3.
can someone explain operations order step by step and why do i get the output i get?
You'll only get 1,2,2 or 1,2,3 if you run this in the console - outside the console both will only output 1,2 - check the console when running this fiddle
When running in the console, the last number you see in the console is the "result" of the last operation ... so, 2 (because of post increment) in the first case, and 3 (because of pre increment) in the second -
if you add ONE line after the } with just a; - both will show 1,2,3 - like so
var a = 1;
while (a < 3) {
console.log(a);
a++;
}
a;
and
var a = 1;
while (a < 3) {
console.log(a);
++a;
}
a;
shows that a is the same after the while loop finishes

Inline `++` in Javascript not working

Astonished to find out that a line like this :
$('#TextBox').val(parseInt($('#TextBox').val())++ );
Will not work !
I've done some tests, it plays out to the conclusion that the inline ++ doesn't work (in Javascript as a whole ? Or simply in my example ?).
Here's a test with three pieces of code, it seems that ++ is ok with a variable but not inline.
So, no inline ++ for us in Javascript?
There's nothing particular to jQuery about this. ++ increments a variable. You are trying to increment the return value of a function call.
Q: What does x++ mean?
A: x++ means take the value of x, let's call this n, then set x to be n + 1, then return n.
Q: Why does this fail on a non-variable?
A: Let's try it on something simple, say 3, and see where things go wrong.
Take the value of 3 and call it n, okay, n = 3
Set 3 to be n + 1, so 3 = 3 + 1, 3 = 4 this makes no sense! So if this step can't be done, the ++ operator can't be used.
++ works on variables, not directly on numbers
var c = parseInt($('#TextBox').val());
$('#TextBox').val( ++c );
Change the order from
var x = 0;
var result = x++;
result // 0
To
var x = 0;
var result = ++x;
result // 1
Then it will evaluate ++ before retrieving the value.

The "unexpected ++" error in jslint [duplicate]

This question already has answers here:
Why avoid increment ("++") and decrement ("--") operators in JavaScript?
(17 answers)
Closed 5 years ago.
What is the best practice for that then?
Jslint explains that it "adds confusion". I don't see it really...
EDIT: The code, as requested:
var all,l,elements,e;
all = inElement.getElementsByTagName('*');
l = all.length;
elements = [];
for (e = 0; e < l; (e++))
{
if (findIn)
{
if (all[e].className.indexOf(className) > 0)
{
elements[elements.length] = all[e];
}
} else {
if (all[e].className === className)
{
elements[elements.length] = all[e];
}
}
}
The longstanding best practice: use i += 1 instead, following jslint's advice.
As for why it is a better practice than ++, according to Crockford:
The increment ++ and decrement -- operators make it possible to write in an extremely terse style. In languages such as C, they made it possible to write one-liners that: for (p = src, q = dest; !*p; p++, q++) *q = *p; Most of the buffer overrun bugs that created terrible security vulnerabilities were due to code like this. In my own practice, I observed that when I used ++ and --, my code tended to be too tight, too tricky, too cryptic. So, as a matter of discipline, I don’t use them any more.
Edit: Included comment from Nope as this answer continues to get views.
Just add /*jslint plusplus: true */ in front of your javascript file.
To avoid confusion, and possible problems when using minifiers, always wrap parens around the operator and its operand when used together with the same (+ or -).
var i = 0, j = 0;
alert(i++ +j);
This adds i and j (and increments i as a side effect) resulting in 0 being alerted.
But what is someone comes along and moves the space?
var i = 0, j = 0;
alert(i+ ++j);
Now this first increments j, and then adds i to the new value of j, resulting in 1 being alerted.
This could easily be solved by doing
var i = 0, j = 0;
alert((i++) +j);
Now this cannot be mistaken.
Personally, I prefer to put statements such as i++ on a line by themselves. Including them as part of a larger statement can cause confusion for those who aren't sure what the line's supposed to be doing.
For example, instead of:
value = func(i++ * 3);
I would do this:
value = func(i * 3);
i++;
It also means people don't have to remember how i++ and ++i work, and removes the need to apply quite so many preference rules.
The real problem of the ++ operator is that it is an operator with side effects and thus it is totally opposed to the principle of functional programming.
The "functional" way to implement i++ would be i = i + 1 where you explicitly reassign the variable with no side effects and then use it.
The possibility of confusion is that ++ does two things by adding a value AND reassigning it to the variable.
JSLint friendly loop
for (i = 0; i < 10; i += 1) {
//Do somthing
}
Please note that the ++ operator depends on position with respect to the prior/next variable and the newline / semicolon to determine order of operations.
var a = 1;
var b = a++;
console.log(b); // b = 1
console.log(a); // a = 2
var a = 1;
var b = ++a;
console.log(b); // b = 2
console.log(a); // a = 2
There is something called a pre-increment: ++i and a post-increment i++
and there is a difference:
var i = 9;
alert(++i); //-> alerts 10
var j = 9;
alert(j++); //-> alerts 9
alert(j); //-> alerts 10 now, as expected
var k = 9;
alert((k++)); //-> still alerts 9 even with extra parentheses

Categories

Resources