JavaScript Basics Tutorial

An overview of Javascript fundementals

Arrays and Loops

Arrays

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

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:

Example


let 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

            

Array methods can be used to manipulate or access data stored in an array

Here are some basic array methods:

  • indexOf() - Searches the array for the given element and returns its position
  • includes() - Checks if the array contains a given element
  • remove() - Removes an item from the list
  • pop() - Removes the last element in the array
  • push() - Adds an element to the end of the array and returns the new length
  • shift() - Removes the first element in the array
  • sort() - Sorts elements in the array in ascending order
  • splice() - Adds or removes elements in an array
  • reverse() - Reverses the order of elements in the array

Exercise

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!
            
 prev  Conditional statements
Maps  next