0
Pls explain this code.
I've little knowledge about js. That's why I'm unable to understand output. it's not my code. it's copy from SL. https://code.sololearn.com/Wte3Ds8E07Ra/?ref=app
2 odpowiedzi
+ 3
var arr = [1,2,3,4]; // declares and initializes an array called arr with 1,2,3 and 4
var x = 1; // declares and initializes an variable x with 1
for(var i = 0; i < arr.length; i++){ // this loop runs as long as i lesser then the length of the array
x *= i; // multiplies i with the current value of i which changes every iteration
}
document.write(x + "<br>"); // writes on the side the value of x and linebreaks
/* second code */
var arr = [1,2,3,4]; // same as above
var x = 1;
for(var i = 0; i < arr.length; i++){
x += i; // this time i is not multiplied but added to x
}
document.write(x); // x is written to the document (website)
0
It's a simple code. If you knew only one programming language. You would understand this code easily. Just a simple "array" and " for loop" used here.
1st program:
At first, x=1.
array.length=4 ( there are 4 values in the array).
so the loop will run 4 times.
inside the loop-
x= x*i ( i=0) //and 0 will be assigned to x.
No matter how many times the loop runs it will always be X=0 ( 0*i =0)
2nd program:
x=1.
inside the loop=
x = x+0. ( x= 1)
x= x+ 1 ( 1+1)
x= x+ 2 ( 2+2)...........
...........
at last you will get 7