Why is x not incremented or decremented in the first program making x equal to 1 and what also makes the second program invalid? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Why is x not incremented or decremented in the first program making x equal to 1 and what also makes the second program invalid?

//first program var x = 1; var y = 4; function func() { while(y > 0) { x++; y--; } } document.write(x); //second program var arr = [1, 2, 3]; arr[0].push(4); console.log(arr);

7th Jul 2019, 3:27 PM
eMBee
eMBee - avatar
7 Answers
+ 3
If you actually called the function. var x = 1: var y = 4; function func() { while (x > 0) { x++; y--; } } func(); document.write(x)
7th Jul 2019, 3:58 PM
Airree
Airree - avatar
+ 3
First program: The function never executes. It won't do anything to the program, since it wasn't called. Second program: The push is a method of the array prototype. arr[0] is 1, a number, and since I remember numbers are not arrays, and there isn't a push method for numbers, therefore it will cause an error
7th Jul 2019, 3:42 PM
Airree
Airree - avatar
+ 3
Airree So in what kind of scenario would x be 5 with the while loop still wrapped inside the func function?
7th Jul 2019, 3:56 PM
eMBee
eMBee - avatar
+ 3
Airree wow, thanks for your help. God bless you for me 😁👍
7th Jul 2019, 4:00 PM
eMBee
eMBee - avatar
+ 2
Airree, I understand your explanation for the second program but for the first, are you saying that the function will only execute when we have "do {}" in the program?
7th Jul 2019, 3:50 PM
eMBee
eMBee - avatar
+ 2
No, that's not what I'm saying. The while loop, as you can see, is wrapped inside the func function. You might have heard, but functions are only executed, when they are called. The func function is never called, therefore the while loop doesn't execute. If it wouldn't be inside a function, yes, x would be 5
7th Jul 2019, 3:53 PM
Airree
Airree - avatar
+ 1
The function in the first program will only execute if you add func() to your program. You’ve defined it but not called it. Also, unless x and y are global variables, the function won’t recognize them. You can fix this easily by changing the function to accept two values func(x,y), and then pass these two values when you call the function.
13th Jul 2019, 11:35 PM
Benjamin