JavaScript Engines: How Do They Even Work?

JavaScript Engines: How Do They Even Work?

A whirlwind tour of JavaScript engines from Call Stack, Global Memory, Event Loop, Callback Queue to Promises and Async/Await! Enjoy the reading!

A whirlwind tour of JavaScript engines from Call Stack, Global Memory, Event Loop, Callback Queue to Promises and Async/Await! Enjoy the reading!

Let's begin our immersion in the language by introducing the wonderful world of JavaScript engines.

Ever wondered how browsers read and run JavaScript code? It seems magic but you can get an hint of what's happening under the hood. Open up a browser console in Chrome and take a look at the Sources tab. You'll see some boxes, one of the more interesting named Call Stack (in Firefox you can see the Call Stack after inserting a breakpoint into the code):

What's a Call Stack? Looks like there is a lot of stuff going on, even for running a couple line of code. JavaScript in fact does not come out of the box with every web browser.

There is a big component which compiles and interprets our JavaScript code: it's the JavaScript engine. The most popular JavaScript engines are V8, used by Google Chrome and Node.js, SpiderMonkey for Firefox, and JavaScriptCore, used by Safari/WebKit.

JavaScript engines today are brilliant pieces of engineering and it would be impossible to cover every single facet of them. But there are some smaller pieces in every engine doing the hard work for us.

One of these component is the Call Stack and alongside together with Global Memory and Execution Context make possible to run our code. Ready to meet them?

JavaScript engines and Global Memory

I said that JavaScript is both a compiled and an interpreted language at the same time. Believe it or not JavaScript engines actually compile your code mere microseconds before executing it. That sounds magic right? The magic is called JIT (Just in time compilation). It's a big topic on its own, another book would not be enough to describe how JIT works. But for now we can just skip the theory behind compilation and focus on the execution phase, which is nonetheless interesting.

To start off consider the following code:

var num = 2;

function pow(num) {
    return num * num;
}

If I were to ask you how does the above code is processed in the browser? What will you say? You might say "the browser reads the code" or "the browser executes the code". The reality is more nuanced than that. First, it's not the browser that reads that snippet of code. It's the engine. A JavaScript engine reads the code and as soon as it encounters the first line it puts a couple of references into the Global Memory.

The Global Memory (also called Heap) is an area where the JavaScript engine saves variables and function declarations. Pay attention, the difference might sound trivial but function declarations in JavaScript are not the same as function invocations. A function declaration is just a description of what the function should accept and how it's going to be invoked. A function invocation on the other hand is the actual execution of a previously declared function.

So, back to our example, when the engine reads the above code the Global Memory is populated with two bindings:

At this point nothing is executed but what if we try to run our function like so:

var num = 2;

function pow(num) {
    return num * num;
}

pow(num);

What will happen? Now things get interesting. When a function is called the JavaScript engine makes room for two more boxes:

  • a Global Execution Context
  • a Call Stack

Let's see what they are in the next section.

Global Execution Context and Call Stack

You learned how the JavaScript engine reads variables and function declarations. They end up in a Global Memory (the Heap). But now we executed a JavaScript function and the engine has to take care of it. How? There is a fundamental component in every JavaScript engine, called Call Stack. The Call Stack is a stack data structure: that means elements can enter from the top but they can't leave if there's some element above them. JavaScript functions are exactly like that. Once executing they can't leave the Call Stack if some other function remains stuck. Pay attention because this concept is helpful for wrapping your head around the sentence "JavaScript is single-threaded". But for now let's get back to our example. When the function is called the engine pushes that function inside the call stack:

I like thinking of the Call Stack as a pile of Pringles. We cannot eat a pringle at the bottom of the pile without first eating all the pringles at the top! Luckily our function is synchronous: it's a simple multiplication and it's calculated quickly. At the very same time the engine allocates also a Global Execution Context, which is the global environment where our JavaScript code runs. Here's how it looks like:

Imagine the Global Execution Context as a sea where JavaScript global functions swim like fishes. How nice! But that's just the half of the story. What if our function has some nested variables or one or more inner functions? Even in a simple variation like the following, the JavaScript engine creates a Local Execution Context:

var num = 2;

function pow(num) {
    var fixed = 89;
    return num * num;
}

pow(num);

Notice that I added a variable named fixed inside the function pow. In that case the Local Execution Context will contain a box for holding fixed. I'm not so good at illustration and you have to use your imagination for now. The Local Execution Context will appear near pow, inside the greener box contained in the Global Execution Context. You can also imagine that for every nested function of a nested function the engine creates more Local Execution Contexts. These boxes can go to far so quickly! Like a matrioska! Now how about getting back to that single-threaded story? What does it means?

JavaScript is single-threaded and other funny stories

We say that JavaScript is single-threaded because there is a single Call Stack handling our functions. That is, functions can't leave the Call Stack if there are other functions waiting for execution.

That's not a problem when dealing with synchronous code. For example, a sum between two numbers is synchronous and runs in microseconds. But how about network calls and other interactions with the outside world? Luckily JavaScript engines are designed to be asynchronous by default. Even if they can execute one function at a time there is a way for slower function to be executed by an external entity: the browser in our case. We'll explore this topic later.

In the meantime you learned that when a browser loads some JavaScript code an engine reads line by line and performs the following steps:

  • populates the Global Memory (Heap) with variables and function declarations
  • pushes every function invocation into a Call Stack
  • creates a Global Execution Context in which global functions are executed
  • creates lot of tiny Local Execution Contexts (if there are inner variables or nested functions)

You should have by now a big picture of the synchronous mechanic at the base of every JavaScript engine. In the next sections you'll see how asynchronous code works in JavaScript and why it works that way.

Asynchronous JavaScript, Callback Queue and the Event Loop

Global Memory, Execution Context and Call Stack explain how synchronous JavaScript code runs in our browser. Yet we're missing something. What happens when there is some asynchronous function to run? By asynchronous function I mean every interaction with the outside world that could take some time to complete. Calling a REST API or invoking a timer are asynchronous because they can take seconds to run. With the elements we have so far in the engine there is no way to handle that kind of functions without blocking the Call Stack, and so the browser.

Remember, the Call Stack can execute one function at a time and even one blocking function can literally freeze the browser. Luckily JavaScript engines are smart and with a bit of help from the browser can sort things out. When we run an asynchronous function the browser takes that function and runs it for us. Consider a timer like the following:

setTimeout(callback, 10000);

function callback(){
    console.log('hello timer!');
}

I'm sure you saw setTimeout an hundred of times yet you might not know that it's not a built-in JavaScript function. That is, when JavaScript was born there were no setTimeout built into the language. setTimeout in fact is part of the so called Browser APIs, a collection of handy tool that the browser gives us for free. How kind! What does it mean in practice? Since setTimeout is a Browser APIs that function is run straight by the browser (it appears for a moment into the Call Stack but is removed instantly). Then after 10 seconds the browsers takes the callback function we passed in and moves it into a Callback Queue. At this point we have two more boxes inside our JavaScript engine. If you consider the following code:

var num = 2;

function pow(num) {
    return num * num;
}

pow(num);

setTimeout(callback, 10000);

function callback(){
    console.log('hello timer!');
}

We can complete our illustration like so:

As you can see setTimeout runs inside the browser context. After 10 seconds the timer is triggered and the callback function is ready to run. But first it has to go through the Callback Queue. The Callback Queue is a queue data structure and as its name suggest is an ordered queue of functions. Every asynchronous function must pass through the Callback Queue before is pushed into the Call Stack. But who pushes that function forward? There is another component named Event Loop.

The Event Loop has just one job for now: it should check whether the Call Stack is empty. If there is some function into the Callback Queue and if the Call Stack is free, then it's time to push the callback into the Call Stack. Once done the function is executed. This is the big picture of a JavaScript engine for handling asynchronous and synchronous code:

Imagine that callback() is ready to be executed. When pow() finishes the Call Stack is empty and the Event Loop pushes callback() in. That's it! Even if I'm simplifying things a bit, if you understand the illustration above then your ready to understand all the JavaScript.

Remember: Browser APIs, Callback Queue, and Event Loop are the pillars of asynchronous JavaScript. Hold on though because we're not done with asynchronous JavaScript. In the next sections we'll take a closer look at ES6 Promises.

Callback hell and ES6 Promises

Callback functions are everywhere in JavaScript. They are used both for synchronous and asynchronous code. Consider the map method for example:

function mapper(element){
    return element * 2;
}

[1, 2, 3, 4, 5].map(mapper);

mapper is a callback function passed inside map. The above code is synchronous. But consider instead an interval:

function runMeEvery(){
    console.log('Ran!');
}

setInterval(runMeEvery, 5000);

That code is asynchronous, yet as you can see we pass the callback runMeEvery inside setInterval. Callbacks are pervasive in JavaScript so that during the years a problem emerged: callback hell. Callback hell in JavaScript refers to a "style" of programming where callbacks are nested inside callbacks which are nested ... inside other callbacks. Due to the asynchronous nature of JavaScript programmers fell into this trap over the years. To be honest I never run into extreme callback pyramids, maybe because I value readable code and I always try sticking to that principle. If you end up in a callback hell it's a sign that your function is doing too much.

I won't cover callback hell here, if you're curious there is a website, callbackhell.com which explores the problem in more detail and offers some solutions. What we want to focus on now are ES6 Promises. ES6 Promises are an addition to the JavaScript language aiming to solve the dreaded callback hell. But what is a Promise anyway?

A JavaScript Promise is the representation of an future event. A Promise can end with success: in jargon we say it's resolved (fulfilled). But if the Promise errors out we say it's in a rejected state. Promises have also a default state: every new Promise starts in pending state. It is possible to create your own Promise? Yes. Let's see how into the next section.

Creating and working with JavaScript Promises

For creating a new Promise you call the Promise constructor by passing a callback function into it. The callback function can take two parameters: resolve and reject. Let's create a new Promise which will resolve in 5 seconds (you can try the examples in a browser's console):

const myPromise = new Promise(function(resolve){
    setTimeout(function(){
        resolve()
    }, 5000)
});

As you can see resolve is a function that we call for making the Promise succeed. Reject on the other hand makes a rejected Promise:

const myPromise = new Promise(function(resolve, reject){
    setTimeout(function(){
        reject()
    }, 5000)
});

Note that in the first example you can omit reject because it's the second parameter. But if you intend to use reject you can't omit resolve. In other words the following code won't work and will end up in a resolved Promise:

// Can't omit resolve !

const myPromise = new Promise(function(reject){
    setTimeout(function(){
        reject()
    }, 5000)
});

Now, Promises don't look so useful isn't it? Those example print nothing to the user. Let's add some data to the mix. Both resolved and rejected Promises can return data. Here's an example:

const myPromise = new Promise(function(resolve) {
  resolve([{ name: "Chris" }]);
});

But still we can't see any data. For extracting data from a Promise you need to chain a method called then. It takes a callback (the irony!) which receives the actual data:

const myPromise = new Promise(function(resolve, reject) {
  resolve([{ name: "Chris" }]);
});

myPromise.then(function(data) {
    console.log(data);
});

As a JavaScript developer and consumer of other's people code you will mostly interact with Promises from the outside. Library creators instead are more likely to wrap legacy code inside a Promise constructor like so:

const shinyNewUtil = new Promise(function(resolve, reject) {
  // do stuff and resolve
  // or reject
});

And when in need we can also create and resolve a Promise in place by calling Promise.resolve():

Promise.resolve({ msg: 'Resolve!'})
.then(msg => console.log(msg));

So to recap a JavaScript Promise is a bookmark for an event happening in the future. The event starts in a pending state and can either succeed (resolved, fulfilled) or fail (rejected). A Promise can return data and that data can be extracted by attaching then to the Promise. In the next section we'll see how to deal with errors coming from a Promise.

Error handling in ES6 Promises

Error handling in JavaScript has been always straightforward, at least for synchronous code. Consider the following example:

function makeAnError() {
  throw Error("Sorry mate!");
}

try {
  makeAnError();
} catch (error) {
  console.log("Catching the error! " + error);
}

The output will be:

Catching the error! Error: Sorry mate!

The error got in the catch block as expected. Now let's try with an asynchronous function:

function makeAnError() {
  throw Error("Sorry mate!");
}

try {
  setTimeout(makeAnError, 5000);
} catch (error) {
  console.log("Catching the error! " + error);
}

The above code is asynchronous because of setTimeout. What happens if we run it?

  throw Error("Sorry mate!");
  ^

Error: Sorry mate!
    at Timeout.makeAnError [as _onTimeout] (/home/valentino/Code/piccolo-javascript/async.js:2:9)

This time the output is different. The error didn't go through the catch block. It was free to propagate up in the stack. That's because try/catch only works with synchronous code. Luckily with Promises there is a way to handle asynchronous errors like they were synchronous. If you recall from the previous section a call to reject is what makes a rejected Promise:

const myPromise = new Promise(function(resolve, reject) {
  reject('Errored, sorry!');
});

In the above case we can handle the error with the catch handler, taking (again) a callback:

const myPromise = new Promise(function(resolve, reject) {
  reject('Errored, sorry!');
});

myPromise.catch(err => console.log(err));

And we can also call Promise.reject() for creating and rejecting a Promise in place:

Promise.reject({msg: 'Rejected!'}).catch(err => console.log(err));

To recap: the then handler runs when a Promise is fullfilled while the catch handler runs for rejected Promises. But that's no the end of the story. Later we will see how async/await works nicely with try/catch.

ES6 Promises combinators: Promise.all, Promise.allSettled, Promise.any, and friends

Promises are not meant to go alone. The Promise API offers a bunch of methods for combining Promises together. One of the most useful is Promise.all which takes an array of Promises and returns a single resolved Promise. The problem is that Promise.all rejects if any Promise in the array is rejected.

Promise.race resolves or reject as soon as one of the Promise in the array is settled. It still rejects if one of the Promise rejects.

Newer versions of V8 are also going to implement two new combinators: Promise.allSettled and Promise.any. Promise.any is still in the early stages of the proposal: at the time of this writing there is still no support for it. But the theory is that Promise.any can signal whether any of the Promise is fullfilled. The difference from Promise.race is that Promise.any does not rejects even if one of the Promise is rejected.

Anyway the most interesting of the two is Promise.allSettled. It still takes an array of Promises but it does not short-circuit if one of the Promise rejects. It is useful for when you want to check if an array of Promises is all settled, regardless of an eventual rejection. Think of it as a countepart of Promise.all.

ES6 Promises and Microtask Queue

If you remember from previous sections every asynchronous callback function in JavaScript ends up in a Callback Queue before being pushed into the Call Stack. But callbacks function passed in a Promise have a different fate: they are handled by the Microtask Queue, not by the Callback Queue.

And there's an interesting quirk you should be aware of: Microtask Queue has precedence over the Callback Queue. Callbacks from the Microtask Queue have priority when the Event Loop checks if there is any new callback ready to be pushed into the Call Stack.

The mechanics is exposed in more detail by Jake Archibald in Tasks, microtasks, queues and schedules, it's a fantastic read.

Asynchronous evolution: from Promises to async/await

JavaScript is moving fast and every year we get constant improvements to the language. Promises seemed the arrival point but with ECMAScript 2017 (ES8) a new syntax was born: async/await. async/await is just a stylistic improvement, what we call syntactic sugar. async/await does not alter JavaScript by any means (remember, JavaScript must be backward compatible with older browser and should not break existing code). It is just a new way for writing asynchronous code based on Promises. Let's make an example. Earlier we save a Promise with the corresponding then:

const myPromise = new Promise(function(resolve, reject) {
  resolve([{ name: "Chris" }]);
});

myPromise.then((data) => console.log(data))

Now with async/await we can handle asynchronous code in a way that looks synchronous from the reader's point of view. Instead of using then we can wrap the Promise inside a function marked async and then await on the result:

const myPromise = new Promise(function(resolve, reject) {
  resolve([{ name: "Chris" }]);
});

async function getData() {
  const data = await myPromise;
  console.log(data);
}

getData();

Makes sense right? Now, the funny thing is that an async function will always return a Promise and nobody prevents you from doing that:

async function getData() {
  const data = await myPromise;
  return data;
}

getData().then(data => console.log(data));

And how about errors? One of the boon offered by async/await is the chance to use try/catch. Let's look again at a Promise where for handling errors we use the catch handler:

const myPromise = new Promise(function(resolve, reject) {
  reject('Errored, sorry!');
});

myPromise.catch(err => console.log(err));

With async functions we can refactor to the following code:

async function getData() {
  try {
    const data = await myPromise;
    console.log(data);
    // or return the data with return data
  } catch (error) {
    console.log(error);
  }
}

getData();

Not everybody is still sold to this style though. try/catch can make your code noisy. And while using try/catch there is another quirk to point out. Consider the following code, raising an error inside the try block:

async function getData() {
  try {
    if (true) {
      throw Error("Catch me if you can");
    }
  } catch (err) {
    console.log(err.message);
  }
}

getData()
  .then(() => console.log("I will run no matter what!"))
  .catch(() => console.log("Catching err"));

What of the two strings is printed to the console? Remember that try/catchis a synchronous construct but our asynchronous function produces a Promise. They travel on two different tracks, like two trains. But they will never meet! That is, an error raised by throw will never trigger the catchhandler of getData(). Running the above code will result in "Catch me if you can" followed by "I will run no matter what!". In the real world we don't want throw to trigger a then handler. One possible solution is returning Promise.reject() from the function:

async function getData() {
  try {
    if (true) {
      return Promise.reject("Catch me if you can");
    }
  } catch (err) {
    console.log(err.message);
  }
}

Now the error will be handled as expected:

getData()
  .then(() => console.log("I will NOT run no matter what!"))
  .catch(() => console.log("Catching err"));

"Catching err" // output

Besides that async/await seems the best way for structuring asynchronous code in JavaScript. We have better control over error handling and the code looks more cleaner. Anyway, I don't advise refactoring all your JavaScript code to async/await. These are choices that must be discussed with the team. But if you work alone whether you use plain Promises or async/await it's a matter of personal preference.

Wrapping up

JavaScript is a scripting language for the web and has the peculiarity of being compiled first and then interpreted by an engine. Among the most popular JavaScript engines there are V8, used by Google Chrome and Node.js, SpiderMonkey, built for the web browser Firefox, and JavaScriptCore, used by Safari.

JavaScript engines have a lot of moving parts: Call Stack, Global Memory, Event Loop, Callback Queue. All these parts work together in perfect tuning for handling synchronous and asynchronous code in JavaScript. JavaScript engines are single-threaded, that means there is a single Call Stack for running functions. This restriction is at the basis of JavaScript's asynchronous nature: all the operations that require time must be taken in charge by an external entity (the browser for example) or by a callback function.

For simplifying asynchronous code flow ECMAScript 2015 brought us Promises. A Promise is an asynchronous object and is used to represent either the failure or the success of any asynchronous operation. But the improvements did not stop there. In 2017 async/await was born: it's a stylistic make up for Promises that makes possible to write asynchronous code as if it was synchronous.

What is JavaScript – All You Need To Know About JavaScript

What is JavaScript – All You Need To Know About JavaScript

In this article on what is JavaScript, we will learn the basic concepts of JavaScript.

After decades of improvement, JavaScript has become one of the most popular programming languages of all time. It all started in the year 1995 when Brendan Eich created JavaScript in a span of 10 days. Since then, it has seen multiple versions, updates and has grown to the next level.

Here’s a list of topics that I’ll be covering in this blog:

  1. What is JavaScript
  2. What can JavaScript do?
  3. JavaScript Frameworks
  4. The Big Picture: HTML, CSS & JavaScript
  5. Benefits of JavaScript
  6. Fundamentals of JavaScript
    VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case
What is JavaScript?

JavaScript is a high level, interpreted, programming language used to make web pages more interactive.

Have you ever thought that your website is missing something? Maybe it’s not engaging enough or it’s not as creative as you want it to be. JavaScript is that missing piece which can be used to enhance web pages, applications, etc to provide a more user-friendly experience.

What is JavaScript?

JavaScript is the language of the web, it is used to make the web look alive by adding motion to it. To be more precise, it’s a programming language that let’s you implement complex and beautiful things/design on web pages. When you notice a web page doing more than just sit there and gawk at you, you can bet that the web page is using JavaScript.

Feature of JavaScript

Scripting language and not Java: In fact, JavaScript has nothing to do with Java. Then why is it called “Java” Script? When JavaScript was first released it was called Mocha, it was later renamed to LiveScript and then to JavaScript when Netscape (founded JavaScript) and Sun did a license agreement. Object-based scripting language which supports polymorphism, encapsulation and to some extent inheritance as well.**Interpreted language: **It doesn’t have to be compiled like Java and C which require a compiler.JavaScript runs in a browser: You can run it on Google Chrome, Internet Explorer, Safari, etc. JavaScript can execute not only in the browser but also on the server and any device which has a JavaScript Engine.

What is JavaScript – Stackoverflow stats

Currently, we have 100s of programming languages and every day new languages are being created. Among these are few powerful languages that bring about big changes in the market and JavaScript is one of them.

JavaScript has always been on the list of popular programming languages. According to StackOverflow, for the 6th year in a row, JavaScript has remained the most popular and commonly used programming language.

What can JavaScript do?

JavaScript is mainly known for creating beautiful web pages & applications. An example of this is Google Maps. If you want to explore a specific map, all you have to do is click and drag with the mouse. And what sort of language could do that? You guessed it! It’s JavaScript.JavaScript can also be used in smart watches. An example of this is the popular smartwatch maker called Pebble. Pebble has created Pebble.js which is a small JavaScript Framework that allows a developer to create an application for the Pebble line of watches in JavaScript.

What is JavaScript – Applications of JavaScript
Most popular websites like Google, Facebook, Netflix, Amazon, etc make use of JavaScript to build their websites.Among things like mobile applications, digital art, web servers and server applications, JavaScript is also used to make Games. A lot of developers are building small-scale games and apps using JavaScript.## JavaScript Frameworks

One major reason for the popularity of JavaScript is the JavaScript Frameworks. Here’s a brief introduction of the most trending JavaScript frameworks :

  1. AngularJS is Google’s web development framework which provides a set of modern development and design features for rapid application development.

  2. ReactJS is another top JavaScript framework mainly maintained by Facebook and it’s behind the User Interface of Facebook and Instagram, showing off its efficiency in maintaining such high traffic applications.

What is JavaScript – JavaScript Frameworks

  1. MeteorJS is mainly used for providing back-end development. Using JavaScript on the back-end to save time and build expertise is one of the major ideas behind Meteor.

  2. jQuery can be used when you want to extend your website and make it more interactive. Companies like Google, WordPress and IBM rely on jQuery.

The Big Picture: HTML, CSS & JavaScript

Anyone familiar with JavaScript knows that it has something to do with HTML and CSS. But what is the relationship between these three? Let me explain this with an analogy.

What is JavaScript – HTML, CSS and JavaScript

Think of HTML (HyperText Markup Language) as the skeleton of the web. It is used for displaying the web.

On the other hand, CSS is like our clothes. We put on fashionable clothes to look better. Similarly, the web is quite stylish as well. It uses CSS which stands for Cascading Style Sheets for styling purpose.

Then there is JavaScript which puts life into a web page. Just like how kids move around using the skateboard, the web also motions with the help of JavaScript.

Benefits of JavaScript

There has to be a reason why so many developers love working on JavaScript. Well, there are several benefits of using JavaScript for developing web applications, here’s a few benefits:

It’s easy to learn and simple to implement. It is a weak-type programming language unlike the strong-type programming languages like Java and C++, which have strict rules for coding.

It’s all about being fast in today’s world and since JavaScript is mainly a client-side programming language, it is very fast because any code can run immediately instead of having to contact the server and wait for an answer.

Rich set of frameworks like AngularJS, ReactJS are used to build web applications and perform different tasks.

**Builds interactive websites: **We all get attracted to beautifully designed websites and JavaScript is the reason behind such attractive websites and applications.

JavaScript is an interpreted language that does not require a compiler because the web interprets JavaScript. All you need is a browser like Google Chrome or Internet Explorer and you can do all sorts of stuff in the browser.

JavaScript is platform independent and it is supported by all major browsers like Internet Explorer, Google Chrome, Mozilla Firefox, Safari, etc.

JavaScript Fundamentals

In this What is JavaScript blog, we’ll cover the following basic fundamentals of JavaScript
VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case## Variables

Variable is a name given to a memory location which acts as a container for storing data temporarily. They are nothing but reserved memory locations to store values.

What is JavaScript – Variables

To declare a variable in JavaScript use the ‘let’ keyword. For example:

let age;
age=22;

In the above example, I’ve declared a variable ‘age’ by using the ‘let’ keyword and then I’ve stored a value (22) in it. So here a memory location is assigned to the ‘age’ variable and it contains a value i.e. ’22’.

Constants

Constants are fixed values that don’t change during execution time.

To declare a constant in JavaScript use the ‘const’ keyword. For example:

const mybirthday;
mybirthday='3rd August'; 

Data types

You can assign different types of values to a variable such as a number or a string. In JavaScript, there are two categories of data types :

What is JavaScript – Data Types

Objects

An object is a standalone entity with properties and types and it is a lot like an object in real life. For example, consider a girl, whose name is Emily, age is 22 and eye-color is brown. In this example the object is the girl and her name, age and eye-color are her properties.

What is JavaScript – Objects example

Objects are variables too, but they contain many values, so instead of declaring different variables for each property, you can declare an object which stores all these properties.

To declare an object in JavaScript use the ‘let’ keyword and make sure to use curly brackets in such a way that all property-value pairs are defined within the curly brackets. For example:

let girl= {
name: 'Emily',
age: 22,
eyeColour: 'Brown'
};

In the above example, I’ve declared an object called ‘girl’ and it has 3 properties (name, age, eye colour) with values (Emily, 22, Brown).

Arrays

An array is a data structure that contains a list of elements which store multiple values in a single variable.

For example, let’s consider a scenario where you went shopping to buy art supplies. The list of items you bought can be put into an array.

What is JavaScript – Arrays example

To declare an array in JavaScript use the ‘let’ keyword with square brackets and all the array elements must be enclosed within them. For example:

let shopping=[];
shopping=['paintBrush','sprayPaint','waterColours','canvas'];

In the above example I’ve declared an array called ‘shopping’ and I’ve added four elements in it.

Also, array elements are numbered from zero. For example this is how you access the first array element:

shopping[0];		

Functions

A function is a block of organised, reusable code that is used to perform single, related action.

Let’s create a function that calculates the product of two numbers.

To declare a function in JavaScript use the ‘function’ keyword. For example:

function product(a, b) {
return a*b;
}

In the above example, I’ve declared a function called ‘product’ and I’ve passed 2 parameters to this function, ‘a’ and ‘b’ which are variables whose product is returned by this function. Now, in order to call a function and pass a value to these parameters you’ll have to follow the below syntax:

product(8,2);

In the above code snippet I’m calling the product function with a set of values (8 & 2). These are values of the variables ‘a’ and ‘b’ and they’re called as arguments to the function.

Conditional statements – if

Conditional statement is a set of rules performed if a certain condition is met. The ‘if’ statement is used to execute a block of code, only if the condition specified holds true.

What is JavaScript – if flowchart

To declare an if statement in JavaScript use the ‘if’ keyword. The syntax is:

if(condition) {
statement;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[2]) {
console.log('Correct!');
}

In the above example I’ve defined an array of numbers and then I’ve defined an if block. Within this block is a condition and a statement. The condition is ‘(numbers[0]==numbers[2])’ and the statement is ‘console.log(‘Correct!’)’. If the condition is met, only then the statement will be executed.

Conditional statements- Else if

Else statement is used to execute a block of code if the same condition is false.

What is JavaScript – Else-if flowchart

The syntax is:

if(condition) {
statement a;
}
else (condition) {
statement b;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[4] {
console.log("Correct!");
}
else {
console.log("Wrong, please try again");
}

In the above example, I’ve defined an if block as well as an else block. So if the conditions within the if block holds false then the else block gets executed. Try this for yourself and see what you get!

**Loops **

Loops are used to repeat a specific block until some end condition is met. There are three categories of loops in JavaScript :

  1. while loop
  2. do while loop
  3. for loop
While loop

While the condition is true, the code within the loop is executed.

What is JavaScript – while loop flowchart

The syntax is:

while(condition) {
loop code;
}

Now let’s look at an example:

let i=0;
while(i < 5) {
console.log("The number is " +i);
i++;
}

In the above example, I’ve defined a while loop wherein I’ve set a condition. As long as the condition holds true, the while loop is executed. Try this for yourself and see what you get!

Do while loop

This loop will first execute the code, then check the condition and while the condition holds true, execute repeatedly.

What is JavaScript – Do while loop flowchart

Refer the syntax to better understand it:

do {
loop code;
} while(condition);

This loop executes the code block once before checking if the condition is true, then it will repeat the loop as long as the condition holds true.

Now let’s look at an example:

do {
console.log("The number is " +i);
i++;
}
while(i > 5);

The above code is similar to the while loop code except, the code block within the do loop is first executed and only then the condition within the while loop is checked. If the condition holds true then the do loop is executed again.

For loop

The for loop repeatedly executes the loop code while a given condition is TRUE. It tests the condition before executing the loop body.

What is JavaScript – for loop flowchart

The syntax is:

for(begin; condition; step) {
loop code;
}

In the above syntax:

  • begin statement is executed one time before the execution of the loop code
  • condition defines the condition for executing the loop code
  • step statement is executed every time after the code block has been executed

For example:

for (i=0;i<5;i++) {
console.log("The number is " +i);
}

In the above example, I’ve defined a for loop within which I’ve defined the begin, condition and step statements. The begin statement is that ‘i=0’. After executing the begin statement the code within the for loop is executed one time. Next, the condition is checked, if ‘i<5’ then, the code within the loop is executed. After this, the last step statement (i++) is executed. Try this and see what you get!

Switch Case

The switch statement is used to perform different actions based on different conditions.

What is JavaScript – Switch case flowchart

Let’s look at the syntax for switch case:

switch(expression) {
case 1:
code block 1
break;
case 2:
code block 2
break;
default:
code block 3
break;
}

How does it work?

  • Switch expression gets evaluated once
  • Value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed

Let’s try this with an example:

let games='football';
switch(games) {
case "throwball":
console.log("I dislike throwball!");
break;
case "football":
console.log("I love football!");
break;
case "cricket":
console.log("I'm a huge cricket fan!");
break;
default:
console.log("I like other games");
break;
}

In the above example the switch expression is ‘games’ and the value of games is ‘football’. The value of ‘games’ is compared with the value of each case. In this example it is compared to ‘throwball’, ‘cricket’ and ‘football’. The value of ‘games’ matches with the case ‘football’, therefore the code within the ‘football’ case is executed. Try this for yourself and see what you get!

With this, we come to the end of this blog. I hope you found this blog informative and I hope you have a basic understanding of JavaScript. In my next blog on JavaScript I’ll be covering in-depth concepts, so stay tuned.

Also, check out our video on JavaScript Fundamentals if you want to get started as soon as possible and don’t forget to leave a comment if you have any doubt and also, let us know whether you’d want us to create more content on JavaScript. We are listening!

Learn JavaScript in 60 Minutes | JavaScript Crash Course | JavaScript Tutorial |

This video on "JavaScript" will help you learn JavaScript basics and fundamental concepts in 60 minutes. This will provide you in-depth knowledge about the JavaScript fundamentals that will help you write your own code in JavaScript and build a website. This JavaScript tutorial covers following topics..

==================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

Svelte.js - The Complete Guide

The Complete JavaScript Course 2019: Build Real Projects!

Advanced CSS and Sass: Flexbox, Grid, Animations and More!

CSS - The Complete Guide (incl. Flexbox, Grid & Sass)

CSS Bootcamp - Master CSS (Including CSS Grid / Flexbox)

Build Responsive Real World Websites with HTML5 and CSS3

Become a JavaScript developer - Learn (React, Node,Angular)

JavaScript: Understanding the Weird Parts

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

The Full JavaScript & ES6 Tutorial - (including ES7 & React)

JavaScript - Step By Step Guide For Beginners

JavaScript | How to use classes in JavaScript

JavaScript | How to use classes in JavaScript

Classes in JavaScript are a special syntax for its prototypical inheritance model that resembles class based inheritance in other object oriented languages. Classes are just special functions that can be declared to resembles classes in other languages. In JavaScript, we can have class declarations and class expressions, because they are just functions. So like all other functions, there are function declarations and function expressions. Classes serve a templates to create new objects.

Defining Classes

To declare a class, or make a class declaration, we use the class keyword to do so. For example, to declare a simple class, we can write:

class Person{
  constructor(firstName, lastName) {
    this.firstName= firstName;
    this.lastName = lastName;
  }
}

Class declarations aren’t hoisted so they can used before they are defined in the code, as the JavaScript interpreter will not automatically pull them up to the top. So the class above won’t work before it’s defined in the code like the following:

const person = new Person('John', 'Smith');
class Person{
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

We will get a ReferenceError if we run the code above.

We can also define a class by a class expression, which is an alternative syntax for defining a class. They can be named or unnamed. We can also assign a class to a variable like we do with functions. If we do that, we can reference the class by its name. For example, we can define:

let Person = class {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

To get the name of the unnamed classes above, we can get the name with the name property, like so:

console.log(Person.name);


We can also undefined a named class like the following:


let Person = class Person2{
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

Then to get the name of the class, we can use the name property again. So we if we write:

console.log(Person.name)


we get Person2 logged.

The class body is defined with curly brackets. We define the class members inside the brackets. The body of the class is executed in strict mode, so everything defined in strict mode applies to the definition of a class, so we can’t define variables with out some keyword before it like var , let or const , and many other rules apply when you define a class. Classes in JavaScript also have a constructor method that lets us set fields when the object is instantiated with a class . Each class can only have one constructor method in it. If there’s more than one, then SyntaxError will be thrown. A constructor have to also call the super method to call the constructor of the super class inside if it the class extends a parent class.

Methods that aren’t declared static constitutes of the prototypical methods of the class. They are called after an object has been created by using the new keyword. For example, the following class have only prototypical methods:


class Person{
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  get fullName(){
    return `${this.firstName} ${this.lastName}`  
  }
  sayHi(){
    return `Hi, ${this.firstName} ${this.lastName}`
  }
}

In the Person class above, fullName and sayHi are prototypical methods. They are called like this:

const person = new Person('Jane', 'Smith');
person.fullName() // 'Jane Smith'

Static methods are methods that can be called without creating an object from the class using the new keyword. For instance, we can have something like the following:


class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  get fullName() {
    return `${this.firstName} ${this.lastName}`
  }
  sayHi() {
    return `Hi, ${this.firstName} ${this.lastName}`
  }
  static personCount() {
    return 3;
  }
}

We can call the personCount function without using the new keyword to create an instance of the class. So if we write:

Person.personCount

We get 3 returned.

The this value inside prototypical methods will be the value of the object. For static methods the value of this has the class that the static method is in as the value.

Getters and Setters

JavaScript classes can have getters and setter functions. Getters, as the name suggests, is a method that lets us get some data from a class. Setters are methods that gives us the ability to set some fields of the class. We denote getter functions with the get keyword and setters with the set keyword. For example, we can write a class that has getters and setters like the following:

class Person {
  constructor(firstName, lastName) {
    this._firstName = firstName;
    this._lastName = lastName;
  }
  get fullName() {
    return `${this.firstName} ${this.lastName}`
  }
  get firstName() {
    return this._firstName
  }
  get lastName() {
    return this._lastName
  }
  sayHi() {
    return `Hi, ${this.firstName} ${this.lastName}`
  }
  set firstName(firstName) {
    this._firstName = firstName;
  }
  set lastName(lastName) {
    this._lastName = lastName;
  }
}

Then when we use the new keyword to construct a Person object, we can use them in the following way:


const person = new Person('Jane', 'Smith');
person.firstName = 'John';
person.lastName = 'Doe';
console.log(person.firstName, person.lastName)

Since we have the getter and setter functions, we can use them to set the data directly to set the data for firstName and lastName of the Person class. In the setter functions, which start with the keyword set , what we assign to them get passed into the parameters and set in the member of the class. In the getter functions, which are denote by get we return the member values so that we can use them.

JavaScript Inheritance

In JavaScript, we can create classes where the properties can be included in the properties of a child class.

So, we can have a high-level class that contains the properties that are common to all the child classes, and the child class can have its own special properties that are not in any other classes.

For example, if we have an Animal class with the common properties and methods, like name and the eat method, then the Bird class can just inherit the common properties in the Animal class. They don’t have to be defined in the Bird class again.

We can write the following to do inheritance in JavaScript:

class Animal {
  constructor(name) {
    this.name = name;
  }
  eat() {
    console.log('eat');
  }
}
class Bird extends Animal {
  constructor(name, numWings) {
    super(name);
    this.numWings = numWings;
  }
}
const bird = new Bird('Joe', 2);
console.log(bird.name)
bird.eat();

In the example above, we have the parent class, Animal, that has the eat method, which all classes that extends from Animal will have, so they don’t have to define eat again.

We have the Bird class which extends the Animal class. Note that in the constructor of the Bird class, we have the super() function call to call the parent’s class constructor to populate the properties of the parent class in addition to the properties of the child class.

Classes cannot extend regular objects, which cannot be constructed with the new keyword. If we want to inherit from a regular object, we have to use the Object.setPrototypeOf function to set a class to inherit from a regular object. For example:

const Animal = {
  eat() {
    console.log(`${this.name} eats`);
  }
};
class Cat{
  constructor(name) {
    this.name = name;
  }
}
class Chicken{
  constructor(name) {
    this.name = name;
  }
}
Object.setPrototypeOf(Cat.prototype, Animal);
Object.setPrototypeOf(Chicken.prototype, Animal);
let cat = new Cat('Bob');
let chicken = new Chicken('Joe');
cat.eat();
chicken.eat();

If we run the example code above, we have see Bob eats and Joe eats logged because we have inherited the eat function from the Animal object.

this Keyword

The this keyword allows us to access the current object’s properties inside an object, unless you’re using arrow functions.

As we can see from the above example, we can get the properties of the instance of the child and the parent class in the object.

Mixins

We can use mixins to do multiple inheritance in JavaScript. Mixins are templates for creating classes. We need mixins to do multiple inheritance because JavaScript classes can only inherit from one super class, so multiple inheritance isn’t possible.

For example, if we have a base class, we can define mixins to incorporate the members from multiple classes into one by composing the mixins by calling one and then pass the returned result into the next one as the argument, an so on, like so:

class Base {
  baseFn() {
    console.log('baseFn called');
  }
}
let classAMixin = Base => class extends Base {
  a() {
    console.log('classAMixin called');
  }
};
let classBMixin = Base => class extends Base {
  b() {
    console.log('classBMixin called');
  }
};
class Bar extends classAMixin(classBMixin(Base)) {}
const bar = new Bar();
bar.baseFn()
bar.a()
bar.b()

In the code above, we have the Base class which we pass into the classBMixin to get the b function into the Base class, then we call the classAMixin by passing in the result of classBMixin(Base) into the argument of the classAMixin to return the a function from classAMixin into the Base class and then return the whole class with all the functions from all the classes incorporated into one.

If we call all the functions above like we did by creating an instance of the Bar object and then call the baseFn , a and b functions, then we get:

baseFn called
classAMixin called
classBMixin called

This means that we have all the functions from the mixins incorporated into the new Bar class.

In JavaScript, classes are just syntactic sugar to make the prototypical inheritance of JavaScript clearer by letting us structure the code in a way that’s more like typical inheritance class based object oriented inheritance pattern. This means that we write classes to and use the new keyword to create objects from the classes, but underneath the syntactic sugar, we are still using prototypical inheritance to extend objects. We can extend classes from objects and we can also use mixins to do multiple inheritance in of JavaScript classes.