Categories
JavaScript Basics

Basic JavaScript Concepts Front End Development — Arrays and More

If we want to become a front end developer, then learning JavaScript is a must.

In this article, we’ll look at the JavaScript concepts to learn to become a productive front end developer.

Array Methods

JavaScript array methods are real lifesavers. Therefore, we should use them as much as we can.

It’ll let us avoid writing lots of loops and instead we can do many array operations without loops.

Some common methods are as follows.

splice

The splice method let us modify and return a subset of an array.

For instance, we can use it to remove entry with the given index as follows:

const arr = ['a', 'c', 'd', 'e'];
const spliced = arr.splice(1, 0);

The code above removes 1 entry with index 0, so we get [“a”, “c”, “d”, “e”] as the value of arr .

If we want to add an entry, we can write the following:

const arr = ['a', 'c', 'd', 'e'];
const spliced = arr.splice(1, 0, 'b');

Then have 'b' inserted to the array at index 1 and removes 0 entries. And we get [“a”, “b”, “c”, “d”, “e”] as the new value of arr .

If we want to replace an item, then we can write the following:

const arr = ['a', 'c', 'd', 'e'];
const spliced = arr.splice(1, 1, 'b');

The code above inserts 'b' ar index 1 and remove 1 entry starting with index 1, so we get [“a”, “b”, “d”, “e”] for arr .

Since 'c' was removed, we also get [“c”] as splice ‘s return value.

slice

slice returns a shallow copy of the array from the given start and before the end position.

If the end position is omitted, then the rest of the array is returned.

For instance, we can use it as follows:

const arr = ['a', 'b', 'c', 'd', 'e'];
const sliced = arr.slice(2, 5);

Then we get [“c”, “d”, “e”] as the value of sliced .

sort

sort lets us sort an array in place the way we want.

If a function returns negative or 0, the order remains unchanged. Otherwise, the order is switched.

We can use it by writing:

const arr = [1, 7, 4, 5, 6, 7, 4, 6];
arr.sort((a, b) => a - b);

Then we get [1, 4, 4, 5, 6, 6, 7, 7] as the value of arr .

Generators

Generator functions let us return the new value of an iterable object or anything else in sequence.

It’s denoted by function* and we use the yield keyword to return the next item.

For instance, we create a generator as follows:

function* words() {
  yield 'foo';
  yield 'bar';
  yield 'baz';
}

And we can use it:

const gen = words();
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);

We called next to get the next entry. The value of the next entry is stored in the value property.

Therefore, we get:

foo
bar
baz

logged in the console log output.

We can generate infinite values, so we can write:

function* numGenerator() {
  while (true) {
    yield 100 * Math.random();
  }
}

and we get a random number between 0 and 100 each time we run:

gen.next().value

after we created gen as follows:

const gen = numGenerator();

Equality Comparison Operators

JavaScript has 2 equality comparison operators, they are == and === .

== does implicit conversion before doing comparisons, which creates issues for us more often than not.

Therefore, we should probably not use it.

On the other hand, === compares objects and primitive values as is. Therefore, it’s much safer to use.

We can use the === operator as follows:

console.log(0 === 0);

That should log true .

For objects, it returns true if they’re the same reference.

For instance, if we have:

const foo = {};
console.log(foo === foo);

will log true , but:

const foo = {};
console.log(foo === {});

logsfalse since they aren’t referencing the same object.

Conclusion

We can make array manipulation a lot easier by using array methods.

Sorting, inserting and removing items are no problems with built-in array methods.

Also, generators are great for sequentially return items however we wish to.

Equality comparison should be done with === to save us headaches.

Categories
JavaScript Basics

Many Ways to Iterate Through JavaScript Arrays

There’re many ways to do things with JavaScript. For instance, there’re lots of ways to iterate through the items of an array.

In this article, we’ll look at several ways we can iterate through a JavaScript array.

Array.prototype.forEach

The array instance’s forEach method takes a callback that takes up to 3 parameters, the current item, the index, and the original array.

The index and original array are optional parameters.

The 2nd argument is an optional argument that takes a value of this that’ll be used in the callback.

For instance, we can use it as follows:

const arr = [1, 2, 3];
arr.forEach((a, i, arr) => {
  console.log(a, i, arr)
})

In the code above, we defined the arr array, then we iterated through it by calling forEach with a callback that has all 3 parameters.

Then we get:

1 0 "[1,2,3]"
2 1 "[1,2,3]"
3 2 "[1,2,3]"

from the console log output.

To pass in the this value for use inside the callback, we can write the following:

const arr = [1, 2, 3];
arr.forEach(function(a) {
  console.log(a + this.num);
}, {
  num: 1
})

In the code above, we passed in:

{
  num: 1
}

as the 2nd argument of forEach .

Therefore, this.num is 1. So a + this.num is a + 1 , and we get:

2
3
4

from the console log output.

Note that we can’t break of the forEach method once it’s called.

The for-in Loop

The for...in loop is good for iterating through an object’s keys along with the keys of its prototypes all the way up the prototype chain.

It only loops through enumerable properties, and they’re looped through without any defined order.

For instance, we can use it as follows:

class Foo {
  constructor() {
    this.a = 1;
  }

}
class Bar extends Foo {
  constructor() {
    super();
    this.b = 2;
    this.c = 3;
  }
}

const bar = new Bar();
for (const key in bar) {
  console.log(bar);
}

In the code above, we have 2 classes, Foo class with instance variable a and class Bar which extends Foo , which has instance variables b and c .

Therefore, a Bar instance would have a Foo instance as its prototype.

Then when we loop through the keys of bar which is a Bar instance, it’ll log the keys of both the Bar instance and its prototype’s keys.

And we get:

a
b
c

as the values that are logged in the console log.

The for-of Loop

The for...of loop lets us loops through many kinds of object. They include arrays and any kind of iterable objects like maps, sets, arguments , DOM NodeLists, etc.

This loop is introduced with ES2015.

Anything that implements the Symbol.iterator method can be iterated through with the for...of loop.

Unlike the forEach method, we can write break to break the loop.

For instance, we can use it as follows:

for (const a of [1, 2, 3]) {
  console.log(a);
}

Then we get:

1
2
3

from the console log output.

We can also iterate through other iterable objects like sets. For instance, we can use it with a set as follows:

for (const a of new Set([1, 2, 3])) {
  console.log(a);
}

Then we get the same result.

Regular for Loop

A regular for loop is one the oldest kinds of loops. It has 3 parts, which are the index initializer, a run condition, and an index modifier that runs at the end of each iteration.

For instance, we can use it as follows:

const arr = [1, 2, 3]
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

In the code above, we have the arr array. Then we create a for loop to loop through it.

The index initializer is let i = 0 , the run condition is i < arr.length so it runs until the i is 1 less than the arr ‘s length. i++ is the index modifier which updates i at every iterate by increasing i by 1.

Conclusion

We can loop through arrays by using the forEach method, which is part of the array’s instance.

A loop for looping through object keys is the for...in loop.

A more versatile loop is the for...of loop which can loop arrays or any other kind of iterable object.

Categories
JavaScript Basics

JavaScript Arrays and Conditional Tricks to Save Us Time and Frustration

When writing JavaScript apps, we often have to write code to solve problems that we encounter frequently.

In this article, we’ll look at some common problems that we encounter in our JavaScript code so that we don’t have to look further to find answers to them.

Flatten Multidimensional Arrays

We can flatten multidimensional arrays by using various methods with arrays.

There’re the flat , flatMap , and concat methods to flatten arrays. Some of these are used along with the spread operator.

For instance, we can use the array instance’s concat method with the spread operator as follows:

const arr = [1, [2, 3],
  [4, 5], 6
];
const flattened = [].concat(...arr);

In the code above, we called the concat method on an empty array to put the items in the arr array into a new array.

The spread operator spreads the items in the array as arguments so that they can be populated into the new array with concat .

Then we get that flattened is [1, 2, 3, 4, 5, 6] .

If we have a deeply nested array, then we need to work a bit harder to flatten an array recursively.

For instance, we can do that as follows:

const flatten = (arr) => {
  const flat = [];

  arr.forEach(a => {
    if (Array.isArray(a)) {
      flat.push(...flatten(a));
    } else {
      flat.push(a);
    }
  });

 return flat;
}

In the code above, we have the flatten function, which takes an array arr as an argument.

In the function body, we call forEach on arr . In the callback, we check if each array entry is an array entry by calling Array.isArray with a , where a is the array entry being looped through.

If it is, then we push the flattened array into the flat array and call flatten on it to flatten the nested array.

Otherwise, we just push the entry into flat . Then we return flat , which is the recursively flattened array.

Then we can call it as follows:

const arr = [1, [2, 3],
  [[4, 5]], 6
];
const flattened = flatten(arr);

Then we get that flattened is [1, 2, 3, 4, 5, 6] .

JavaScript’s array instance also has the flat method to flatten an array by an arbitrary depth.

It takes an argument, which is a positive integer or Infinity , to flatten the nested array by the given depth level or flatten all levels respectively.

flat returns a new flattened array.

For instance, we can call it as follows:

const arr = [1, [2, 3],
  [
    [4, 5]
  ], 6
];
const flattened = arr.flat(1);

Then we get:

[
  1,
  2,
  3,
  [
    4,
    5
  ],
  6
]

If we pass in Infinity as follows:

const arr = [1, [2, 3],
  [
    [4, 5]
  ], 6
];
const flattened = arr.flat(Infinity);

Then flattened is [1, 2, 3, 4, 5, 6] .

The flatMap method calls map and then calls flat with level 1.

For instance, we can use it as follows:

const arr = [1, 2, 3];
const flattened = arr.flatMap(a => [a])

Then flattened is [1, 2, 3] because flatMap calls map to map each number to an array with a single number. Then it calls flat to flatten the array by 1 nesting level.

Therefore, we get that flattened is [1, 2, 3] .

Short Circuit Conditionals

If we have conditional statements like the following:

if (condition) {
  doSomething();
}

We can shorten it with the && operator as follows:

condition && doSomething();

The 2 pieces of code are equivalent because in the 2nd piece of code, the && operator returns true only when both operands are truthy.

So when condition is a truthy value, then it’ll move on to evaluate the 2nd operand, which is to run doSomething() .

This is the same as what the if statement does. If condition is truthy, then doSomething() is run.

Conclusion

There’re multiple ways to flatten an array with JavaScript. One is the flat method to flatten the array by any arbitrary depth level, including Infinity .

The concat method can be used with the spread operator to do the same thing.

The flatMap method calls map and flat with depth level 1.

To shorten our conditional statements where we run something if a condition is truthy, we can use the && operator to replace that.

Categories
JavaScript Basics

Ways to Iterate or Combine JavaScript Arrays Entries

There’re many ways to do things with JavaScript. For instance, there’re lots of ways to iterate through the items of an array.

In this article, we’ll look at ways to iterate through and combine items inside arrays.

Array.prototype.reduce

The array instance’s reduce method is used to combine the entries in an array into one value.

It takes up to 2 arguments. The first is a callback that takes the combined value so far as the first parameter and the current value being processed as the 2nd parameter.

The 3rd parameter is the index of the current value and the last is the original array. These 2 are both optional.

The 2nd argument is the initial value to be used for the combined value.

For instance, we can use it to sum up all the items in the array as follows:

const result = [1, 2, 3].reduce((a, b) => a + b, 0);

In the code above, we called reduce on [1, 2, 3] and compute the sum of the entries by passing in:

(a, b) => a + b

where a is the sum so far, and b is the current item being processed. 0 is the initial value of the sum.

Then result should be 6 since it’s the sum of all the numbers in the array.

Array.prototype.join

The join method combines all the array entries into a string, separated by a separator of our choice.

It takes one argument, which is a string with the separator we want to use.

For instance, we can use it as follows:

const result = [1, 2, 3].join(',');

Then we get 1,2,3 for result .

ES2018 for await of Loop

The for...await...of loop is used to iterate through promises to make sure that they are completed in sequence.

It’s like for...of but it’s for promises. For instance, we can use it as follows:

const promises = [1, 2, 3, 4, 5].map(a => new Promise((resolve) => setTimeout(() => resolve(a), 1000)));

(async () => {
  for await (const p of promises) {
    console.log(p);
  }
})()

In the code above, we have an array of promises, and we used the for...await...of loop to resolve them one at a time.

So we should see the numbers 1 to 5 logged in the console after a 1-second delay, as we specified in the setTimeout function.

Array.prototype.flat

The array instance’s flat method lets us flatten an array by reducing the depth of the array. It takes an argument with a positive number to specify the number of levels to flatten. Or we can specify Infinity to recursively flatten an array.

It returns a new flattened array.

For instance, we can use it as follows:

const arr = [
  [
    [1], 2, 3
  ]
];

const flattened = arr.flat(1);

In the code above, we have an array that has nested arrays in it. Then when we call flat on it with 1 as the argument, we get that flattened is :

[
  [
    1
  ],
  2,
  3
]

If we specify Infinity as its argument as follows:

const flattened = arr.flat(`Infinity`);

We get:

[
  1,
  2,
  3
]

as the value of flattened .

Array.prototype.flatMap

The flatMap method calls map then flat . It can flatten by 1 nesting level only after doing the mapping.

For instance, if we have:

const arr = [
  1, 2, 3
];

const flattened = arr.flatMap(a => [a * 2]);

Then flattened is:

[
  2,
  4,
  6
]

since we mapped the entries by multiplying each by 2, and then we put each in their own array.

Then the flat part of flatMap flattens the individual arrays so that we get back the entries that have no array in it.

If we write:

const arr = [
  1, 2, 3
];

const flattened = arr.flatMap(a => [[a * 2]]);

Then we get:

[
  [
    2
  ],
  [
    4
  ],
  [
    6
  ]
]

as the value of flattened since flatMap only flattens up to one level.

Conclusion

The array flat method lets us flatten an array as many levels as we like by flattening any nested arrays.

The flatMap method does the same thing as map and flat(1) one after the other.

The for...await...of loop lets us complete an array of promises in sequence.

Array instance’s reduce method lets us combine the values in an array into one.

The join method lets us combine array entries into one as a string.

Categories
JavaScript Basics

More Ways to Iterate Through JavaScript Arrays

There’re many ways to do things with JavaScript. For instance, there’re lots of ways to iterate through the items of an array.

In this article, we’ll look at several ways we can iterate through a JavaScript array.

The While Loop

The while loop is a loop that’s fast. And we only need the run condition to run the loop.

For instance, we can use it to loop through an array as follows:

const arr = [1, 2, 3]
let i = 0;
while (i < arr.length) {
  console.log(arr[i]);
  i++;
}

In the code above, we have a while loop with the initial index defined outside as i .

Then in the while loop, we defined the run condition as i < arr.length , so it’ll run if i is less than arr.length .

Then inside the loop body, we log the items from arr by its index, and then increment i by 1 at the end of the loop.

The Do-while Loop

The do...while loop runs the first iteration regardless of the condition. Then at the end of each iteration, it’ll check the run condition to see if it’s still satisfied.

If it is, then it’ll continue with the next iteration. Otherwise, it’ll stop. For instance, we can loop through an array as follows:

const arr = [1, 2, 3]
let i = 0;
do {
  console.log(arr[i]);
  i++;
}
while (i < arr.length)

In the code above, we have:

do {
  console.log(arr[i]);
  i++;
}

Which iterates through the entries by accessing the arr ‘s entry via index i , then i is incremented by 1.

Next, it checks the condition in the while loop.

Then it moves on to the next iteration until i < arr.length returns false .

Array.prototype.map

The array instance’s map method is for mapping each array entry into a new value as specified by the callback function.

The callback takes up to 3 parameters. The first is the current item, which is required. The 2nd and 3rd are the current array index and original array respectively.

The callback returns a value derived from the current item.

It can also take an optional 2nd argument to set the value of this inside the callback.

For instance, if we want to add 1 to each number in the array, we can write:

const arr = [1, 2, 3].map(a => a + 1);

In the code above, we have a => a + 1 , which is used to add 1 to a , which is the current item being processed.

Therefore, we get [2, 3, 4] as the value of arr .

We can pass in a value for this in the callback and use it as follows:

const arr = [1, 2, 3].map(function(a) {
  return a + this.num;
}, {
  num: 1
});

In the code above, we have:

{
  num: 1
}

which is set as the value of this . Then this.num is 1 as we specified in the object. So we get the same result as the previous example.

map doesn’t mutate the original array. It returns a new one with the mapped values.

Array.prototype.filter

The array instance’s filter method returns a new array that meets the condition returned in the callback.

The callback takes up to 3 parameters. The first is the current item, which is required. The 2nd and 3rd are the current array index and original array respectively.

The callback returns a value derived from the current item.

It can also take an optional 2nd argument to set the value of this inside the callback.

For instance, we can get a new array with all the entries that are bigger than 1 as follows:

const arr = [1, 2, 3].filter(a => a > 1);

In the code above, we called filter with a => a > 1 to only take entries that are bigger than 1 from the array it’s called on and put it in the returned array.

Then we get that arr is [2, 3] .

To pass in a value of this and use it, we can write:

const arr = [1, 2, 3].filter(function(a) {
  return a > this.min;
}, {
  min: 1
});

Since we assigned this inside the callback to:

{
  min: 1
}

this.min will be 1, so we get the same result as in the previous example.

Conclusion

We can use the while and do...while loop to loop through items until the given run condition is no longer true.

The array instance’s map method is used to map each entry of an array to a different value. The mapped values are returned in a new array.

The filter method is used to return an array that has the entries that meet the condition returned in the callback inside.