Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

491
Vistas
how does increment operator work in javascript? directly assigns value to variable?

how does below code give result as 10

var myVar = 2;
myVar = ++myVar + myVar++ + myVar--;
console.log(myVar);

and when directly given as below without assigning to myVar give result as 3 in javascript?

var myVar = 2;
++myVar + myVar++ + myVar--;
console.log(myVar);

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

There are two main factors we need to analyze:

Pre-Increment - The variable is first incremented, and then its value is used:

++x

Post-Increment - The variable value is first used, and then the value is incremented:

x++

With the first example:

var myVar = 2;
myVar = ++myVar + myVar++ + myVar--;
console.log(myVar);

The ++myVar increments the value from 2 to 3 first, so the value 3 is used. Then, for myVar++, the value 3 is used first, and then it is incremented to 4. For myVar--, the 4 is used, and then the value decrements from 4 to 3.

In the end, the expression will be: 3 + 3 + 4 = 10

For the second example:

var myVar = 2;
++myVar + myVar++ + myVar--;
console.log(myVar);

The individual +'s between the myVar are doing nothing. They are adding them together, but there is no variable storing that value. So the only thing that line does is apply the changes of ++myVar, myVar++, and myVar-- to myVar, giving it a value of 3 (from 2 to 3 to 4 to 3).

I hope this helped! Please let me know if you need any further clarification or details :)

about 4 years ago · Juan Pablo Isaza Denunciar

0

As @Teemu said. Reading the documentation is really helpful. Documentation

Maybe this helps also to understand this.

var myVar = 2;
myVar += myVar++;
console.log(myVar);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda