Beginners Javascript | FOR Loops
Now we know how to check and compare value or variables, it’s time to look at loops.
These can be used for lots of things but to start with it can be used to check each value of an array.
the first is the for loop:
var array = [1,2,3,4,5]; for (var i = 0; i < array.length; i++) { if (array[i] == 3) { alert('there is a 3 in this array'); } }
The first part inside the brackets defines a variable to be used in each pass through of the loop it is general practice to use i for this variable and then j,k etc for nested loops as they are not accessible outside of the loop.
The second part is the comparison argument to decide if to run the loop, in this case is i less than the length of the array.
The third part is the action to take after the loop has been executed.
There is are a few different ways that loops are coded that reduces processing required. The first runs through in the same direction but the more cpu intensive part is only done once:
var array = [1,2,3,4,5]; for (var i = 0, var j = array.length; i < j; i++) { if (array[i] == 3) { alert('there is a 3 in this array'); } }
Assuming it doesn’t matter what order the values are processed this form can be used:
var array = [1,2,3,4,5]; for (var i = array.length; i > 0; i--) { if (array[i] == 3) { alert('there is a 3 in this array'); } }
I personally like to use the first version for readability as my code is still small, but choose what bests suits the complexity of the project.