Check out the new web development bootcamp! learn more

It has already been one month since I first created this blog! I am trying to improve it. Do you have any ideas? leave a feedback

home > learn javascript part2

Web Dev Bootcamp ∙ Learn Javascript Part 2 ∙ ES5

Hieu Nguyen · May 04, 2020 · 6 min read

webdevjavascriptcourse

0

0 leave some love!

Goal

Here we will learn some new Javascript features that were introduced in ES5 that will be useful when developing our React and Nodejs apps.

What is ES5

ES5 is a set of new features added to Javascript in 2009 to enhance productivity and to enable certain features natively without the need to hack it or code it out yourself

ES5 Features

Note: all of these features can be implemented using basic Javascript, but they exists to save you time.

We will walk through a couple of these features and see how they can be implemented using basic Javascript. I am not suggesting that you should develop that way , but it can shed light on how these features were constructed

String.trim()

allows you to trim whitespaces from the start and end of a string.

var str = " Hi There   "
var trimmedStr = str.trim() // "Hi There"

Array.isArray()

checks if a variable is an array

var arr = []
var str = "[]"

Array.isArray(arr) // true
Array.isArray(str) // false

Array.forEach()

loops through the elements on an array and run some code for each item, but it does not change the original array or return anything

var arr = [1, 2, 3]
arr.forEach(function(element, index, arr, thisArg) {
  if (element === arr[index]) {
    console.log(element)
  }
})

forEach is part of the Array prototype object and as such, you can invoke forEach using the . operator on any array [].forEach()

What is the function that we are passing to forEach ?

It is an anonymous function that accepts four parameters:

  1. the current element
  2. the index of the current element
  3. the entire array
  4. finally the thisArg

For most of your work, you will be concerned with only the first three parameters.

Let’ try to recreate the forEach() function using regular Javascript

function forEach(arr, fn) {
  var i = 0
  while (i < arr.length) {
    fn(arr[i], i, arr, this)
    i++
  }
  return
}

Can you figure out what is happening in this function…

Here is what is happening:

  1. we declared a function called forEach(arr, fn) that accepts an array and a function
  2. we loop through each element in the array using a while loop
  3. in each iteration we are invoking the function fn that we passed in and passing the current element arr[i], the current index i, the array arr , and a this reference
  4. once the loop terminates, we return nothing

Let’s trying calling it

forEach([1, 2, 3], function(currentElement, currentIndex, array, thisArg) {
  console.log(currentElement, currentIndex)
})

/* 
Output:
1 0
2 1
3 2
*/

Array.map()

Array.map() is similar to Array.forEach(), but it maps each element of the array to a new item and returns a new array with those new items

var newArray = [1, 2, 3].map(function(
  currentElement,
  currentIndex,
  array,
  thisArg
) {
  return currentElement * 2
})

// newArray = [2,4,6]

Here we are mapping over an array, and returning each value doubled

Array.filter()

Used when trying to filter certain elements from the array

var filteredArr = [1, 2, 3].filter(function(
  currentElement,
  currentIndex,
  array,
  thisArg
) {
  return currentElement > 2
})

// filteredArr = [3]

When filtering an array using Array.filter(), if the function that we pass in returns true, then that element is included in the new array. otherwise, it is excluded from the new array.

Array.reduce()

This one is a little complicated because there are many ways to use it.

You can use it to map and filter at the same time

Here is an implementation using just map and filter that filters out value that are >=2 and maps those values to a new value that is doubled the original

var newArr = [1, 2, 3]
  .filter(function(currentElement) {
    return currentElement >= 2
  })
  .map(function(currentElement) {
    return currentElement * 2
  })

//output: newArr = [4,6]

The downside to doing this, is that you are performing filter and map sequentially meaning you are revisiting certain elements twice! Once for filtering and another time to map().

This is generally ok for small amount of data, but what if you have a set of millions of values? Doing it this way can be quite expensive

Wouldn’t it be better to visit each value, check if it should be filtered out and doubling it at the same time? we would only have to visit each element once!

Here is the same functionality implemented using Array.reduce():

var newArr = [1, 2, 3].reduce(function(
  accumulator,
  currentElement,
  currentIndex,
  arr,
  thisArg
) {
  if (currentElement >= 2) {
    accumulator.push(currentElement * 2)
  }
  return accumulator
},
[])

// output: newArr = [4,6]

Here we are:

  1. invoking the reduce() function on our array [1,2,3].
  2. passing in a function that accepts an accumulator, the currentElement, the currentIndex, the array, and the thisArg
  3. We are also passing in an empty array as a second argument to the reduce() function. This empty array is our accumulator
  4. In each iteration, we check if the currentElement is greater than or equal to 2
  5. If it is, then we add the doubled value of the currentElement to the accumulator
  6. Then we return the accumulator

Note: always make sure to return a accumulator

learn more about Array.reduce()

Array.every()

Checks if every element in the array meets a condition and returns a boolean

var res = [1, 2, 3].every(function(currentElement) {
  return currentElement < 5
})

// res = true, every element is less than 5

var res2 = [1, 2, 3].every(function(currentElement) {
  return currentElement < 2
})
// res2 = false, not every element is less than 2, because 3 is greater than 2

Array.some()

Checks if at least one element meets a condition and returns a boolean

;[1, 2, 3].some(function(currentElement) {
  return currentElement === 1
}) // true because there is at least one element that is equal to 1

Note: the function will terminate when it encounters the first element that meets the condition

Object Properties Access Using Strings

Prior to ES5 object members are accessed using the . operator, such as person.name

In ES5 the equivalent can be written as person['name']

Why would you write write it this way? It looks more complicated and doesn’t seem to do anything different, then why?

This is useful when you are given the object key as a string

Multiline String Literals

You can now create multiline string literals using: ``

var str = `line 1
            line 2
            line 3`

More information

list of all ES5 features

What’s Next?

Learn more advanced Javascript features in ES6!


Hieu Nguyen - Founder of devsurvival.com. I am also a video gamer, a full stack developer, and an anime lover. I'm also an advocate of teaching others how to code.
Archive