0

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.

5
  • 4
    a++ is the equivalent of running a = a + 1. Its value is being incremented in the first console.log. Commented Feb 24, 2020 at 13:08
  • I understand that but i didnt know this can be done in console.log Commented Feb 24, 2020 at 13:09
  • 4
    @Alinacdn - Calling console.log is just like calling any other function. foo(a++) would do exactly the same thing. Commented Feb 24, 2020 at 13:10
  • That's the basis of programming, pal. x++ gets x and then increments it. ++x first increments, then returns. Commented Feb 24, 2020 at 13:11
  • @T. J. Crowder ok that makes sense. Thank you. Commented Feb 24, 2020 at 13:12

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

you've answered my question! This is what I needed to understand. Thank you so much.
2

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

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.