About the difference between a++ and ++a

【Foreword】

    Today, a student asked an interview question, about a++ and ++a, know the difference. Although he said it before, he still remembered it. Record it here, and the emphasis will be emphasized in future lectures

 

【main body】

a++ is to output a first, then increment → output first and then increment

var a=1;
console.log(a++); //output 1

++a is incremented first, then output → incremented first and then output

var a=1;
console.log(++a); //output 2

The principle of decrement is similar to 

 

【expand】

Here, in order to enhance memory, I also have a question

var a = 1;
console.log(a++);
console.log(++a);

What is the output result?

Students who do not understand well may think it is 1 and 2,,,,,

but the correct answer is to output 1 and 3

The reason is: a++ has been added once after the output, so when ++a is added 1 on the basis of 2, so it is 3

 

 

.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326213742&siteId=291194637