Bootcamp Notes – Day 11 (Tues) – Bootstrap: JavaScript – While and For Loops and also Arrays
JavaScript – While and For Loops and also Arrays
While and for loops have long been the workhorses for iteration in programming.
While … Loop
It is very simple but very powerful. With this you can have your computer repeat a task over and over as many times as you want. Must be aware of the infinite Loop.
while (condition) {
…code to execute…
}
You must make sure to include a way for the condition to change to falsy inside the while block, so that the loop does not repeat infinitely! You initially want the condition to be true so that you can enter the while block, but then eventually it’s going to have to be false falsy so that it can exit the while block. Now in our example below the i means iterator. You can also see that our loop ran 10 times: 0 to 9! Every time you go through the loop, it’s called an iteration.
Do While … Loop
Ok, the difference here is that the code inside the do while block will always execute at least once, while the code inside a while block may never execute.
do {
….code to execute….
} while (condition);
Sometimes you need to break out of a while loop completely or to break out of the current iteration and go onto the next one. That’s were break and continue come in handy. Break is your escape out of a while loop.
The continue statement will let you skip an iteration and move to the next iteration. It will simply skip all the code below the continue statement and go back to the top of the loop, evaluating the condition once again.
In the above case, you can see that the iterator was moved to the top of the loop body instead of the bottom, so that it would happen before the continue statement. Otherwise, an infinite loop would have occurred since i would have never incremented.
For Loops
for ([initialization]; [condition]; [final-expression]) {
…code block to execute…
}
The expressions inside the for loops are technically optional, but typically you will use all of them. The terms “initialization” “condition” and “final-expression” to describe the three parts of a for loop are not official terms, but they are used by MDN and are as good as any. You may see them referred to by other terms in other places.
For loops can do the same thing as while loop in less code!
Consider a while loop. There is a very common pattern when you write a while loop, as we have explored. First, you initialize a variable that acts as an iterator – a variable that either increments or decrements inside the loop body. Second, you set a condition. Third, at the end of the loop body execution, you change the iterator (usually by incrementing or decrementing it) so that it will eventually not meet the condition to continue the loop. The for loop condenses these three actions into one line.
Just as in a while loop, you can use break and continue in a for loop. Unlike in a while loop, you do not have to worry about where the iterator is incremented/decremented. The final-expression will occur at the end of the iteration, even if some of the code was skipped due to using continue.
Also, understand that you do not always have to use i++. Any statement that changes the value of i such that it will eventually fail the condition will work. For example, you could count backwards by using i– to decrement instead of increment.
This would create an infinite loop: for (let i = 10; i <= 10; i– )
Arrays
An array is the list of items that are numerically indexed starting with zero. To create an array, uses square brackets with the items inside, separated by commas.
Example: [4, 5, 6, 7]
Now we can put the array within a variable like this:
let myArr = [4, 5, 6, 7]
An array does not always have to contain items of the same data type. You could create an array with items of mixed data types, like this:
myArr = [6, 'a', true, 2]
Arrays are numerically indexed, which means that every item in the array has a numeric index based on its position within the array. Because arrays are zero-indexed, that means the first item in the array will have an index of 0. The second item in the array will have an index of 1, and so on.
You can retrieve an item that’s stored in an array by using its index, like this (enter it into the console): myArr[0];
Notice that the length of an array will always be 1 more than the last index of the array. If you have 4 items in an array, that means that the indices will be 0, 1, 2, and 3, for example.
To get the length of an array, type this: myArr.length;
Arrays are a commonly used data structure and as such JavaScript has a large number of methods which work with arrays. .
Array Methods: indexOf, includes, concat, join
Methods are functions that are tied to objects and can only be called in reference to an object. Arrays are a special kind of object and so they are able to have methods tied to them. One such method is: indexOf
If you know the value of an item in an array, you can get its corresponding index by entering, for example (try it in your console): indexOf
So you can use indexOf() to check whether or not a value is stored in an array. Also, It’s possible to have more than multiple items with the same value in an array. Now, look for the index of 3:
myArr.indexOf(3); As you can see below, it returned the index of the first matching item in the array.
includes just tells us true or false. Whether or not an array includes a certain element.
includes() – this method will simply check for a matching item in an array then return true if found or false if not found.
Example:
concat – concatenates two different arrays together and returns a new array that contains both.
join – The method join() will create a string that contains all the items from two arrays, separated by commas by default.
Notice that one thing that all these methods you’ve seen so far have in common is that they do not change the original array upon which they operate. Check what is stored in arr1, arr2, and arr3 – they all contain the same items they did when they were first created.
There are other methods that do change the original array, classified as mutator methods.
The four mutator array methods: push(), pop(), shift(), unshift().
The array methods here actually cause change to the array upon which they are used. Thus, they are called mutator methods because they mutate the original array.
push() – adds to end of array
pop() – removes the last item in array and return it
Notice that methods work just like functions – they require the parentheses after the method name, which contain the parameter list. Even if there are no parameters being passed to the method, you still need to use an empty set of parentheses, as with pop(). If you just typed myArr.pop, it would not work. If you keep popping the array with myArr.pop(), eventually you would end up with an empty array. If you pop an empty array, you will get the return value of undefined. When you use push(), you can push multiple items in at the same time like this:
myArr.push('a', 'b', 'c');
shift() – removes first item in array and return it
unshift() – adds to beginning of array and return the new length of the array
shift() and unshift() actually shift the indices of the entire array, while push() and pop() do not. For example, when you unshift() a new item into the beginning of an array, then the array item which previously had the index of 0 now has the index of 1, the array item with index 1 now has index 2, and so on.
Additional Resources:
- W3Schools – While Loop
- JavaScript.Info – While and For Loops
- MDN – Loops and iteration – While statement
- W3Schools – For Loop
- JavaScript.info – Loops – While and for
- MDN – For
- W3Schools – Array Methods
- MDN – Global Objects – Array
- JavaScript.info – Array