<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Shirshendu Bhowmick - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Shirshendu Bhowmick - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 30 May 2026 19:49:22 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/shirshendu/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ All you need to know to understand JavaScript’s Prototype ]]>
                </title>
                <description>
                    <![CDATA[ Most of the time, JavaScript’s prototype confuses people who have just started to learn JavaScript — especially if they’re from a C++ or Java background. In JavaScript, inheritance works a bit differently compared to C++ or Java. JavaScript inheritan... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/all-you-need-to-know-to-understand-javascripts-prototype-a2bff2d28f03/</link>
                <guid isPermaLink="false">66bce172b4d21e8b1de0ebb6</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Shirshendu Bhowmick ]]>
                </dc:creator>
                <pubDate>Wed, 03 Apr 2019 22:16:46 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*bgfErxHxXBw-Ccm4OMu7_w.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Most of the time, JavaScript’s prototype confuses people who have just started to learn JavaScript — especially if they’re from a C++ or Java background.</p>
<p>In JavaScript, inheritance works a bit differently compared to C++ or Java. JavaScript inheritance is more widely known as “prototypical inheritance”.</p>
<p>Things become more difficult to understand when you also encounter <code>class</code> in JavaScript. The new <code>class</code> syntax looks similar to C++ or Java, but in reality, it works differently.</p>
<p>In this article, we will try to understand “prototypal inheritance” in JavaScript. We also look into the new <code>class</code> based syntax and try to understand what it actually is. So let’s get started.</p>
<p>First, we will start with the old school JavaScript function and prototype.</p>
<h4 id="heading-understanding-the-need-for-prototype">Understanding the need for prototype</h4>
<p>If you have ever worked with JavaScript arrays or objects or strings, you have noticed that there are a couple of methods that are available by default.</p>
<p>For example:</p>
<pre><code><span class="hljs-keyword">var</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>];arr.reverse(); <span class="hljs-comment">// returns [4,3,2,1]</span>
</code></pre><pre><code><span class="hljs-keyword">var</span> obj = {<span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">value</span>: <span class="hljs-string">"Some value"</span>};obj.hasOwnProperty(<span class="hljs-string">'id'</span>); <span class="hljs-comment">// returns true</span>
</code></pre><pre><code><span class="hljs-keyword">var</span> str = <span class="hljs-string">"Hello World"</span>;str.indexOf(<span class="hljs-string">'W'</span>); <span class="hljs-comment">// returns 6</span>
</code></pre><p>Have you ever wondered where these methods come from? You haven’t defined these methods on your own.</p>
<p>Can you define your own methods like this? You could say that you can in this way:</p>
<pre><code><span class="hljs-keyword">var</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>];arr.test = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hi'</span>;}arr.test(); <span class="hljs-comment">// will return 'Hi'</span>
</code></pre><p>This will work, but only for this variable called <code>arr</code>. Let’s say we have another variable called <code>arr2</code> then <code>arr2.test()</code> will throw an error “TypeError: arr2.test is not a function”.</p>
<p>So how do those methods become available to each and every instance of array / string / object? Can you create your own methods with the same behavior? The answer is yes. You need to do it in the right way. To help with this, in comes JavaScript’s prototype.</p>
<p>Let’s first see where these functions are coming from. Consider the code snippet below:</p>
<pre><code><span class="hljs-keyword">var</span> arr1 = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>];<span class="hljs-keyword">var</span> arr2 = <span class="hljs-built_in">Array</span>(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>);
</code></pre><p>We have created two arrays in two different ways: <code>arr1</code> with array literals and <code>arr2</code> with <code>Array</code> constructor function. Both are equivalent to each other with some differences that don’t matter for this article.</p>
<p>Now coming to the constructor function <code>Array</code> — it is a predefined constructor function in JavaScript. If you open Chrome Developer tools and go to the console and type <code>console.log(Array.prototype)</code> and hit <code>enter</code> you will see something like below:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/LgPwy0jWfYBMdxUPmjdTAtDVZmyBkYFE-x8s" alt="Image" width="800" height="603" loading="lazy">
<em>Fig: 1</em></p>
<p>There you will see all the methods that we were wondering about. So now we get from where those functions are coming. Feel free to try with <code>String.prototype</code> and <code>Object.prototype</code>.</p>
<p>Let’s create our own simple constructor function:</p>
<pre><code><span class="hljs-keyword">var</span> foo = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name</span>) </span>{ <span class="hljs-built_in">this</span>.myName = name; <span class="hljs-built_in">this</span>.tellMyName = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{   <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.myName); }}
</code></pre><pre><code><span class="hljs-keyword">var</span> fooObj1 = <span class="hljs-keyword">new</span> foo(<span class="hljs-string">'James'</span>);fooObj1.tellMyName(); <span class="hljs-comment">// will print Jamesvar fooObj2 = new foo('Mike');fooObj2.tellMyName(); // will print Mike</span>
</code></pre><p>Can you identify a fundamental problem with the above code? The problem is we are wasting memory with the above approach. Note that the method <code>tellMyName</code> is the same for each and every instance of <code>foo</code>. Each time we create an instance of <code>foo</code> the method <code>tellMyName</code> ends up taking space in the system’s memory. If <code>tellMyName</code> is the same for all the instances it’s better to keep it in a single place and make all our instances refer from that place. Let’s see how to do this.</p>
<pre><code><span class="hljs-keyword">var</span> foo = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name</span>) </span>{ <span class="hljs-built_in">this</span>.myName = name;}
</code></pre><pre><code>foo.prototype.tellMyName = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{   <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.myName);}
</code></pre><pre><code><span class="hljs-keyword">var</span> fooObj1 = <span class="hljs-keyword">new</span> foo(<span class="hljs-string">'James'</span>);fooObj1.tellMyName(); <span class="hljs-comment">// will print Jamesvar fooObj2 = new foo('Mike');fooObj2.tellMyName(); // will print Mike</span>
</code></pre><p>Let’s check the difference with the above approach and previous approach. With the above approach, if you <code>console.dir()</code> the instances then you will see something like this:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/cCfrooHWD8qhcTEt6sqlXGI6hNVo-MT00Icv" alt="Image" width="726" height="642" loading="lazy">
<em>Fig: 2</em></p>
<p>Note that as a property of the instances we only have <code>myname</code>. <code>tellMyName</code> is defined under <code>__proto__</code>. I will come to this <code>__proto__</code> after sometime. Most importantly note that comparing <code>tellMyName</code> of both the instances evaluates to true. Function comparison in JavaScript evaluates true only if their references are the same. This proves that <code>tellMyName</code> is not consuming extra memory for multiple instances.</p>
<p>Let’s see the same thing with the previous approach:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ZNgTtP4W2av-lJDUoRDdf7DmuWtnGumvbFUe" alt="Image" width="750" height="514" loading="lazy">
<em>Fig: 3</em></p>
<p>Note that this time <code>tellMyName</code> is defined as a property of the instances. It’s no longer under that <code>__proto__</code>. Also, note that this time comparing the functions evaluates to false. This is because they are at two different memory locations and their references are different.</p>
<p>I hope by now you understand the necessity of <code>prototype</code>.</p>
<p>Now let’s look into some more detail about prototype.</p>
<p>Each and every JavaScript function will have a <code>prototype</code> property which is of the object type. You can define your own properties under <code>prototype</code>. When you will use the function as a constructor function, all the instances of it will inherit properties from the <code>prototype</code> object.</p>
<p>Now let’s come to that <code>__proto__</code> property you saw above. The <code>__proto__</code> is simply a reference to the prototype object from which the instance has inherited. Sounds complicated? It’s actually not that complicated. Let’s visualize this with an example.</p>
<p>Consider the code below. We already know creating an Array with array literals will inherit properties from <code>Array.prototype</code>.</p>
<pre><code><span class="hljs-keyword">var</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
</code></pre><p>What I just said above is “<em>The <code>__proto__</code> is simply a reference to the prototype object from which the instance has inherited</em>”. So <code>arr.__proto__</code> should be the same with <code>Array.prototype</code>. Let’s verify this.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/j8gJ-ryF1SW3bo7IWNnJoreG3Hp5vy1ZSIbx" alt="Image" width="588" height="258" loading="lazy">
<em>Fig: 4</em></p>
<p>Now we shouldn’t access the prototype object with <code>__proto__</code>. According to MDN using <code>__proto__</code> is highly discouraged and may not be supported in all browsers. The correct way of doing this:</p>
<pre><code><span class="hljs-keyword">var</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];<span class="hljs-keyword">var</span> prototypeOfArr = <span class="hljs-built_in">Object</span>.getPrototypeOf(arr);prototypeOfArr === <span class="hljs-built_in">Array</span>.prototype;prototypeOfArr === arr.__proto__;
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/WJ6FyFSXejZFU4QONss9YDsZqDLX64UWRYwM" alt="Image" width="744" height="482" loading="lazy">
<em>Fig: 5</em></p>
<p>The last line of the above code snippet shows that <code>__proto__</code> and <code>Object.getPrototypeOf</code> return the same thing.</p>
<p>Now it’s time for a break. Grab a coffee or whatever you like and try out the examples above on your own. Once you are ready, come back to this article and we will then continue.</p>
<h4 id="heading-prototype-chaining-amp-inheritance">Prototype chaining &amp; Inheritance</h4>
<p>In Fig: 2 above, did you notice that there is another <code>__proto__</code> inside the first <code>__proto__</code> object? If not then scroll up a bit to Fig: 2. Have a look and come back here. We will now discuss what that is actually. That is known as prototype chaining.</p>
<p>In JavaScript, we achieve Inheritance with the help of prototype chaining.</p>
<p>Consider this example: We all understand the term “Vehicle”. A bus could be called as a vehicle. A car could be called a vehicle. A motorbike could be called a vehicle. Bus, car, and motorbike have some common properties that's why they are called vehicle. For example, they can move from one place to another. They have wheels. They have horns, etc.</p>
<p>Again bus, car, and motorbike can be of different types for example Mercedes, BMW, Honda, etc.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/LmR5EM367CwHz0BXh8o9jBeAPjbIjmfYjFNz" alt="Image" width="800" height="490" loading="lazy">
<em>Fig: 6</em></p>
<p>In the above illustration, Bus inherits some property from vehicle, and Mercedes Benz Bus inherits some property from bus. Similar is the case for Car and MotorBike.</p>
<p>Let's establish this relationship in JavaScript.</p>
<p>First, let's assume a few points for the sake of simplicity:</p>
<ol>
<li>All buses have 6 wheels</li>
<li>Accelerating and Braking procedures are different across buses, cars, and motorbikes, but the same across all buses, all cars, and all motorbikes.</li>
<li>All vehicles can blow the horn.</li>
</ol>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Vehicle</span>(<span class="hljs-params">vehicleType</span>) </span>{  <span class="hljs-comment">//Vehicle Constructor    this.vehicleType = vehicleType;}</span>
</code></pre><pre><code>Vehicle.prototype.blowHorn = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Honk! Honk! Honk!'</span>); <span class="hljs-comment">// All Vehicle can blow Horn}</span>
</code></pre><pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Bus</span>(<span class="hljs-params">make</span>) </span>{ <span class="hljs-comment">// Bus Constructor  Vehicle.call(this, "Bus");      this.make = make}</span>
</code></pre><pre><code>Bus.prototype = <span class="hljs-built_in">Object</span>.create(Vehicle.prototype); <span class="hljs-comment">// Make Bus constructor inherit properties from Vehicle Prototype Object</span>
</code></pre><pre><code>Bus.prototype.noOfWheels = <span class="hljs-number">6</span>; <span class="hljs-comment">// Let's assume all buses have 6 wheels</span>
</code></pre><pre><code>Bus.prototype.accelerator = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Accelerating Bus'</span>); <span class="hljs-comment">//Bus accelerator}</span>
</code></pre><pre><code>Bus.prototype.brake = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Braking Bus'</span>); <span class="hljs-comment">// Bus brake}</span>
</code></pre><pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Car</span>(<span class="hljs-params">make</span>) </span>{  Vehicle.call(<span class="hljs-built_in">this</span>, <span class="hljs-string">"Car"</span>);  <span class="hljs-built_in">this</span>.make = make;}
</code></pre><pre><code>Car.prototype = <span class="hljs-built_in">Object</span>.create(Vehicle.prototype);
</code></pre><pre><code>Car.prototype.noOfWheels = <span class="hljs-number">4</span>;
</code></pre><pre><code>Car.prototype.accelerator = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Accelerating Car'</span>);}
</code></pre><pre><code>Car.prototype.brake = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Braking Car'</span>);}
</code></pre><pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MotorBike</span>(<span class="hljs-params">make</span>) </span>{  Vehicle.call(<span class="hljs-built_in">this</span>, <span class="hljs-string">"MotorBike"</span>);  <span class="hljs-built_in">this</span>.make = make;}
</code></pre><pre><code>MotorBike.prototype = <span class="hljs-built_in">Object</span>.create(Vehicle.prototype);
</code></pre><pre><code>MotorBike.prototype.noOfWheels = <span class="hljs-number">2</span>;
</code></pre><pre><code>MotorBike.prototype.accelerator = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Accelerating MotorBike'</span>);}
</code></pre><pre><code>MotorBike.prototype.brake = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Braking MotorBike'</span>);}
</code></pre><pre><code><span class="hljs-keyword">var</span> myBus = <span class="hljs-keyword">new</span> Bus(<span class="hljs-string">'Mercedes'</span>);<span class="hljs-keyword">var</span> myCar = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">'BMW'</span>);<span class="hljs-keyword">var</span> myMotorBike = <span class="hljs-keyword">new</span> MotorBike(<span class="hljs-string">'Honda'</span>);
</code></pre><p>Allow me to explain the above code snippet.</p>
<p>We have a <code>Vehicle</code> constructor which expects a vehicle type. As all vehicles can blow their horns, we have a <code>blowHorn</code> property in <code>Vehicle</code>'s prototype.</p>
<p>As <code>Bus</code> is a vehicle it will inherit properties from <code>Vehicle</code> object.</p>
<p>We have assumed all buses will have 6 wheels and have the same accelerating and braking procedures. So we have <code>noOfWheels</code>, <code>accelerator</code> and <code>brake</code> property defined in <code>Bus</code>’s prototype.</p>
<p>Similar logic applies for Car and MotorBike.</p>
<p>Let’s go to Chrome Developer Tools -&gt; Console and execute our code.</p>
<p>After execution, we will have 3 objects <code>myBus</code>, <code>myCar</code>, and <code>myMotorBike</code>.</p>
<p>Type <code>console.dir(mybus)</code> in the console and hit <code>enter</code>. Use the triangle icon to expand it and you will see something like below:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1ST6FxGCAEigEAayuqNpwlUByhTlg3jDm4GR" alt="Image" width="800" height="771" loading="lazy">
<em>Fig: 7</em></p>
<p>Under <code>myBus</code> we have properties <code>make</code> and <code>vehicleType</code>. Notice the value of <code>__proto__</code> is prototype of <code>Bus</code>. All the properties of its prototype are available here: <code>accelerator</code>, <code>brake</code>, <code>noOfWheels</code>.</p>
<p>Now have a look that the first <code>__proto__</code> object. This object has another <code>__proto__</code> object as its property.</p>
<p>Under which we have <code>blowHorn</code> and <code>constructor</code> property.</p>
<pre><code>Bus.prototype = <span class="hljs-built_in">Object</span>.create(Vehicle.prototype);
</code></pre><p>Remember the line above? <code>Object.create(Vehicle.prototype)</code> will create an empty object whose prototype is <code>Vehicle.prototype</code>. We set this object as a prototype of <code>Bus</code>. For <code>Vehicle.prototype</code> we haven’t specified any prototype so by default it inherits from <code>Object.prototype</code>.</p>
<p>Let’s see the magic below:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/VD2RXaotYkPxWd3opcuthx8dX1olyo66LN1Z" alt="Image" width="446" height="414" loading="lazy">
<em>Fig: 8</em></p>
<p>We can access the <code>make</code> property as it is <code>myBus</code>'s own property.</p>
<p>We can access the <code>brake</code> property from <code>myBus</code>'s prototype.</p>
<p>We can access the <code>blowHorn</code> property from <code>myBus</code>'s prototype’s prototype.</p>
<p>We can access the <code>hasOwnProperty</code> property from <code>myBus</code>'s prototype’s prototype’s prototype. :)</p>
<p>This is called prototype chaining. Whenever you access a property of an object in JavaScript, it first checks if the property is available inside the object. If not it checks its prototype object. If it is there then good, you get the value of the property. Otherwise, it will check if the property exists in the prototype’s prototype, if not then again in the prototype’s prototype’s prototype and so on.</p>
<p>So how long it will check in this manner? It will stop if the property is found at any point or if the value of <code>__proto__</code> at any point is <code>null</code> or <code>undefined</code>. Then it will throw an error to notify you that it was unable to find the property you were looking for.</p>
<p>This is how inheritance works in JavaScript with the help of prototype chaining.</p>
<p>Feel free to try the above example with <code>myCar</code> and <code>myMotorBike</code>.</p>
<p>As we know, in JavaScript everything is an object. You will find that for every instance, the prototype chain ends with <code>Object.prototype</code>.</p>
<p>The exception for the above rule is if you create an object with <code>Object.create(null)</code></p>
<pre><code><span class="hljs-keyword">var</span> obj = <span class="hljs-built_in">Object</span>.create(<span class="hljs-literal">null</span>)
</code></pre><p>With the above code <code>obj</code> will be an empty object without any prototype.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/7NnMhJUMOYgjrMLyRW7HWIcJP4bNE0FvCtI7" alt="Image" width="484" height="352" loading="lazy">
<em>Fig: 9</em></p>
<p>For more information on <code>Object.create</code> check out the documentation on MDN.</p>
<p>Can you change the prototype object of an existing object? Yes, with <code>Object.setPrototypeOf()</code> you can. Check out the documentation in MDN.</p>
<p>Want to check if a property is the object’s own property? You already know how to do this.<code>Object.hasOwnProperty</code> will tell you if the property is coming from the object itself or from its prototype chain. Check out its documentation on MDN.</p>
<p>Note that <code>__proto__</code> also referred to as <code>[[Prototype]]</code>.</p>
<p>Now it’s time for another break. Once you are ready, come back to this article. We will then continue and I promise this is the last part.</p>
<h4 id="heading-understanding-classes-in-javascript">Understanding Classes in JavaScript</h4>
<p>According to MDN:</p>
<blockquote>
<p>JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax <em>does not</em> introduce a new object-oriented inheritance model to JavaScript.</p>
</blockquote>
<p>Classes in JavaScript will provide better syntax to achieve what we did above in a much cleaner way. Let’s have a look into the class syntax first.</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Myclass</span> </span>{  <span class="hljs-keyword">constructor</span>(name) {    <span class="hljs-built_in">this</span>.name = name;  }    tellMyName() {    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name)  }}
</code></pre><pre><code><span class="hljs-keyword">const</span> myObj = <span class="hljs-keyword">new</span> Myclass(<span class="hljs-string">"John"</span>);
</code></pre><p><code>constructor</code> method is a special type of method. It will be automatically executed whenever you create an instance of this class. Inside your class body. Only one occurrence of <code>constructor</code> is possible.</p>
<p>The methods that you will define inside the class body will be moved to the prototype object.</p>
<p>If you want some property inside the instance you can define it in the constructor, as we did with <code>this.name = name</code>.</p>
<p>Let’s have a look into our <code>myObj</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/8YV1-cTjvrf4za0emIjWqvDfmmonmA1287vp" alt="Image" width="800" height="672" loading="lazy">
<em>Fig: 10</em></p>
<p>Note that we have the <code>name</code> property inside the instance that is <code>myObj</code> and the method <code>tellMyName</code> is in the prototype.</p>
<p>Consider the code snippet below:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Myclass</span> </span>{  <span class="hljs-keyword">constructor</span>(firstName) {    <span class="hljs-built_in">this</span>.name = firstName;  }    tellMyName() {    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name)  }  lastName = <span class="hljs-string">"lewis"</span>;}
</code></pre><pre><code><span class="hljs-keyword">const</span> myObj = <span class="hljs-keyword">new</span> Myclass(<span class="hljs-string">"John"</span>);
</code></pre><p>Let’s see the output:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/dY8-i7joXX5hzVuLXbgN4vUENWqoParuuoJW" alt="Image" width="552" height="310" loading="lazy">
<em>Fig: 11</em></p>
<p>See that <code>lastName</code> is moved into the instance instead of prototype. Only methods you that you declare inside the Class body will be moved to prototype. There is an exception though.</p>
<p>Consider the code snippet below:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Myclass</span> </span>{  <span class="hljs-keyword">constructor</span>(firstName) {    <span class="hljs-built_in">this</span>.name = firstName;  }    tellMyName = <span class="hljs-function">() =&gt;</span> {    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name)  }  lastName = <span class="hljs-string">"lewis"</span>;}
</code></pre><pre><code><span class="hljs-keyword">const</span> myObj = <span class="hljs-keyword">new</span> Myclass(<span class="hljs-string">"John"</span>);
</code></pre><p>Output:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/GIb2hzCV7C92-Z9L1oEHpr-tJgAFytgrQsdN" alt="Image" width="708" height="248" loading="lazy">
<em>Fig: 12</em></p>
<p>Note that <code>tellMyName</code> is now an arrow function, and it has been moved to the instance instead of prototype. So remember that arrow functions will always be moved to the instance, so use them carefully.</p>
<p>Let’s look into static class properties:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Myclass</span> </span>{  <span class="hljs-keyword">static</span> welcome() {    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World"</span>);  }}
</code></pre><pre><code>Myclass.welcome();<span class="hljs-keyword">const</span> myObj = <span class="hljs-keyword">new</span> Myclass();myObj.welcome();
</code></pre><p>Output:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/CpztRyj49N2Wss0c6-o2bqAa3x5dWA3blyC4" alt="Image" width="800" height="506" loading="lazy">
<em>Fig: 13</em></p>
<p>Static properties are something that you can access without creating an instance of the class. On the other hand, the instance will not have access to the static properties of a class.</p>
<p>So is static property a new concept that is available only with the class and not in the old school JavaScript? No, it’s there in old school JavaScript also. The old school method of achieving static property is:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Myclass</span>(<span class="hljs-params"></span>) </span>{}Myclass.welcome = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World"</span>);}
</code></pre><p>Now let’s have a look at how we can achieve inheritance with classes.</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicle</span> </span>{  <span class="hljs-keyword">constructor</span>(type) {    <span class="hljs-built_in">this</span>.vehicleType= type;  }  blowHorn() {    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Honk! Honk! Honk!"</span>);  }}
</code></pre><pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bus</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Vehicle</span> </span>{  <span class="hljs-keyword">constructor</span>(make) {    <span class="hljs-built_in">super</span>(<span class="hljs-string">"Bus"</span>);    <span class="hljs-built_in">this</span>.make = make;   }  accelerator() {    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Accelerating Bus'</span>);  }  brake() {    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Braking Bus'</span>);  }}
</code></pre><pre><code>Bus.prototype.noOfWheels = <span class="hljs-number">6</span>;
</code></pre><pre><code><span class="hljs-keyword">const</span> myBus = <span class="hljs-keyword">new</span> Bus(<span class="hljs-string">"Mercedes"</span>);
</code></pre><p>We inherit other classes using the <code>extends</code> keyword.</p>
<p><code>super()</code> will simply execute the parent class’s constructor. If you are inheriting from other classes and you use the constructor in your child class, then you have to call <code>super()</code> inside the constructor of your child class otherwise it will throw an error.</p>
<p>We already know that if we define any property other than a normal function in the class body it will be moved to the instance instead of prototype. So we define <code>noOfWheel</code> on <code>Bus.prototype</code>.</p>
<p>Inside your class body if you want to execute parent class’s method you can do that using <code>super.parentClassMethod()</code>.</p>
<p>Output:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/cSH-VN7BReS2g5-2FkoDEY0dC6DxpeLrG4DD" alt="Image" width="800" height="828" loading="lazy">
<em>Fig: 14</em></p>
<p>The above output looks similar to our previous function based approach in Fig: 7.</p>
<h4 id="heading-wrapping-up">Wrapping up</h4>
<p>So should you use new class syntax or old constructor based syntax? I guess there is no definite answer to this question. It depends on your use case.</p>
<p>In this article, for the classes part I have just demonstrated how you can achieve prototypical inheritance classes. There is more to know about JavaScript classes, but that’s out of the scope of this article. Check out the documentation of classes on MDN. Or I will try to write an entire article on classes at some time.</p>
<p>If this article helped you in understanding prototypes, I would appreciate if you could applaud a little.</p>
<p>If you want me to write on some other topic, let me know in the responses.</p>
<p>You can also connect with me over <a target="_blank" href="https://www.linkedin.com/in/shirshendubhowmick/">LinkedIn</a>.</p>
<h4 id="heading-thank-you-for-reading">Thank You for Reading. :)</h4>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to declare JavaScript variables: a look at let, const, and var ]]>
                </title>
                <description>
                    <![CDATA[ With the old JavaScript, we had only one way to declare a variable, and that was with var, like var x = 10. It will create a variable called x and assign a value 10 to it. Now with modern ES6 JavaScript, we have 3 different ways to declare a ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-declare-javascript-variables-a-look-at-let-const-and-var-5d801c70c377/</link>
                <guid isPermaLink="false">66bce175bf44a4e8b300aea5</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Shirshendu Bhowmick ]]>
                </dc:creator>
                <pubDate>Mon, 11 Mar 2019 14:49:24 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*f5NxsWhcLjKe4GYjw74adg.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>With the old JavaScript, we had only one way to declare a variable, and that was with <code>var</code>, like <code>var x = 10</code>. It will create a variable called x and assign a value 10 to it. Now with modern ES6 JavaScript, we have 3 different ways to declare a variable: <code>let</code>, <code>const</code> and <code>var</code>. We will talk about <code>let</code> &amp; <code>const</code> later. For now, let's focus on <code>var</code>.</p>
<h2 id="heading-var">var</h2>
<p>We already know how to declare a variable with <code>var</code>. Let us now refer to some code to understand <code>var</code> properly.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> x = <span class="hljs-number">20</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> y = <span class="hljs-number">10</span>;
    <span class="hljs-built_in">console</span>.log(x);
    <span class="hljs-built_in">console</span>.log(y);
}
foo(); <span class="hljs-comment">// will print 20 and 10</span>
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// will print 20</span>
<span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">// will throw a reference error</span>
</code></pre>
<p>Those who are familiar with C or C++ might understand why the output is like so. This is because <code>x</code> is in global scope and <code>y</code> is in the function foo’s scope. As function <code>foo</code> has access to the global scope, from the inside of the function we can access both <code>x</code> and <code>y</code>. Printing <code>x</code> also goes fine because as <code>x</code> is in global scope, we can access it from everywhere. Things go wrong when we try to access <code>y</code> from the global scope because <code>y</code> is limited to the function scope only.</p>
<p>Similar to C or C++ right? No. Let’s see why not.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> x = <span class="hljs-number">20</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> y = <span class="hljs-number">10</span>;
    {
        <span class="hljs-keyword">var</span> z = <span class="hljs-number">30</span>;
    }
    <span class="hljs-built_in">console</span>.log(x);
    <span class="hljs-built_in">console</span>.log(y);
    <span class="hljs-built_in">console</span>.log(z);
}
foo();
</code></pre>
<p>What do you think the output of the code will be? If you think that there will be a reference error at the line <code>console.log(z)</code>, then you are correct from a C or C++ point of view. But with JavaScript, that’s not the case. The above code will print 20 10 30.</p>
<p>This is because in JavaScript with <code>var</code>, unlike in C and C++, we don’t have any block level scope. We have only global and function level scope. So <code>z</code> falls under function foo’s scope.</p>
<p>Now we have one more example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> x = <span class="hljs-number">20</span>;
<span class="hljs-keyword">var</span> x = <span class="hljs-number">30</span>;
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// this will print 30</span>
</code></pre>
<p>In C or C++ if we declare a variable more than once in the same scope we get an error. But that’s not the case with <code>var</code> in JavaScript. In the above example, it just redefines <code>x</code> and assigns a value of 30.</p>
<p>Let’s consider the below code snippets:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
    x = <span class="hljs-number">20</span>;
    <span class="hljs-built_in">console</span>.log(x);
}
foo();
<span class="hljs-built_in">console</span>.log(x);
</code></pre>
<p>The above code will print 20 20. So what happens here? If you declare a variable anywhere without the <code>var</code> keyword it becomes a part of the global scope. It is accessible from both inside and outside of <code>foo</code>.</p>
<pre><code class="lang-js"><span class="hljs-meta">'use strict'</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
    x = <span class="hljs-number">20</span>;
    <span class="hljs-built_in">console</span>.log(x);
}
foo();
<span class="hljs-built_in">console</span>.log(x);
</code></pre>
<p>In the above code, we are using strict mode. In strict mode, an <code>x = 20</code> kind of declaration is not allowed. It will throw a reference error. You have to declare a variable using <code>var</code>, <code>let</code> or <code>const</code>.</p>
<h2 id="heading-let">let</h2>
<p>Now it’s time to have a look at <code>let</code>. <code>let</code> is the new var in ES6 but with some differences.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> x = <span class="hljs-number">20</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> y = <span class="hljs-number">10</span>;
    {
        <span class="hljs-keyword">let</span> z = <span class="hljs-number">30</span>;
    }
    <span class="hljs-built_in">console</span>.log(x);
    <span class="hljs-built_in">console</span>.log(y);
    <span class="hljs-built_in">console</span>.log(z);
}
foo();
</code></pre>
<p>Remember that in JavaScript, <code>var</code> doesn’t have any block-level scope? Now block level scopes are back with <code>let</code>. If you execute the above code you will get a reference error at the line <code>console.log(z)</code>. The variable <code>z</code> declared with <code>let</code> is now in a different block-level scope and is not accessible outside of this scope.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">let</span> x = <span class="hljs-number">20</span>; <span class="hljs-comment">// will throw an error</span>
</code></pre>
<p>Re-declaration of variables with <code>let</code> is not allowed.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">let</span> y = <span class="hljs-number">20</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>.x); <span class="hljs-comment">// 10</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>.y); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>Global variables declared globally with <code>var</code> are added to the <code>global</code> object, the <code>window</code> in case of browsers. Variables declared globally with let are not added to <code>window</code> (global object). Though they are accessible globally, it's like it’s there but you can’t see it.</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">//undefined</span>
<span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">//reference error</span>
<span class="hljs-keyword">var</span> x;
<span class="hljs-keyword">let</span> y;
</code></pre>
<p>Unlike <code>var</code>, <code>let</code> variables are not initialized with undefined before their definitions are evaluated. If you try to access the variable before that you will encounter a reference error. This is also known as the temporal dead zone. In simple words, hoisting is only available with <code>var</code>, not with <code>let</code> &amp; <code>const</code>.</p>
<h2 id="heading-const">const</h2>
<p><code>const</code> stands for constant, it is very similar to <code>let</code>. The only differences are its value cannot be changed and it needs to be initialized where you are declaring it.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> x = <span class="hljs-number">20</span>;
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// will print 20</span>
x = <span class="hljs-number">30</span> <span class="hljs-comment">// will throw an error</span>
</code></pre>
<p>It’s not that in the case of <code>const</code> objects you can change the property of that object — it’s just that you can’t reassign a <code>const</code> variable.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = {<span class="hljs-attr">firstName</span>: <span class="hljs-string">"James"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Bond"</span>}
<span class="hljs-built_in">console</span>.log(obj); <span class="hljs-comment">// will print the obj object</span>
obj.firstName = <span class="hljs-string">"Ruskin"</span>;
<span class="hljs-built_in">console</span>.log(obj); <span class="hljs-comment">// will print the obj object, it has new firstName</span>
obj = {<span class="hljs-attr">firstName</span>: <span class="hljs-string">"James"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Bond"</span>}; <span class="hljs-comment">// will throw an error</span>
</code></pre>
<p>Also as mentioned earlier you have to initialize a <code>const</code> variable, you can’t keep it uninitialized.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> x; <span class="hljs-comment">// will throw an error</span>
some other code;
</code></pre>
<p>That’s all for this article — see you later!</p>
<h2 id="heading-thank-you-for-reading">Thank you for reading :)</h2>
<p>## </p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
