Skip to content
Angular Essentials
GitHub

JS/ES6 recap

Arrow function

A compact alternative to a traditional function expression, but is limited and can’t be used in all situations.

// Before
var func = function() {
  return "Hi!";
}

// With arrow function
const funcn = () => {
  return "Hi!";
}

It gets shorter! If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword:

const func = () => "Hi!";

If you have parameters, you pass them inside the parentheses:

const paramFun = (param) => `Hello ${param}`;

If you have only one parameter, you can skip the parentheses as well:

const noParentheses = param => `Hello ${param}`;

Callback function

Functions are objects. Can we pass objects to functions as parameters? Yes.

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

function greet(callback) {  
    callback();
}

greet() takes another function, callback as a parameter and calls it inside.

Why do we need callback functions?

From here.

JavaScript runs code sequentially in top-down order. However, there are some cases the code runs (or must run) after something else happens and also not sequentially. This is called asynchronous programming.

Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has been completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.

In JavaScript, the way to create a callback function is to pass it as a parameter to another function, and then call it back right after something has happened or some task is completed.

Callback with setTimeout

const greet = function() {  
    console.log("Hi!");
}
 
setTimeout(greet, 5000);

Callback when the promise is resolved

const myPromise = new Promise((resolve, reject) => {
  resolve('Hi!');
});

myPromise.then(val => {
  console.log(val);
});

Array methods

forEach()

  • executes a provided function once for each array element.
  • is not executed for empty elements.
  • break statement cannot be used because of the callback function.
  • await keyword cannot be used due to the callback function. It may lead to incorrect output.
const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"
  • return doesn’t stop looping.
const array = [1, 2, 3, 4];
array.forEach(element =>  {
  console.log(element);
  if (element === 2) 
    return;
});
// Output: 1 2 3 4
  • The reason is that we are passing a callback function in our forEach function, which behaves just like a normal function and is applied to each element no matter if we return from one i.e. when an element is 2 in our case.

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

every()

  • behaves exactly like forEach(), except it stops iterating through the array whenever the callback function returns a falsy value.
  • With every(), return false is equivalent to a break, and return true is equivalent to a continue.
// Prints "1, 2, 3"
[1, 2, 3, 4, 5].every(v => {
  if (v > 3) {
    return false;
  }
  console.log(v);
  // Make sure you return true. If you don't return a value, `every()` will stop.
  return true;
});

map()

  • creates a new array populated with the results of calling a provided function on every element in the calling array.
  • does not execute the function for empty elements.
  • does not change the original array.
const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

filter()

  • creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
  • does not execute the function for empty elements.
  • does not change the original array.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made.

find()

  • returns the first element in the provided array that satisfies the provided testing function.
  • If no values satisfy the testing function, undefined is returned.
  • does not execute the function for empty elements.
  • does not change the original array.
const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

includes()

  • determines whether an array includes a certain value among its entries, returning true or false as appropriate.
  • is case-sensitive.
const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false