Control constructs and arrays review

What you need to know for Friday’s assessment.

if statements

if

if (n % 2 === 0) {
  return true;
}

if / else

if (n % 2 === 0) {
  evens++;
} else {
  odds++;
}

for loops

for (let i = 0; i < N; i++) {
  // the body of this loop executes N times
}

while loops

while (!done) {
  // something in here must change the
  // value of done for the loop to end
}

return statement

Including returning early from a function, e.g. from the middle of a loop.

const foo = () => {
  for (let i = 0; i < 100; i++) {
    if (someCondition(i)) {
      return true; // found it
    }
  }
  return false; // didn't find it. N.B. outside the loop
};

The syntax for array values

[10, 11, 71]

A three-element array

[]

An empty array

['foo', 'bar', 'baz']

An array of strings

[[1,2], [3, 4]]

An array of arrays

[x, y, z * 10]

An array whose elements are the current values of x, y, and z * 10

The expressions are evaluated when the array is created.

Changing the variables later doesn't change the array.

The index operator: []

Used to fetch elements of an array.

And in assignments to change an element of an array.

const xs = ['foo', 'bar', 'baz'];
xs[0]          // evaluates to 'foo'
xs[0] = 'quux' // assign 'quux' to zeroth element
xs[0]          // evaluates to 'quux'
xs             // evaluates to ['quux', 'bar', 'baz']

myArray[0]

This is an expression that can be used anywhere a value is needed.

myArray[0] + 10

myArray[0] === someValue

myArray[0].toUpperCase();

The .length property

Gives you the length of an array.

How to write a for loop over an array.

 for (let i = 0; i < theArray.length; i++) {
   // do whatever with theArray[i]
 }

How to use for loops for thins like counting, summing, and finding.

See For loop patterns

Simple uses of nested for loops

The pyramid problem is probably as complicated as it'll get.