Can someone help explain to me why is it that
let one = 1;
function chg(arg) {
return arg++ // --> shouldn't this be similar to arg + arg? but it's outputting 1
}
console.log(one);
console.log(chg(one));
Can someone help explain to me why is it that
let one = 1;
function chg(arg) {
return arg++ // --> shouldn't this be similar to arg + arg? but it's outputting 1
}
console.log(one);
console.log(chg(one));
x++
is the post-increment expression, i.e. its value is x
, and after that value is returned, the variable is incremented by one.
++x
is the pre-increment expression, i.e. x
is first incremented by one, then returned.
You'll want ++x
here – or since this is a function argument, just be clearer and use x + 1
; the ++
modification will have no effect anyway.
Try below code. You need to use pre-increment instead of post-increment
let one = 1;
function chg(arg) {
return ++arg // --> shouldn't this be similar to arg + arg? but it's outputting 1
}
console.log(one);
console.log(chg(one));
Just edited your code:
let one = 1;
function chg(arg) {
return ++arg;
}
console.log(one);
console.log(chg(one));
or can also be like this
let one = 1;
function chg(arg) {
return arg;
}
console.log(one);
console.log(chg(++one));
let one = 1;
function chg(arg) {
return arg+1 // This is more readable code
}
console.log(one);
console.log(chg(one));