An overview of Javascript fundementals
An array is a variable that can store many values under a single name.
You can simply use an array literal to create a JavaScript Array: var array_name = [item1, item2, ...];
You access an array element by referring to the index number:
var item = array_name[0];
Loops can be used to iterate through or access elements inside arrays easily. The Array.forEach() method can also be used to do this.
There are different kinds of loops:for
- loops through a block of code a number of timesfor/of
- loops through the values of an iterable objectwhile
- loops through a block of code while a specified condition is truedo/while
- also loops through a block of code while a specified condition is truelet classMarks = [62,88,70,62,69,85]; //for loop for (i=classMarks.length - 1; i >= 0; i--) { console.log(classMarks[i]); } //outputs each element of array in reverse order //for/of loop for (let number of classMarks) { console.log(number); } //outputs each element //forEach() method classMarks.forEach(function(number) { console.log(number + 2) }); //adds 2 to each number and outputs it let counter = 0; let j = 0; //while loop while (counter <= 4) { console.log(classMarks[j]); counter ++; j++; } //outputs the first 5 elements in the array
Here are some basic array methods:
Complete the statement to output each element of the carsArr Array.
let carsArr = ["BMW","Volvo","VW","Merc","Toyota","Ford"]; ( car of ) { console.log(); } try Again!