295 Advanced JavaScript [2.5d]

Updated . Posted . Visible to the public.

Stepping forward from JavaScript Basics, the goal of this card is for you to be able to read and write more complex ES6+ code.

The JavaScript Object Model

ES6 ("ES Next")

Equality

Closures

Have a look at the following examples. Each code snippet is trying to "save away" a local variable i or k in a callback function which can write it to console.log. Understand why each code block behaves the way it does:

Variant 1: Iterating with forEach's callback function

const callbacks = [];

[1, 2, 3].forEach(function(i) {
  callbacks.push(function() { console.log(i) })
})

callbacks.forEach((callback) => callback())

Example 2: Incrementing a variable created with var

const callbacks = [];

var i = 1;
while (i <= 3) {
  callbacks.push(function() { console.log(i) })
  i++
}

callbacks.forEach((callback) => callback())

Variant 3: Wrapping the push statement with an IIFE

const callbacks = [];

var i = 1;
while (i <= 3) {
  (function(k) {
    callbacks.push(function() { console.log(k) })
  })(i)
  i++
}

callbacks.forEach((callback) => callback())

Variant 4: Declaring a temporary variable with let

const callbacks = [];

var i = 1;
while (i <= 3) {
  let k = i
  callbacks.push(function() { console.log(k) })
  i++
}

callbacks.forEach((callback) => callback())

Exercises

Note

Now that you've learned about const and let, you shouldn't use var anymore in any future code you commit.

Note

Important: For the following exercises, don't simply use a library or Stackoverflow code for this. You can look at other people's code to see how it works, but you must understand the concepts and be able to implement them on your own.

  • Read You should probably load your JavaScript with script defer, then apply it to your MovieDB
  • Write a simple class in ES6
    • Class Rectangle with properties width and height. It offers an area method that returns the product of width and height.
  • Write an average function that takes an arbitrary number of arguments ("rest parameters") and computes their arithmetic mean.
  • Read JavaScript: Testing the type of a value. Then, write only one isEqual() method that compares whether two objects of the following types are equal:
    • string literals
    • number literals
    • undefined
    • null
    • Array, recursively compared by their elements. Their contents must have the same order.
    • Simple objects, recursively compared by their own properties.
    • Nested structures built from objects, arrays and primitive variables.
Henning Koch
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra Curriculum (2015-08-03 17:11)