Javascript – Looping

The for-of loop

Similar to PHP for as loop

for ( const item of myArray ) console.log(item) // Iterates through an array each item is the value

Getting the index of a value, use the .entries method

for ( const item of myArray.entries() ) {
  key = item[0]; value = item[1];
}

// Destructured approach
for ( const [i, el] of myArray.entries() ) {
  key = i; value = el;
}

Enhanced object literals

ES6 three ways to write object literals:

const miniObject = {
 day1: {
  open: 08:00,
  close: 16:00
 },
 day2: {
  open: 08:00,
  close: 12:00
 },
}

const mainObject = {
 miniObject,  // referencing the other object creates a new object within this object with the same property name
}

For methods (functions) within objects, there is no need to add the function keyword:

orderDelivery: function(arg1, arg2) {
 // action
}
// With ES6 you can do this instead...
orderDelivery(arg1, arg2) {
 // action
}

Compute property names instead of manually writing them:

const weekdays = ['mon', 'tues', 'wed', 'thu', 'fri', 'sat', 'sun'];
const openingHours = {
 [weekdays[3]]: {
  open: 12,
  close: 22
 }
}

You can also compute property names with expressions (ie maths)

Optional Chaining (?)

ES2020

Using ? operator after the potentially non-existent property prevents errors. It will return undefined (falsey) if not, otherwise it will continue down the chain.

restaurant.openingHours.mon?.open // return undefined if mon does not exist (shortcircuit), if it does then return open.
const weekdays = ['mon', 'tues', 'wed', 'thu', 'fri', 'sat', 'sun'];

for (const day of weekdays) {
 const open = restuarant.openingHours[day]?.open ?? 'closed';
}

Optional chaining on methods and arrays too.

const users = [{name: 'Duncan', email: 'duncan@samwell.me'}];
console.log(users[0]?.name ?? 'no name given';

Looping objects

Indirectly looping over objects

Looping over property names: Object.keys

for ( const day of Object.keys(openingHours)) {
 console.log(day) // array of all the property names within that object
}

Looping over property values: Object.values

for ( const values of Object.values(openingHours)) {
 console.log(values) // array of all the values within that object
}

Looping over entire objects: Object.entries

Transfers object into an array

for ( const [key, {propertyName1, propertyName2] of Object.entries(openinghours)) {

}

Leave a Reply

Your email address will not be published. Required fields are marked *