Prefix and postfix operators [duplicate] - javascript

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
});

Related

How can i make a contraction of this if statement with ternary operator? [duplicate]

I'm just curious about one thing. A little example in Javascript
var a = 1;
a = a++;
console.log(a); // 1
var b = 1;
b = ++b;
console.log(b); // 2
var c = 1;
c += 1;
console.log(c); //2
I understand why it works this way in case b and c, but what about a?
At first the code makes an assignment a = a, the value stays the same actually, but then it should (as I see) make increment and increase value a per unit. But this not happening. Why?
var a = 1;
a = a++;
1 is assigned to a
a++ is evaluated as 1
a++ increments a to 2
a = {result of previous evaluation} assigns the 1 to a so it is 1 again
var b = 1;
b = ++b;
1 is assigned to b
++b increments b to 2
++b is evaluated as 2
b = {result of previous evaluation} assigns the 2 to b so it is 2 still
That is how post increment works
If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing.
a = a++;
when a++ executes a is 2 and the expression returns 1 and a gets assigned to 1.
That is the reason you seeing the value before increment.
Note that if you don't assign back, you see the incremented value of a. You in short ovverriding the incremented value here by assigning it back.
var a = 1;
a++;
console.log(a); // 1
It is rumored that to execute ++a, the value in memory increases and then returns. While for a++, first the value is stored in the created temporary variable, then the value of the primary variable is incremented and the value of the temporary variable is returned - thus the "expenses" for creating the temporary variable increase.
In the case of a++ the return value is actually the original value. You’ve assigned the original value to a again.
The a++ returns the value that before self-increase;
While the ++a returns the value that after the self-increase;
so this is why when you call a = a++, a is equal to 1;
a= a++ return the previous value of a before increment it's value.
you can just use a++
The postfix operator returns the original value of a.
So a is increased by the postfix ++ operator but then a is overwritten by assigning the return value of the operator, which is the value before incrementing.
The return value of a of 1 is temporary stored for assingment, then the increment takes place, a has now the value of 2 and then the assingmet of the former stored value happens.
a = a++;
is the same like
a = (temp = a, a++, temp);
var a = 1;
// Here a++ means a = a; then a = a + 1
a = a++; // so you are assign first step value inside a so thats way a = 1
console.log(a); // 1
means you are storing value that time when a++ is equal to a = a. You simply assigning the value of a and replacing the value.

If I change a variable's value will the original value still exist inside the memory?

let a = 7;
a = 3;
console.log(a); // output 3
In this case, the value 7 is still inside a memory? I was reading that all primitive data types are immutable.
The value of a is kept in memory, until garbage collection eventually recycles it. What the docs mean by immutable is that you can't directly alter the primative (in this case the integer 7). You can only replace the value.
There are examples on the docs but this is another one
let a = 1;
a.toString() // a is still 1, it cannot be mutated
However, we can assign this to another variable
let a = 1;
let b = a.toString() // b is string "1" and a remains as the integer 1
Or we can replace the value
let a = 1;
a = 10; // a is 10
Short answer: no.
Immutable is about the behaviour of the value, not about what happens when it's no longer being references: you cannot change an immutable value, you have to instead reassign your variable if you want it to point to a new value.
let b = 3;
let a = b; // the variable "a" points to the primitive value 3
b = 7; // the variable "a" still points to the primitive value 3
a = 7; // and now it points to a _different_ value. 7, in this case.
This is in contrast to things like arrays or objects, which you can change as much as you like without needing to reassign:
const obj = {};
const a = obj;
obj.cat = `meow`;
console.log(a); // this will show that "a" is { cat: "meow" }
We just changed the content of the value that "a" points to, without any reassignments.

Postfix operator in JavaScript [duplicate]

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.

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.

how does this two varibles exchange using one line? [duplicate]

This question already has answers here:
How does [b][b = a,0] swap between a and b?
(2 answers)
Closed 9 years ago.
I do not know how to learn demo 2,because it's difficult for me.
//demo1.js
var a = 1;
var b = 2;
var c;
c = b;
b = a;
a = c;
log(a); // a = 2
log(b); // b = 1 I can read this one.
//demo 2.js
var a = 1, b = 2;
a = [b][b = a, 0]; // why? '0' is a varible?
console.log(a,b) //output a = 2, b =1
// v---- 1. v---- 3.
a = [b][b = a, 0];
// ^---^-- 2.
Put the value of the b variable in a new Array.
The next set of square brackets is the member operator used for getting the index. In this case, that space is being used to reassign the value of the a variable to the b variable. This can be done because the original value of b is safely in the Array (from step 1.).
Separated by comma operator, the 0 index is then used as the actual value of the Array being retrieved, which if you'll recall is the original b value. This is then assigned to a via the first = assignment on the line.
So to summarize, b is put in the Array, and is retrieved via the 0 index and assigned to a on the left, but not before a is assigned to b (borrowing the space of the [] member operator).
This could also be written like this:
a = [b, b = a][0];
Only difference now is that the second index of the Array is used to do the assignment. Probably a little clearer like this.
The comma operator in Javascript evaluates its left operand, throws it away and returns its right operand after evaluating. Its only use is when the left operand has a side-effect (like modifying a variable's value) but you don't want its result.
[b] defines an array containing b.
[b = a, 0] evaluates b = a - so b now contains the value of a. Then it throws it away. Then it takes the element at index 0 of [b] - returning b. a now contains the value of b that was stored there, rather than the up-to-date value of b, so our swap is successful (albeit obfuscated).

Categories

Resources