Arrays,

Logic and Loops

JavaScript

Having learned about JavaScript's primitive values, now we'll cover the following topics:

 

  • arrays
  • conditional statements

  • loops

Arrays

Arrays

  • are ordered lists of values
  • are used to store multiple values in a single variable
  • there are two ways of creating an array* :
// using a pair of square brackets - the array literal

var myArray = [ 'string', 100, { key: 'value' }, [ 1, 2 ], null, true ];

// using the array constructor function

var myArray = new Array( 'string', 100, { key: 'value' }, [ 1, 2 ], null, true );
  • are not primitive values, but a special built-in object
typeof myArray 
>> "object"

*for simplicity, readability and execution speed, use the first one (the array literal method)

Arrays

creating and adding values

var myArray = [];
myArray[5] = "My sixth element";
  • each item in an array can be treated like a variable, whose values can be changed using the assignment operator
  • create an array (the empty array in this case)
  • access a specific value using its index (position in the array)
myArray[0]
>> undefined
  • add values to the array*
myArray[0] = "First array element";
myArray[5] = "Am I the second array element?";

*adding elements with high indexes can create undefined "holes" in an array !

! array indexes start with 0

myArray
>> [ "My first element", undefined, undefined, undefined, undefined, "Am I
the second array element?" ];

Arrays

removing values

var myArray = [ 0, 1, 2, 3, 4 ];
delete myArray[3];

// now myArray will be [ 0, 1, 2, undefined, 4 ]
  • removing an item from an array can be done by using the delete operator

the value that was in position 3  has been deleted from the array, but the space that it occupied is still there and contains a value of undefined

 

this means that the array still has the same number of elements and the position can still be referenced as an index

Array

properties and methods

  • the length property helps finding the length of an array

var myArray = [ 0, 1, 2, undefined, 4 ];

myArray.length = 7;
// myArray is [ 0, 1, 2, undefined, 4, undefined, undefined ]

myArray.length = 3;
// myArray is [ 0, 1, 2 ]

the length property is mutable, so it can be manually changed:

- making the array longer fills the extra slots with undefined

- making the array shorter than it already is,  completely removes all the extra elements

  • pop() method removes the last item
  • push() method appends a new value at the end of the array
  • shift() method removes first item
  • unshift() method appends a new value at the beginning of the array
var myArray = [ 0, 1, 2, 3, 4 ];

myArray.pop(); 
// 4 is removed, myArray becomes [ 0, 1, 2, 3 ]

myArray.push(5);
// 5 is added, myArray becomes [ 0, 1, 2, 3, 5 ]

myArray.shift();
// 0 is removed, myArray becomes [ 1, 2, 3, 5 ]

myArray.unshift(6);
// 6 is added, myArray becomes [ 6, 1, 2, 3, 5 ]
  • concat() method can be used to join two or more arrays
var myArray = [ 0, 1, 2 ];

var myConcatArray = myArray.concat([ 3, 4, 5 ]);

// now myConcatArray is [ 0, 1, 2, 3, 4, 5 ]
// and myArray is [ 0, 1, 2 ]

note that this does not change the initial array, it simply creates another array combining the two arrays


assignment would need to be used in order to change the old array to this new array

  • join() method is used to turn the array into a string that comprises all the items in the array, separated by a provided separator (or comma by default)
var myArray = [ 0, 1, 2 ];

myArray.join();
// "0,1,2"

myArray.join(" & ");
// "0 & 1 & 2"
  • the slice() method creates a subarray, effectively chopping out a slice of an original array starting at one index and finishing at the next
var myArray = [ 0, 1, 2, 3, 4 ];

myArray.slice(2,4);
// starts at the third item (index of 2) and finishes 
// at the fourth (the item with index 4 is not included)
// [2, 3]

myArray;
// [ 0, 1, 2, 3, 4 ]

note that this operation is non-destructive so no items are actually removed from the array

  • the splice() method removes items from an array and then inserts new items in their place
var myArray = [ 0, 1, 2, 3, 4 ];

my splicedSubarray = myArray.splice(1,3,'a',6);
// splicedSubarray is [1, 2, 3] while myArray is [0, "a", 6, 4]

myArray.splice(3,0,'b')
// by indicating 0 items to be removed, splice can be used to only
// insert values at a specific index
// myArray is [0, "a", 6, "b", 4]

myArray.splice(2,1)
// myArray is [0, "a","b", 4]

- the first number provides the index at which to start the splice

- the second number tells how many items to remove from the array

- every value after this is then inserted into the array at the same place the other items were removed

- notice that the items removed from the array were returned as a subarray

! to be used instead of delete for removing items completely

  • reverse() method is used to reverse the order of an array (order of the array is changed permanently)
var myArray = [ 0, 1, 2 ];

myArray.reverse();
// myArray is [ 2, 1, 0 ]
  • sort() method is used to sort the order of an array (order of the array is changed permanently)
var myArray = [ "d", "db", "a", 2, 10 ];

myArray.sort();
// myArray is [10, 2, "a", "d", "db"]

alphabetical order is default for String objects and also for Numbers

  • indexOf() method is used to find the first occurrence of a value in an array
var myArray = [ 3, 4, 3 ];

myArray.indexOf(3);
// 0

myArray.indexOf(5);
// -1

Multidimensional Arrays

multidimensional arrays are arrays of arrays

var multiDimensional = [[0,1],[“one”,“two”,“three”],[],[true,false]];
var coordinates = [[1,3],[4,2]];

coordinates[0][0]; // 1
coordinates[0][1]; // 3 

coordinates[1][0]; // 4
coordinates[1][1]; // 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

Control structures

JavaScript programs are a sequence of statements (commands) which an interpreter executes one after another in the same order they were written

 

in order to alter the default order of execution JavaScript has a number of control structures:

 

conditional (if & switch) that make the interpreter execute or skip other statements depending on the value of an expression

 

loops (while, do ... while, for) that execute other statements repetitively

 

jumps (break, return, throw) that cause the interpreter to jump to another part of the program

Conditional statements

Conditional statemets

 

execute or skip other statements depending on the value of a
specified expression

 

are the decision points of your code, and they are also sometimes known as “branches”

  • the if statement

will allow the code inside the block to run only if the condition is true

if (condition) {
    code to run if 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

var truthy = 1,
    falsy = 0;

if (truthy) {
  console.log(truthy + ' is `truthy` value');
}

if (falsy) {
  console.log('This will not be printed, guess why?');
}
  • the else keyword

is 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
}
var falsy = 0;

if (falsy) {
  console.log('This will not be printed, guess why?')
} else {
  console.log('Because ' + falsy + ' is a `falsy value`');
}
  • the ternary operator

is a shorthand way of writing an if ... else statement
has three operands

condition ? (code to run if condition is true) : (code to run if condition isn’t true)
var n = 5;
n%2 === 0 ? console.log(“n is even”) : console.log(“n is odd”);
// n is odd

the ternary operator can make your code  more succinct, but can also make it  difficult to read, so be careful when you  use it !

  • the switch statement

can be used instead of lots of if ... else statements when checking the same expression for all the branches

switch (expression) {                  switch (number) {
  case valueOne:                          case 1:
    statementForCaseOne                     console.log('number is 1'); 
    [break;]                                break;
  case valueTwo:                          case 2:
    statementForCaseTwo                     console.log('number is 2'); 
    [break;]                                break; 
  ... 
  case valueN:                            default:
    statementForCaseN                       console.log('number isn't 1 or 2');
    [break;]                            }
  default:                              // if there's no default the entire
    defaultStatement                    // block of code is skipped
    [break;]
}

it is important to finish each case block with the break keyword, as this stops “fall through”  (more than one of the case blocks being executed).

Loops

looping statements


- are used to execute other statements repetitively
 - bend the path of the source code upon itself to repeat portions of code

 

  • the while loop

will repeatedly run a block of code while a certain condition is true

while (condition) {
  do something
}

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

var count = 0;
while (count <= 15) {
  console.log(count);
  count++;
}

//=> it will print numbers from 0 to 15 then it stops

avoid infinite loops, they will crash your program !

  • the do ... while loop

will repeatedly run a block of code while a certain condition is true, the difference from the while loop is that the condition comes after the code block

do {
  do something
} while (condition);

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

var test = false;
do {
  console.log(test);
} while (test);

//=> it will print `false` and then it stops
  • the for loop

is a construct that is often more convenient than the while statement because it encodes the loop counter variable

for (initialization ; condition ; after) {
    do something
}

the initialization code is run before the loop starts; it initializes any variables used in the loop

the condition has to be satisfied for the loop to continue

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 (var count = 0; count <= 15; count++)
  console.log(count);

//=> it will print numbers from 0 to 15 then it stops
  • nested loops

place a loop inside another loop

for(var n=1 ; n<13 ; n++){
  for(var m=1 ; m<13 ; m++){
    console.log(m + ” multiplied by ” + n + ” is ” + n*m);
  }
}
var myArray = [1, 2, 3, 4];

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

=> it will print 1 2 3 4
  • looping over arrays

Javascript Arrays, Logic & Loops

By Azaleea Cristina Constantinescu