I just ran into this:
let a = 1;
console.log(a++);
console.log(a); // 2
I am trying to understand how is the value of 'a' changed within console.log.
In a comment you've said:
I understand [that
a++isa = a + 1] but i didnt know this can be done inconsole.log
Calling console.log is just like calling any other function. foo(a++) would do exactly the same thing:
a is set aside for future useaa from Step 1 is passed to foo (or console.log).(That's because you used postfix increment. If you'd used prefix increment [++a], the function would recieve the updated value, not the old value.)
console.log is not special, it's just a predefined function most environments (browsers, Node.js) make available to your code. If you perform side effects within its argument list (such as a++), those side effects occur.
a++ is the equivalent of a = a + 1 happening after the variable a is evaluated.
Thus, you get 1 for the console.log statement and then a is incremented:
Your code could also be written as this, the ++ is just shorter:
let a = 1;
console.log(a);
a = a + 1;
console.log(a); // 2
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators
The example below shows two ways of incrementing the counter within a string.
Note the space before the slash in the first output.
let i = 0;
let docNum = 10;
console.log('Document', i+1, '/' + docNum + '.')
// Document 1 /10.
console.log('Document ' + parseInt(i+1) + '/' + docNum + '.')
// Document 1/10.
a++is the equivalent of runninga = a + 1. Its value is being incremented in the firstconsole.log.console.logis just like calling any other function.foo(a++)would do exactly the same thing.x++getsxand then increments it.++xfirst increments, then returns.