Javascript: A single-threaded, non-blocking, synchronous, concurrent language (Part 1)

Javascript: A single-threaded, non-blocking, synchronous, concurrent language (Part 1)

As the title suggests, javascript is not so simple. Although, learning it is quite simple, understanding the fundamentals... not so much.

So in this series of posts, this being the first one, I'll be covering the core concepts that one must understand to know how javascript works under the hood.

Synchronous and Asynchronous

Synchronous:

Each statement is executed in sequence. So if there are 10 lines of code, each line will wait for the previous one to finish.

function doSomething() {
  console.log('First');
  axios.get('https://foo.com');
  console.log('Second');
  console.log('Third');
}

In the above example, the execution of program will get blocked after first line. The second console.log will have to wait for the API call to finish.

Asynchronous:

Opposite of Synchronous. The execution of the program is taken outside the box allowing the statements to not wait and get called immediately.

function doSomething() {
  console.log('First');
  axios.get('https://foo.com', function (err, data) {
    console.log('Second');
  })
  console.log('Third');
}

In the example above, the output will be: “First”, “Third”, “Second”. In this case, the program execution does not wait after first console.log.

Single Threaded vs Multi Threaded

A thread is just a small process which has it own call stack, its own program counter, its own set of registers and stuff.

Single Threaded

Single Threaded means it has one call stack, one memory heap, one program counter and one sequence of instructions that can be executed at a possible time.

Take for example, a web server which runs a single threaded application that handles user requests. Here other users have to wait for the server to finish executing the request of the user 1.

Multi Threaded

Multi Threaded means each thread has its own program counter, its own call stack and its own memory heap but they all share the common code, data and other certain things such as file system.

Today, almost all operating systems are multi-threaded. For example in a word processor, a background thread may check spelling and grammar while a foreground thread processes user input, while yet a third thread loads images from the hard drive, and a fourth does periodic automatic backups of the file being edited.

image.png