+ 3
Could someone explain me how this code works line to line? Thanks.
function f(a){ var arr=[]; var i=0; while(i<a.length){ if(a[i]%2!==0){arr.push(a[i]);} i++; } var a=[1,4,3,5]; document.write(f(a));
1 Answer
+ 6
//Define a function f which takes an argument let's say a
function f(a)
//create an empty array named arr
var arr = []
//create a variable i to use in while loop condition statement
var i = 0
//run the loop while i is less than function's argument length (a.length)
while( i < a.length){
//if a index i modulus 2 is not equal to 0
if (a[i] % 2 !== 0){
//then push a[i] to our variable arr
arr.push(a[i])
//increment the counter variable i otherwise this will be an infinite
i++
}
//added this return statement below so you can see the output
return arr
} // this curly brace was absent in your code
// assign variable a to an array of length 4
var a = [1, 4, 3, 5]
//now write the result to the html document
document.write(f(a))