6.2 Javascript Arrays and Loops
Functions
Section titled “Functions”A function allows you to reuse code. We use the function keyword to declare a function, one or more parameters to customize its task, and return to send data back to the location where it was called. To use a function, call it with the function’s name and two parentheses ().

Function Expressions
Section titled “Function Expressions”Functions can be written multiple ways. Following are four examples showuing essentially the same function. The above graphic shows a function declaration using the function keyword. Here is another example:
function square (num){ console.log("Hello from a function declaration!");}The same function can also be written as a function expression like this:
const square = (num) => { console.log("Hello from a function expression!");}This example is the same as the above but, since it only contains one statement inside the function block it can be written without the curly braces using the fat arrow syntax.
const square = (num) => console.log("Hello from a single line function expression!");This is an example of a anonymous function. You can see it has no name because it is passed as the second parameter (the callback) of the addEventListener() handler.
document.addEventListener("click", function (){ console.log("Hello from an anonymous function!");}Function Scope
Section titled “Function Scope”The location you declare a variable determines its scope, or how its value can be accessed by other parts of your program. Below we declare num in the global scope (outside of any functions) so we can access it from anywhere (“globally”) in the program, even inside a function. Alternately, variables created inside a statement block (inside functions, if statements, for loops, etc.) have local scope and are only accessible “locally” inside the curly braces where they were declared. So, creating a function not only packages your code for reuse, it also allows you to protect variables from being changed accidentally by other parts of your code.
let num = 7;function main (){ let secret = 7; console.log(`The number is ${num}`); console.log(`The secret number is ${secret}`);}console.log(`The number is ${num}`);console.log(`The secret number is ${secret}`); // this will show an errorLoops are a control structure that let you repeat specific code until a condition is met.
A loop is a kind of control structure that will repeat until a condition is met.
A Javascript for loop includes a control variable, loop condition, and iterator. If the condition is true then the code in the statement block will run.
Arrays
Section titled “Arrays”Review the data type diagram from Chapter 5 below. In addition to primitive data types, Javascript can store collections of data. An array is an example of a collection type, letting you store multiple values inside a single variable. You can store any type of data inside an array, even other arrays. Explore a simple array in the DevTools console.
Javascript organizes data by primitive and non-primitive types
- Open the DevTools console andto create the following array with a variable declaration, a name, and multiple comma-separated values between square brackets. This introduces a new array with three values. The variable name is written in plural form, a best practice for naming an entity that holds multiple values.
let colors = ["purple", "green", "blue"];- To retrieve any array value, use the index—the position or order of the data in the array—between two square brackets. Arrays are zero-indexed so the first data value is stored at 0, and then 1, and so on. Even though array indexes start at zero, their length reflects the total number in the array. Run this code, line by line, in the DevTools console to see what we mean.
colors[0] // -> "purple"colors[1] // -> “green”colors.length // -> 3- Arrays are also like variables in that you can not only retrieve, or get stored values, you can set values by assigning them to an array index. Run these on the console to see this in action.
colors[0] = "red";colors[0] // -> "red"colors // -> ["red", "green", "blue"];- In Javascript, arrays can store the same or different data types. This includes other arrays. An array inside an array adds a second dimension, similar to a table of data. While
people[0]returns the entire array (or row), which is['Mary', 18, 'mauve'],people[0][1]returns only the first index inside the array atpeople[0].
const people = [ ['Mary', 18, 'mauve'], ['Pam', 33, 'periwinkle']];people[0] // -> ['Mary', 18, 'mauve']people[0][1] // -> 18Put It All Together
Section titled “Put It All Together”Putting this all together, we can create a function that logs each element of an array with a loop. Open the console to see the results.
<button class="logColors">Log them to the console</button>
<script>let colors = ["red", "green", "blue"];function logarray(){ for (let i = 0; i < colors.length; i++){ console.log(i, colors[i]) }}document.querySelector(".logColors").addEventListener("click", logarray);</script>The above example is a little simplified so here’s another example that uses setInterval() to make elements appear to move. The next article covers animation.
See the Pen JS Color Array by Owen Mundy (@owenmundy) on CodePen.
See this Codepen https://codepen.io/owenmundy/pen/dPMxgqj