2. to 1. How 3. Code

2. to 1. How 3. Code

An opinionated approach to making websites.

Home

2. to 1. How 3. Code

5. Script III

Synchronous vs. Asynchronous

Synchonous code is written in a linear manner where each statement is executed in sequence, one after the other. This JavaScript is synchronous:

console.log('Hello');
console.log('Hello 2');
console.log('Hello 3');

However, many things in the browser take an unknown amount of time: for example, loading resources or accessing information in a web database.

In order that a slow function not pause the entire page indefinitely, JavaScript makes use of asynchronous code extensively.

In this model, functions are called with a "callback" function as a parameter. When the function is done completing an asynchronous task, it will invoke the "callback" function. Meanwhile, other parts of the program can continue running.

setTimeout(function() {
  console.log('Hello 1');
}, 1000); // pause for 1 s or 1000 ms before running the anonymous callback function
console.log('Hello 2');

Callbacks are a fundamental part of JavaScript, but they can be quite counterintuitive to understand at first.

Spend some time reading about them on JavaScript.info: Callbacks

Classes

In many programming languages (categorized as "object-oriented" languages), code can be organized in units called "classes."

A class is a unit of code which combines data (object values) and behavior (functions) in a way which makes it easy to create many versions or instances of the code.

You can think of a class as a way of grouping or organizing code as well as a way of abstracting complexity behind a simpler interface.

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  area () {
    return this.height * this.width;
  }
}

This class declares a rectangle object. The constructor is invoked to set up the object. The this keyword will refer to the instance of the class itself.

We can use the class as follows:

const square = new Rectangle(10, 10);
console.log(square.area()); // 100

Read more about classes on MDN or in more depth on JavaScript.info.

Object-oriented programming is an entire field of computer science. This is a brief introduce to a topic which has a lot of depth. Continue reading about the topic as you run into issues organizing your code.