In this article, we will talk about the different topics that will lead us to understand better what thenew keyword does in JS.

  1. What is the __proto__ property and its role when it comes to objects and the prototypal chaining
  2. What’s the difference between prototype and __proto__
  3. Where in our code do we take advantage of __proto__ and prototype and the prototypal chain
  4. With all the previous knowledge, we will be able to understand the new keyword and how do the different pieces relate to it

The tweet which you can see below is asking whether all Objects have the prototype property [by default]. It sparked a lot of discussions, different answers, and people wondering if what they think is correct or not.

Let me try and answer it in the best way I can. Let’s start with some related topics that will help us to clear the confusion around __proto__[[Prototype]], and prototype . That will lead us to understand what the new keyword does in JavaScript under the hood.

JavaScript is a prototypal language

One of the cool things about JavaScript is that you can write an application using different programming paradigms such as functional programming and object oriented programming (OOP). The difference between OOP languages such as Java, C#, C++, and the rest of the gang, is that JavaScripts OOP is just syntactical sugar. Under the hood, it makes use of the prototypal chain to allow us as developers to write our application in an OOP style.

Bundling up functions and objects together

Suppose the application we want to create is an e-commerce application. One of the entities that exist in the application is a customer. As a customer, I can add an item to my cart, remove an item, and also checkout/purchase the items that I hold.

Of course, you will have more than one customer registered in your application, and you want all of them to share these functionalities, the ones that we have just defined. Also in the future when our application grows we start having more use cases that we need to add to our customer functionalities.

What’s one way to bundle up multiple functions in one place in JS and save it to be used later again and again? You guessed it, in an Object!

Function are first class citizens in JavaScript

Because functions in JavaScript are first class citizens (objects), it allows us to store functions in a variable, and even in objects as a properties.

In JavaScript, a function is both a function and an object. As soon as you declare a function in JavaScript it gets an object attached to it directly. You can call it a “function-object combo”. If we use the parentheses myFunc() we are going to access the function form, and if you use the dot notation myFunc.something we will access its object form.

#tips #beginner #javascript #es6 #programming

What Does the `New` Keyword Do “Under the Hood” in Javascript?
2.70 GEEK