ARRAYS

Data structures for storing lists of values

 

LOGICAL STATEMENTS

Help us to control the flow of a program

 

LOOPS

Allow us to repeat blocks of code over&over again

ARRAY

LITERALS

ADDING & REMOVING

VALUES

FROM ARRAYS

ARRAY

METHODS

IF/ELSE

STATEMENTS

SWITCH

STATEMENTS

WHILE

LOOPS

DO... WHILE

LOOPS

FOR

LOOPS

ITERATING OVER 

AN ARRAY

 

an ARRAY  =  an ordered list of values

How do we create an array ?

 EMPTY ARRAY OBJECTS

typeOf []
<< "object"
let myArray = [];

(using square brackets)

let myArray = new Array();

(using the array constructor function)

Stacks of Pizza

let pizzas = [];
pizzas[0]; 
<< undefined 

If an array is empty, undefined is returned

To see the position we write its index in []

Adding Values to Arrays

pizzas[0] = "Margherita";

Each item in an array can be treated like a variable.

 

You can change the value using the assignment operator =.

pizzas[0] = "Ham & Pineapple";
pizza[1] = "Mushroom";
pizza[2] = "Spinach & Rocket;
pizzas[5] = "Pineapple & Sweetcorn"; 
pizzas;
<< ["Ham & Pineapple", "Mushroom", "Spinach & Rocket",undefined, undefined, "Pineapple & Sweetcorn"]

Creating Array Literals

let pizzas = ["Margherita", "Mushroom", "Spinach & Rocket", "Pineapple & Sweetcorn"]; 

<< ["Margherita", "Mushroom", "Spinach & Rocket", "Pineapple & Sweetcorn"];

You don’t  have to use the same types of items inside an array!

mixedArray = [null, 1, "two", true, undefined, {} ]; 
<< [null, 1, "two", true, undefined, {}] 

contains 5 different types of primitive values +

 an empty object

Removing Values from Arrays

delete pizzas[3];
<< true

 

Using the DELETE operator

pizzas;
<< ["Margherita", "Mushroom", "Spinach & Rocket", undefined]

 

The value that was in position 3 ("Pineapple & Sweetcorn") has been deleted from the array, but the space that it occupied is still there and contains a value of undefined

pizzas[3]
<< undefined 

LENGTH

pizzas = ["Margherita", "Mushroom", "Spinach & Rocket", "Ham & Pinapple", "Pineapple & Sweetcorn"]
pizzas.length
<< 5

Find out the last item in an array

pizzas[pizzas.length - 1] 
<< "Pineapple & Sweetcorn"

* we subtracted 1 from the length value because the index starts at 0, so the last item in the array will have an index of 1 less than the array’s length

property that shows the length of the array

The length property is mutable  = you can manually change it

pizzas.length = 8 
<< ["Margherita", "Mushroom", "Spinach & Rocket", "Ham & Pinapple", "Pineapple & Sweetcorn", undefined, undefined, undefined]

If you make the array SHORTER than it already is, all the extra elements will be removed completely.

If you make the array LONGER, the extra slots will be filled in with undefined.

pizzas.length = 3 
<< ["Margherita", "Mushroom", "Spinach & Rocket"]

POP()

removes the last item from an array

 pizzas
["Margherita", "Mushroom", "Spinach & Rocket"]
pizzas.pop();
<< "Spinach & Rocket"

PUSH()

 appends a new value to the end of the array

pizzas.push("Pepperoni");
<< 3

returns the new length of the array

SHIFT()

removes the first item from an array

pizzas.shift();
<< "Margherita"

UNSHIFT()

 appends a new value to the beginning of the array

pizzas.unshift("Chicken&Bacon");
<< 3

returns the new length of the array

CONCAT()

merges an array with one or more arrays

pizzas.concat(["Spicy Beef", "Chicken and Mushroom"]);
 
<< ["Chicken & Bacon", "Mushroom", "Pepperoni","Spicy Beef", "Chicken and Mushroom"]

 concat() does not change the pizzas array, it simply creates another array combining the two arrays

pizzas.join(); 
<< "Chicken & Bacon,Mushroom,Pepperoni,Spicy Beef,Chicken and Mushroom"

You can choose

a separator other than a

comma by placing

it inside the parentheses

JOIN()

 turns the array into a string that comprises all the items in the array, separated by commas

pizzas.join(" & "); 
<< "Chicken & Bacon & Mushroom & Pepperoni & Spicy Beef & Chicken and Mushroom"

! separator

SLICE()

creates a subarray

chopping out a slice of an original array starting at one index and finishing at the next

pizzas.slice(2,4)
<< ["Pepperoni", "Spicy Beef"]

 starts at the third item (index of 2) and

finishes at the fourth

(the item with index 4 is not included)

This operation is non-destructive - no items are actually

removed from the array,

pizzas; 
<< ["Chicken & Bacon", "Mushroom", "Pepperoni", "Spicy Beef", "Chicken and Mushroom"]

SPLICE()

removes items from an array and then inserts new items in their place

pizzas.splice(2, 1, "Chicken and Pepper", "Veggie Deluxe") 
<< ["Pepperoni"]
pizzas 
<< ["Chicken & Bacon", "Mushroom", "Chicken and Pepper", "Veggie Deluxe", "Spicy Beef", "Chicken and Mushroom"]

the index at which

to start the splice

how many items to remove from the array

         returns 
the items removed 
from the array 
as a subarray

splice()

splice()  can also be used to insert values into an array at a specific index without removing any items, by indicating that zero items are to be removed

pizzas.splice(4,0,"Ham & Mushroom"); 
<< []

 inserts "Ham & Mushroom" as

the fifth item in the pizzas array

pizzas;
<< ["Chicken & Bacon", "Mushroom", "Chicken and Pepper", "Veggie Deluxe", "Ham & Mushroom", "Spicy Beef", "Chicken and Mushroom"]

splice() removes a value completely, with a length of 1 and without specifying any values to add

pizzas.splice(2,1);
<< ["Chicken and Pepper"];

 will remove the item at index 2

The value removed  will be returned as an array containing that value

pizzas; 
<< ["Chicken & Bacon", "Mushroom", "Veggie Deluxe", "Ham & Mushroom" , "Spicy Beef", "Chicken and Mushroom"] 

REVERSE()

reverses the order of an array

pizzas.reverse();
<< ["Chicken and Mushroom", "Spicy Beef", "Ham & Mushroom", "Veggie Deluxe", "Mushroom", "Chicken & Bacon"]

SORT()

sorts the order of an array

pizzas.sort();
<< ["Chicken & Bacon", "Chicken and Mushroom", 
"Ham & Mushroom", "Mushroom", "Spicy Beef", 
"Veggie Deluxe"]

 

in alphabetical order 

for STRING objects

in alphabetical order 

for numbers

[5, 9, 10].sort(); 
<< [10, 5, 9]

 

indexOf()

finds if a value is in an array

Find the first occurrence of a value in an array

pizzas.indexOf("Spicy Beef");
<< 4

If the item is in the array, it will return
the index of the first occurrence of that item

pizzas.indexOf("Margherita");
<< -1

If the item is not in the array, it will return -1

An array of arrays:

multiDimensional = [[0,1],["one","two","three"],[],[true,false]];
<< [[0,1],["one","two","three"],[],[true,false]]
coordinates = [[1,3],[4,2]];
<< [[1,3],[4,2]]

To access the values in a multidimensional array, we use two indices:

one to refer
to the item’s place in the outer array

one to refer to its place in the inner array

x1 = coordinates[0][0]; 
<< 1

x2 = coordinates[1][0]; 
<< 4

y1 = coordinates[0][1]; 
<< 3

y2 = coordinates[1][1];
<< 2

1st value of the 1st array

1st value of the 2nd array

2nd value of the 1st array

2nd value of the 2nd array

IF statements

if (condition) {
code to run if condition is true
}

will only run if the condition is true

If the condition is
not a Boolean value, it will be converted to a Boolean, depending on whether or
not it is truthy or falsy

let age = 23;
if (age<18) {
    alert("Sorry, you are not old enough to play this game");
}
let age = 12;
if (age<18) {
    alert("Sorry, you are not old enough to play this game");
}

The alert message box will only be displayed if the age is less than 18!

ELSE statements

else keyword can be used to add an extra block of code to run if the condition is false

if (condition)     {
  code to run if condition is true
} else {
  code to run if condition isn't true
}
n = 12;
if (n%2 === 0) {
  console.log("n is an even number");
} else {
  console.log("n is an odd number");
}

Ternary Operator

?

condition ? 
(code if condition is true) : (code if condition is false)
n = 5;

n%2 === 0 ? console.log("n is an even number") : console.log("n is an odd number");

<< n is an odd number

A shorthand way of writing an if ... else statement is to use the ternary operator,
?

switch Statements

if (number === 4) {
alert("You rolled a four");
} else if (number === 5) {
alert("You rolled a five");
} else if (number === 6){
alert("You rolled a six");
} else {
alert("You rolled a number 
less than four");
}
switch (number) {
case 4:
alert("You rolled a four");
break;
case 5:
alert("You rolled a five");
break;
case 6:
alert("You rolled a six");
break;
default:
alert("You rolled a number 
less than four");
break;
}

default keyword is used at the end for any code than needs to be run if none of the cases are true

WHILE Loops

while (condition) {
do something
}

will repeatedly run a

block of code while
a certain condition is true

let bottles = 10;

while (bottles > 0){
alert("There were " + bottles + " green bottles, hanging on the wall. And if one green bottle should accidentally fall, there'd be " + (bottles-1) + "green bottles hanging on the wall");

bottles--;
}

The condition in the example is that the number of bottles has to be
greater than zero
.

 "keep repeating the block of code, as long
as the number of bottles is greater than zero"

the decrement operator (--) is used to decrease the bottles variable
by one.

let bottles = 11;

while (--bottles){
alert("There were " + bottles + " green bottles, hanging on the wall. And if one green bottle should accidentally fall, there'd be" + (bottles-1) + " green bottles hanging on the wall");
}

INFINITE Loops

let n = 1;

while(n>0){
  alert("Hello");
  n++;
}

It is important that the condition in a while loop will be met at some point, OTHERWISE
you’ll be stuck in an infinite loop that can crash your program.

This loop will keep running, as the variable n will always be above zero.

do ... while Loops

similar to a while loop

BUT the condition comes after the block of code

do {
  do something
} while(condition)
let bottles = 10;
do {
alert("There were " + bottles + " green bottles, hanging on the
wall. And if one green bottle should accidently fall, there'd be
 " + (bottles-1) + " green bottles hanging on the wall");
bottles--;
} while (bottles > 0)

the block of code will always be run at least once, regardless of the
condition being true or not.

for Loops

for (initialization ; condition ; after) { do something }
  1. The initialization code is run before the loop starts and is usually employed to initialize any variables used in the loop.
  2. The condition has to be satisfied for the loop to continue.
  3. The after code is what to do after each iteration of the loop, and it is typically used to increment a counter of some sort.
for (let bottles = 10 ; bottles > 0 ; bottles--) {

alert("There were " + bottles + " green bottles, hanging on the
wall. And if one green bottle should accidentally fall, there'd be " + (bottles-1) + " green bottles hanging on the wall");

}
let bottles = 10; // bottles is initialized here instead

for ( ; bottles > 0 ; ) { // empty initialization and increment
alert("There were " + bottles + " green bottles, hanging on the
wall. And if one green bottle should accidentally fall, there'd be " + (bottles-1) + " green bottles hanging on the wall");

bottles--; // increment moved into code block
}

A for loop is the most common as it keeps all the details
of the loop
(the initialization, condition, and increment) in one place and separate
from the code block
.

Nested for Loops

loop inside another loop 

 

 it will have an
inner loop that will run all the way through before the next step of the outer loop
occurs

for(let n=1 ; n<13 ; n++){
   for(let m=1 ; m<13 ; m++){
     console.log(m + " multiplied by " + n + " is " +    n*m);
   }
}
<< 1 multiplied by 1 is 1
<< 1 multiplied by 2 is 2
...
<< 12 multiplied by 12 is 144

Looping over Arrays

a for loop can be used to iterate over each value in an array.

for (let i=0, max=pizzas.length; i < max; i++){
console.log(pizzas[i]);
}

<< "Chicken & Bacon"
<< "Chicken and Mushroom"
<< "Ham & Mushroom"
<< "Mushroom"
<< "Spicy Beef"
<< "Veggie Deluxe"
let  quiz = [   
     ["What is Superman's real name?","Clarke Kent"],   
     ["What is Wonderwoman's real name?","Dianna Prince"],   
     ["What is Batman's real name?","Bruce Wayne"]   
];
let score = 0 // initialize score
for(i=0,max=quiz.length;i<max;i++){
  // get answer from user  
let answer = prompt(quiz[i][0]); // quiz[i][0] is the ith question
  // check if answer is correct 
if(answer === quiz[i][1]){ // quiz[i][1] is the ith answer    alert("Correct!");   
// increase score by 1   
score++; 
} else {   
  alert("Wrong!"); 
  } 
}
alert("Game Over, you scored " + score + " points");
  1. Arrays are an ordered lists of values
  2. Multidimensional arrays contain arrays
  3. Arrays have lots of methods that can be used to manipulate items in the array
  4. We can use an if and else statement to control the flow of code
  5. The switch statement can be used instead of multiple if and else statements
  6. A while loop and do ... while loop can be used to repeat a block of code while a condition is still true
  7. A for loop works in a similar way to a while loop, but has a different syntax
  8. A for loop can be used to iterate over an array

arrays-logic-loops

By mihaelaadln

arrays-logic-loops

Arrays | Logical statements | Loops

  • 162