JS challenge. I do not understand the output | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
- 1

JS challenge. I do not understand the output

The output here is 1. I can not understand why. var x = 0; var a = [3, 4]; a[x] = ++x; document.write(a[0]); Does this mean that if x = 0, then a[x] is the first element of array and after ++x it becomes the second element of array with index 1? My first answer was 4.

2nd Nov 2017, 9:03 PM
Olga Slavova
Olga Slavova - avatar
8 Respuestas
+ 2
The ++x is the incrementation of the variable x, which is 0 right now. What ++ means before a variable is essentially: 1) Add 1 to the value of the variable. 2) Then use the value of the variable after it is incremented. So a[x] = ++x means to increment the value of x first (to 1), then to use it in the statement, so now a[0] (x before the increment) is 1.
2nd Nov 2017, 11:58 PM
LunarCoffee
LunarCoffee - avatar
+ 2
plz don't confuse your assign the value for x=0; let me explain your code: your code is var x= 0; var a= [3,4]; a[x]=++x; in this line you changed the value of array of index 0 a[x]=++x. a[0]= 1; you changed the value of array index 0 beacuse the value of x 0 now ,if you have any confusion the let me know
4th Nov 2017, 1:12 AM
Abc
Abc - avatar
+ 1
++x is pre-incremnt the value of variable change on echo example for u if var = 1; if u print ++x it returns the value of x 2 because this change the value of variable before print
3rd Nov 2017, 4:58 PM
Abc
Abc - avatar
+ 1
I understand how increment works. But this array a = [3,4] confuses me. I thought that after increment index 0 becomes 1 thus 4, which has index 1 should be outputed.
3rd Nov 2017, 6:06 PM
Olga Slavova
Olga Slavova - avatar
+ 1
Thank you, guys, for your help and time.
3rd Nov 2017, 6:08 PM
Olga Slavova
Olga Slavova - avatar
+ 1
Code reads like text, so when the code runs, it uses the value of x first (which is 0), and then changes the values.
4th Nov 2017, 12:26 AM
LunarCoffee
LunarCoffee - avatar
+ 1
Oh, now I got it! Thank you again.
4th Nov 2017, 7:00 PM
Olga Slavova
Olga Slavova - avatar
+ 1
welcome
4th Nov 2017, 11:35 PM
Abc
Abc - avatar