Acdn
Acdn

Reputation: 638

Increment within console.log changes value of variable

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.

Upvotes: 0

Views: 4849

Answers (4)

Victoria Stuart
Victoria Stuart

Reputation: 5082

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.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074555

In a comment you've said:

I understand [that a++ is a = a + 1] but i didnt know this can be done in console.log

Calling console.log is just like calling any other function. foo(a++) would do exactly the same thing:

  • First, the value of a is set aside for future use
  • Then 1 is added to it, updating a
  • Then the old value of a 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.

Upvotes: 4

mikeb
mikeb

Reputation: 11267

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

Upvotes: 1

caramba
caramba

Reputation: 22480

a++ is like you would run it outside the console.log() it's just adding +1 to a

let a = 1;
console.log(a++);
console.log(a); // 2
a++
console.log(a); // 3

Upvotes: 2

Related Questions