<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anirudh syal on Medium]]></title>
        <description><![CDATA[Stories by Anirudh syal on Medium]]></description>
        <link>https://medium.com/@anirudhsyaliitk?source=rss-2af8d2290c18------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cw1dxOSUokR35QcAOtoJwg.jpeg</url>
            <title>Stories by Anirudh syal on Medium</title>
            <link>https://medium.com/@anirudhsyaliitk?source=rss-2af8d2290c18------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:32:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anirudhsyaliitk/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[this Keyword]]></title>
            <link>https://anirudhsyaliitk.medium.com/this-keyword-cf623ca7f0e4?source=rss-2af8d2290c18------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf623ca7f0e4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[intermediate]]></category>
            <category><![CDATA[this]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Anirudh syal]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 14:27:17 GMT</pubDate>
            <atom:updated>2023-06-17T14:27:17.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="the this keyword!" src="https://cdn-images-1.medium.com/max/968/1*Itn1L3WrUA6XTUgLTffuLA.jpeg" /></figure><p>its not a mystery, its just rules.</p><p>let’s dive into the this keyword in JavaScript</p><p><strong>Level 1 — Basic Understanding</strong></p><blockquote>At its simplest, this is a special keyword in JavaScript that refers to the context in which a function is called. In other words, it refers to the <strong>object</strong> that the function is a <strong>method of</strong>. In this case, this inside sayHello refers to obj because sayHello is a method of obj.</blockquote><pre>let obj = {<br>  name: &#39;John&#39;,<br>  sayHello: function() {<br>    console.log(&#39;Hello, &#39; + this.name);<br>  }<br>};<br><br>obj.sayHello();  // Outputs: &#39;Hello, John&#39;</pre><p>Level 2 — Understanding this in Different Contexts</p><blockquote>The value of this can change depending on the context in which a function is called. Here are the four main rules for how this gets bound</blockquote><p><strong>Default Binding</strong>: If a function is invoked as a standalone function (not as a method, constructor, or an arrow function), this will refer to the global object (window in a browser, global in Node.js). This is the case in &quot;<strong>use strict</strong>&quot; mode where this will be undefined.</p><pre>function sayHello() {<br>  console.log(this);  <br>}<br>sayHello();  // Outputs: Window {...} (or global object in Node.js)</pre><p><strong>Implicit Binding</strong>: If a function is called as a method of an object, this refers to the object.</p><pre>let obj = {<br>  name: &#39;John&#39;,<br>  sayHello: function() {<br>    console.log(this.name);<br>  }<br>};<br>obj.sayHello();  // Outputs: &#39;John&#39;</pre><p><strong>Explicit Binding</strong>: We can explicitly set what this refers to using call, apply, or bind. ( i do not use this as much )</p><pre>let obj1 = {<br>  name: &#39;John&#39;<br>};<br><br>let obj2 = {<br>  name: &#39;Jane&#39;<br>};<br><br>function sayHello() {<br>  console.log(this.name);<br>}<br><br>sayHello.call(obj1);  // Outputs: &#39;John&#39;<br>sayHello.call(obj2);  // Outputs: &#39;Jane&#39;</pre><p><strong>New Binding</strong>: When a function is called as a constructor using the new keyword, this refers to the newly created object.</p><pre>function Person(name) {<br>  this.name = name;<br>}<br><br>let john = new Person(&#39;John&#39;);<br>console.log(john.name);  // Outputs: &#39;John&#39;</pre><blockquote>Level 3 — Advanced Concepts and Pitfalls. <em>Now that you have a solid understanding of the basics, let’s dive into some advanced topics and potential pitfalls.</em></blockquote><p><strong>Arrow Functions</strong>: Arrow functions do not have their own this value. Instead, this is lexically bound and refers to the this value of the enclosing non-arrow function. The one below is quite expected. however, let’s wrap our heads around some specific pitfalls.</p><pre>let obj = {<br>  name: &#39;John&#39;,<br>  sayHello: function() {<br>    setTimeout(() =&gt; {<br>      console.log(this.name);  // &#39;this&#39; refers to &#39;obj&#39;<br>    }, 1000);<br>  }<br>};<br>obj.sayHello();  // Outputs: &#39;John&#39; after 1 second // this is lexically bound to the object john</pre><p><strong>Pitfall</strong> — Losing this Context: A common pitfall is losing the this context in callbacks or event handlers.</p><pre>let obj = {<br>  name: &#39;John&#39;,<br>  sayHello: function() {<br>    setTimeout(function() {<br>      console.log(this.name);  // &#39;this&#39; does not refer to &#39;obj&#39;<br>    }, 1000);<br>  }<br>};<br><br>obj.sayHello();  // Outputs: undefined (or an error in strict mode)</pre><p>this inside the setTimeout callback <strong>does not</strong> refer to the obj object as one might expect. Instead, it refers to the global object (window in a browser environment, global in Node.js), and since there is no name property on the global object, it outputs undefined.</p><p>When you use a function as a callback, like in setTimeout, the function is not being used as a method of an object, but is instead being invoked as a standalone function. This is why this inside of the setTimeout callback refers to the global object. ( it is important to note that within the setTimeOut(), the callback function is defined with the <strong>keyword function</strong>.</p><p>In JavaScript, when a <strong>function</strong> is created with the function keyword, a new context for this is created. Functions declared with the function keyword behave like so: When the function is <strong>invoked</strong>, the value of this is determined by <strong>how</strong> the function is called, not <strong>where</strong> the function is defined. This is called the &quot;execution context&quot; or &quot;invocation context&quot; of the function. ( note this explanation holds for functions defined with the keyword function.)</p><p>When I use function keyword to declare a function, the value of this is determined by how the function is called:</p><ul><li>If a function is called as a method of an object, this is set to the object the method is called on. For example, in obj.method(), this inside method refers to obj.</li><li>If a function is called as a standalone function, not as a method of an object, this is set to the global object (window in a browser, global in Node.js). For example, in a function func() that&#39;s not a method of an object, this inside func refers to the global object.</li><li>If a function is called as a constructor (with the new keyword), this is set to the newly created object.</li><li>If a function is called using call, apply, or bind, this is set to the object that is passed as the first argument to call, apply, or bind.</li></ul><p>So, in the setTimeout example, the function passed to setTimeout is not being called as a method of an object, but as a standalone function. Therefore, this inside that function refers to the global object.</p><blockquote><strong>Arrow functions and resolution ?</strong></blockquote><p>On the other hand, arrow functions <strong>do not create</strong> their own this context, so this inside an arrow function is lexically or statically bound. It means that it&#39;s set to the this value of the outer function where the arrow function is defined. Notice that the outer function is still defined with the keyword <strong><em>function.</em></strong></p><pre>let obj = {<br>  name: &#39;John&#39;,<br>  sayHello: function() {<br>    setTimeout(() =&gt; {<br>      console.log(this.name);  // &#39;this&#39; refers to &#39;obj&#39; because arrow functions use the &#39;this&#39; of the enclosing context<br>    }, 1000);<br>  }<br>};<br>obj.sayHello();  // Outputs: &#39;John&#39;</pre><p>Arrow functions <strong>do not bind </strong>their own this, instead, they inherit the one from the <strong>parent scope</strong>, which is defined by the way they are called.</p><p>If you have an object with an arrow function as a method, this will not refer to the object itself because arrow functions do not have their own this. Instead, this inside the arrow function will refer to the surrounding context where the object was defined.</p><pre>let obj1 = {<br>  name: &#39;John&#39;,<br>  sayHello: () =&gt; {<br>    console.log(this.name);<br>  }<br>};<br><br>obj1.sayHello();  // Outputs: undefined</pre><p><strong>let illustrate this even further,</strong></p><pre>function outerFunction() {<br>  let obj1 = {<br>    name: &#39;John&#39;,<br>    sayHello: () =&gt; {<br>      console.log(this.name);  <br>    }<br>  };<br><br>  obj1.sayHello();  // Outputs: undefined<br>}<br><br>outerFunction();</pre><p>In this case, obj1 is defined inside the scope of outerFunction. However, because sayHello is an arrow function, this inside sayHello doesn&#39;t refer to obj1. Instead, this refers to the context of outerFunction.</p><p>The outerFunction function is not a method of an object, it&#39;s just a regular function. Therefore, the value of this inside outerFunction (and hence inside sayHello) is determined by how outerFunction is called. In this case, outerFunction is called as a standalone function, so this inside outerFunction refers to the global object.</p><p>Thus, this.name inside sayHello tries to access the name property of the global object, which is undefined, and that&#39;s why obj1.sayHello() outputs undefined.</p><p><strong>let’s go deeper, and voila!</strong></p><pre>let obj2 = {<br>  name: &#39;Jane&#39;,<br>  outerFunction: function() {<br>    let obj1 = {<br>      name: &#39;John&#39;,<br>      sayHello: () =&gt; {<br>        console.log(this.name);  <br>      }<br>    };<br><br>    obj1.sayHello();  // Outputs: &#39;Jane&#39;<br>  }<br>};<br><br>obj2.outerFunction();</pre><p>In this case, outerFunction is a method of obj2, so when outerFunction is called as obj2.outerFunction(), the value of this inside outerFunction is obj2.</p><p>Since sayHello is an arrow function, it doesn&#39;t have its own this, it inherits the this from its parent scope, which is outerFunction. Therefore, this inside sayHello refers to obj2, not obj1.</p><p>That’s why this.name inside sayHello refers to obj2&#39;s name property, not obj1&#39;s name property, and obj1.sayHello() outputs &#39;Jane&#39;, not &#39;John&#39;.</p><blockquote><strong>Summary</strong></blockquote><p>I believe you now have a good understanding of the this keyword in JavaScript, which is an important concept especially when working with object methods and functions.</p><p><strong>Just to summarise, here are some key points:</strong></p><ol><li>In a regular function (not an arrow function), this usually refers to the object that the function is a method of. However, if a regular function is not a method of an object, this refers to the global object (in a browser, this is window)</li><li>Arrow functions do not have their own this. They inherit this from the parent scope, which is determined when the function is defined, not when it is invoked.</li><li>In event handlers, this refers to the element that fired the event. <strong>we havent covered this here.</strong></li><li>The value of this can be explicitly set with methods like call(), apply(), and bind(). <strong>( i don’t typically use call() apply() bind() )</strong></li></ol><p>Remember, the behaviour of this in JavaScript can sometimes be counterintuitive, especially when it comes to arrow functions and regular functions. It&#39;s always a good idea to carefully test your code and make sure this is referring to what you expect it to.</p><p>If you understand these principles, you’ll be well-equipped to handle most situations involving this in JavaScript.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf623ca7f0e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data encapsulation]]></title>
            <link>https://anirudhsyaliitk.medium.com/data-encapsulation-be3749041854?source=rss-2af8d2290c18------2</link>
            <guid isPermaLink="false">https://medium.com/p/be3749041854</guid>
            <category><![CDATA[encapsulation]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[constructor-function]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Anirudh syal]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 09:44:29 GMT</pubDate>
            <atom:updated>2023-06-17T09:44:40.895Z</atom:updated>
            <content:encoded><![CDATA[<p>and constructor functions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*Ukg132fLfxCRZuNVxi9E3Q.jpeg" /></figure><p>In JavaScript, when you want to maintain <strong>true privacy of variables</strong>, i.e., not accessible directly from outside the object, you cannot use the prototype to define methods that access those variables. This is because prototype methods are not able to access the variables defined within the constructor function; they can only access properties and methods that are attached to this. Now, let me elaborate on this.</p><p>In JavaScript, a constructor function is used to create new objects of the same type. The this keyword within the constructor function refers to the newly created object, and properties can be added to it using the this.propertyName notation.</p><pre>function Person(name, age) {<br>  this.name = name;<br>  this.age = age;<br>}<br><br>var john = new Person(&#39;John&#39;, 30);<br>console.log(john.name); // &#39;John&#39;<br>console.log(john.age); // 30</pre><p>Here, the Person is a constructor function. Now, <strong>functions</strong> have access to a property called prototype. Prototypes are the mechanism by which JavaScript objects inherit features from one another. In JavaScript, prototypes are themselves objects.</p><p>The new keyword in creates an instance of a user-defined object type has a constructor function. The new keyword does the following things:</p><ul><li>It creates a brand new object.</li><li>It links that object to an object <strong>prototype</strong>.</li><li>It binds ‘this’ to the new object scope.</li><li>It implicitly returns ‘this’ if the function doesn’t return its own object. ( notice there is no “return” statement in the declaration of Person )</li></ul><p>In the context of a constructor function, the this keyword refers to the new object being created. If a method is called on an object, this refers to the object the method was called on. Notice that all instances of the type Person, are “built” with all properties directly declared withint the constructor Person. ( As you may guess, this is not memory efficient and we can do better )</p><pre>function Person(name, age) {<br>  this.name = name;<br>  this.age = age;<br>  this.introduce = function() {<br>    console.log(&#39;My name is &#39; + this.name + &#39; and I am &#39; + this.age + &#39; years old.&#39;);<br>  };<br>}<br><br>var john = new Person(&#39;John&#39;, 30);<br>john.introduce(); // &#39;My name is John and I am 30 years old.&#39;</pre><p>There is something else available to us. Each function has a property called prototype. Therefore, the Person function also has a prototype property which refers to itself. And, methods added to that prototype, are inherited by all instances of the type Person like so.</p><pre>function Person(name, age) {<br>  this.name = name;<br>  this.age = age;<br>}<br><br>Person.prototype.sayHello = function() {<br>  return &#39;Hello, my name is &#39; + this.name;<br>};<br><br>var john = new Person(&#39;John&#39;, 30);<br>console.log(john.sayHello()); // &#39;Hello, my name is John&#39;</pre><p>In JavaScript, every function automatically gets a prototype property when it&#39;s created. The prototype property is essentially an object (called a prototype object) that has a constructor property by default. The constructor property points back to the function on which prototype object is a property. This mechanism is used for inheritance in JavaScript.</p><p>Consider the following code:</p><pre>function Car(make, model) {<br>    this.make = make;<br>    this.model = model;<br>}<br><br>Car.prototype = {<br>    start: function() {<br>        console.log(this.make + &#39; &#39; + this.model + &#39; started&#39;);<br>    }<br>};<br><br>let myCar = new Car(&#39;Toyota&#39;, &#39;Corolla&#39;);<br>myCar.start();</pre><p>The output of myCar.start() will be &quot;Toyota Corolla started&quot;. If you add a method to the Car.prototype after creating myCar, myCar will still have access to the new method. This is because myCar&#39;s prototype is a reference to Car.prototype, not a copy of it. So, any modifications to Car.prototype will be reflected in myCar.</p><p>Now, compared to the previous case, when you add <strong>methods</strong> <strong>directly</strong> to the constructor, every instance of the object gets its <strong>own copy</strong> of the method, which <strong>can consume more memory</strong>. But these methods can access private variables from the constructor.</p><p>When you add methods to the prototype, all instances share the same method, leading to memory efficiency. However, these methods cannot access private variables of the constructor.</p><p><strong>Now, the crux of inheritance!</strong></p><p>When you add a method to the prototype, it does not have its own private variables. Private variables are scoped to the <strong>constructor function</strong> and are <strong>unique</strong> to each instance created by that constructor. What the prototype method will share is access to the properties and methods defined on this in the constructor. However, the prototype methods themselves do not have direct access to the private variables declared inside the constructor function.</p><pre>function MyConstructor(balance, bankName) {<br>    let privateVar = balance;<br><br>    this.publicVar = bankName; <br><br>    this.accessPrivateVar = function() {<br>        console.log(privateVar);<br>    };<br>}<br><br>MyConstructor.prototype.accessPublicVar = function() {<br>    console.log(this.publicVar);<br>};<br><br>let obj1 = new MyConstructor(1000, &quot;SBI&quot;);<br>let obj2 = new MyConstructor(0, &quot;ICICI&quot;);<br><br>obj1.accessPrivateVar(); // Logs 1000<br>obj2.accessPrivateVar(); // Logs 0<br><br>obj1.accessPublicVar(); // Logs SBI<br>obj2.accessPublicVar(); // Logs ICICI</pre><p>In this example, accessPrivateVar is defined in the constructor and has access to privateVar. Each instance of MyConstructor has its own accessPrivateVar method and privateVar.( think of it as creating many bank accounts, each with their own private variable called balance.)</p><p>accessPublicVar, on the other hand, is defined on the prototype, so all instances share the same method. This method doesn&#39;t have access to privateVar, but it does have access to publicVar because publicVar is defined on this in the constructor. So when we change publicVar on obj1 and obj2, the changes are reflected when we call accessPublicVar on each object. But the changes to publicVar do not affect the other instance because each instance has its own publicVar.</p><p>Let’s end this post using a sensible example.</p><p>let’s consider a BankAccount constructor function where we want to keep balance as a private variable. We&#39;ll add methods directly to the constructor, allowing them to access the private balance variable.</p><pre>function BankAccount(initialBalance) {<br>    let balance = initialBalance; // private variable<br><br>    // Method added directly to the constructor<br>    this.getBalance = function() {<br>        return balance;<br>    };<br><br>    this.deposit = function(amount) {<br>        balance += amount;<br>    };<br><br>    this.withdraw = function(amount) {<br>        if (amount &lt;= balance) {<br>            balance -= amount;<br>        } else {<br>            console.log(&quot;Insufficient balance.&quot;);<br>        }<br>    };<br>}</pre><p>In the above example, each instance of BankAccount gets its own copy of getBalance, deposit, and withdraw methods. This can consume more memory if you have many instances of BankAccount, but these methods can access the private balance variable because they&#39;re defined within the same scope.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be3749041854" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Encapsulation and Privacy]]></title>
            <link>https://anirudhsyaliitk.medium.com/data-encapsulation-and-privacy-c13a5136729b?source=rss-2af8d2290c18------2</link>
            <guid isPermaLink="false">https://medium.com/p/c13a5136729b</guid>
            <category><![CDATA[constructor-function]]></category>
            <category><![CDATA[encapsulation]]></category>
            <category><![CDATA[this]]></category>
            <category><![CDATA[closures-functions]]></category>
            <dc:creator><![CDATA[Anirudh syal]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 17:09:07 GMT</pubDate>
            <atom:updated>2023-06-15T17:09:07.795Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Secure design In javaScript.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*LrdzfO5rCpG-n0QlOEFRlw.jpeg" /><figcaption><em>Secure coding practices</em></figcaption></figure><p><strong>Idea in brief</strong></p><p>JavaScript does not have built-in support for private variables, but closures can be used to achieve this. This is a technique that&#39;s commonly used in a design pattern called the Module Pattern</p><p>In JavaScript, encapsulation and privacy are not supported in the same way as in some other languages, because JavaScript <strong>does not</strong> have native support for private variables</p><pre>function createCounter() {<br>    let count = 0; <br>    return {<br>        increment: function() {<br>            count++;<br>            console.log(count);<br>        },<br>        decrement: function() {<br>            count--;<br>            console.log(count);<br><br>        },<br>        getCount: function() {<br>            console.log(count)<br>            return count;<br>        }<br>    };<br>}<br><br>const alphaCounter = createCounter();<br>const betaCounter = createCounter();<br><br>alphaCounter.increment() // outputs 1<br>betaCounter.getCount() // outputs 0 <br>alphaCounter.increment() // outputs 2</pre><p>In this example, count is private - it cannot be accessed directly from outside the createCounter function. However, the increment, decrement, and getCount functions, which are defined inside the same scope as count, do have access to it thanks to closures.</p><p>Consider next the following example:</p><pre>function bankAccount(initialBalance) {<br>    let balance = initialBalance;<br>    return {<br>        getBalance: function() {<br>            return balance;<br>        },<br>        deposit: function(amount) {<br>            balance += amount;<br>            return balance;<br>        },<br>        withdraw: function(amount) {<br>            if (balance - amount &lt; 0) {<br>                console.log(&#39;Insufficient balance.&#39;);<br>                return balance;<br>            } else {<br>                balance -= amount;<br>                return balance;<br>            }<br>        }<br>    };<br>}<br><br>let account = bankAccount(100);<br>console.log(account.getBalance());  // 100<br>console.log(account.deposit(50));   // 150<br>console.log(account.withdraw(200)); // Insufficient balance.<br>console.log(account.balance);       // undefined</pre><p>In this example, balance is a variable that is private to the bankAccount function. The returned object has three methods, getBalance, deposit, and withdraw, that are closures and have access to the balance variable, but nothing outside the bankAccount function can directly access or modify balance.</p><p>This encapsulates the balance data, providing a way to control access and modification of it. It is only possible to modify the balance via the provided methods, and these methods can enforce rules (like not allowing the balance to go negative).</p><p>If balance were a public variable, any part of the code could modify it directly, potentially breaking these rules. For example, one could directly set balance to a negative value or a non-numeric value, which would be inconsistent with the rules enforced by the deposit and withdraw methods.</p><p><strong><em>The encapsulation</em></strong> provided by closures is important for data integrity, and it also provides a kind of privacy. In a larger application, there may be many parts of the code that interact with an account, and we don’t want all of them to have unrestricted access to the account balance.</p><p>In terms of user privacy, a similar principle applies. For example, if you were building a web app with user accounts, you could use closures to ensure that sensitive user data (like passwords or personal information) is only accessible via specific functions that enforce appropriate access controls. <strong>This is a key principle in secure software design</strong>.</p><p>Now, let’s take an example of a poor coding practice, where balance is <strong>not encapsulated.</strong></p><pre>function BankAccount(initialBalance) {<br>    this.balance = initialBalance;<br>    this.getBalance = function() {<br>        return this.balance;<br>    };<br>    this.deposit = function(amount) {<br>        this.balance += amount;<br>        return this.balance;<br>    };<br>    this.withdraw = function(amount) {<br>        if (this.balance - amount &lt; 0) {<br>            console.log(&#39;Insufficient balance.&#39;);<br>            return this.balance;<br>        } else {<br>            this.balance -= amount;<br>            return this.balance;<br>        }<br>    };<br>}<br><br>var account = new BankAccount(100);<br>console.log(account.getBalance());  // 100<br>console.log(account.deposit(50));   // 150<br>console.log(account.withdraw(200)); // Insufficient balance.<br>console.log(account.balance);       // 150</pre><p>In this example, balance is a public property of BankAccount instances. Any part of the code that has access to a BankAccount instance can directly access or modify balance, like this:</p><pre>account.balance = -1000;  // Sets the balance to -1000 directly<br>console.log(account.getBalance());  // -1000</pre><p>This is a problem because the balance can be set to any value directly, bypassing the rules enforced by the deposit and withdraw methods. In this example, we were able to set balance to a negative value, even though the withdraw method is supposed to prevent the balance from going negative.</p><p>Also, balance could be set to a non-numeric value, which would make no sense and could cause other parts of the code to fail:</p><pre>account.balance = &quot;a lot&quot;;  // Sets the balance to a string<br>console.log(account.getBalance());  // &quot;a lot&quot;</pre><p>By making balance a private variable and only providing access to it via methods that enforce appropriate rules, we can prevent these kinds of problems.</p><p>Now, let’s develop the pattern <strong>further</strong>, and create <strong>constructor functions</strong> which use javaScript clsoures to hide important variables, while still enabling methods to access and modify them.</p><pre>function BankAccount(initialBalance) {<br>    let balance = initialBalance;<br><br>    this.getBalance = function() {<br>        return balance;<br>    };<br><br>    this.deposit = function(amount) {<br>        if (typeof amount !== &#39;number&#39; || amount &lt;= 0) {<br>            console.log(&#39;Deposit amount must be a positive number.&#39;);<br>            return balance;<br>        }<br>        balance += amount;<br>        return balance;<br>    };<br><br>    this.withdraw = function(amount) {<br>        if (typeof amount !== &#39;number&#39; || amount &lt;= 0) {<br>            console.log(&#39;Withdrawal amount must be a positive number.&#39;);<br>            return balance;<br>        }<br>        if (balance - amount &lt; 0) {<br>            console.log(&#39;Insufficient balance.&#39;);<br>            return balance;<br>        }<br>        balance -= amount;<br>        return balance;<br>    };<br>}<br><br>let account = new BankAccount(100);<br>console.log(account.getBalance());  // 100<br>console.log(account.deposit(50));   // 150<br>console.log(account.withdraw(200)); // Insufficient balance. 150<br>console.log(account.balance);       // undefined</pre><p>In the BankAccount constructor function, balance is a local variable. After the BankAccount function finishes execution, we can&#39;t directly access balance from outside the function, because it&#39;s not a property of the object. It&#39;s not attached to this, so it&#39;s not publicly accessible.</p><p>However, the getBalance, deposit, and withdraw methods, defined inside the BankAccount function, still have access to balance because they were defined in the same scope where balance was defined. This is possible because of closures in JavaScript.</p><p>This creates a situation where balance is private to the object — it can be manipulated using the methods of the object, but it can&#39;t be directly accessed or manipulated from outside the object. This is an example of data encapsulation and privacy in JavaScript. It helps to maintain the integrity of the data by preventing unauthorised access and unintended modification.</p><p>Without using closures to achieve this privacy, any code that had access to the object could directly modify balance. This could lead to balance being set to invalid values (like a negative balance or a non-numeric balance) or being updated without going through the proper checks and procedures (like the overdraft check in withdraw).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c13a5136729b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[|Node.js The very basics of creating a server]]></title>
            <link>https://anirudhsyaliitk.medium.com/node-js-the-very-basics-of-creating-a-server-c408014473b1?source=rss-2af8d2290c18------2</link>
            <guid isPermaLink="false">https://medium.com/p/c408014473b1</guid>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[servers]]></category>
            <dc:creator><![CDATA[Anirudh syal]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 10:05:48 GMT</pubDate>
            <atom:updated>2023-01-24T13:29:15.403Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>No mumbo jumbo</strong></p><p>Let’s understand what are we building here, in pure layman’s language.</p><h3><strong>1.</strong> We want to build an <strong>HTTP server</strong></h3><ul><li>A hardware that stores a website’s files or data, ( HTML, CSS, Js) and can service a client or browser when the client or browser requests for these files or data.</li></ul><h3><strong>2.</strong> So what does this specific <strong>server do</strong>?</h3><ul><li>It connects to the Internet to support physical data exchange</li></ul><h3><strong>3. How does a basic <em>HTTP</em> server function?</strong></h3><ul><li>It is software that understands <a href="https://developer.mozilla.org/en-US/docs/Glossary/URL">URLs</a> (web addresses).</li><li><strong>and the </strong><a href="https://developer.mozilla.org/en-US/docs/Glossary/HTTP">HTTP</a> protocol browsers use.</li></ul><h3>4. What is the process?</h3><ul><li>A browser needs a file that is hosted on a web server.</li><li>It needs to talk to the server to request this file or data.</li><li>The “<strong>language</strong>” servers understand and browsers communicate in, is HTTP. for us, the same, English (or whichever language)</li><li>The server is in a <strong>“listening”</strong> mode. It is listening to the requests from clients( browser in this case)</li><li>These requests enter the server via a <strong>port</strong>. ( just like sound enters the body via the <strong>ears</strong>)</li><li>The server understands what the client wants, ( i.e. the request), and answers the request. This answer is called the <strong>response</strong> of the server.</li><li>There are specific <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status"><strong>response status codes</strong></a>, such as, 200, 401 etc, which are a shorthand for the <strong>status</strong> of the request.</li><li>These codes are part of the HTTP message which the server communicates back to the client/ browser.</li></ul><h3>5. Now, to the node.js part!</h3><p><strong>Lets create the server object</strong></p><pre>const http = require(&#39;http&#39;);<br>//Require the http module.<br>const server = http.createServer();<br>//Create a server object.</pre><ol><li>The http.Server class extends the net.Server class, which is a basic TCP server.</li><li>Because it extends the net.Server class, it inherits all of its methods and properties, such as the listen() method and the on() method.</li><li>This server listens for incoming HTTP requests and respond to them.</li></ol><p><strong>Now, add the event handler to the server object</strong></p><pre>const serverThatCanHandleEvents= server.on(&#39;request&#39;, function (request, response){<br>   // understand the request<br>  //  craft the response<br> //   response will have a header, that defines what the response is about<br>//    the stauts code, the content type etc, i.e, the meta data<br>      response.writeHead(200, {&#39;Content-Type&#39;: &#39;text/plain&#39;});<br>//    response will have the &quot;body&quot; of the response<br>      response.write(&#39;Hello World!&#39;);<br>// and one will need to explicitly end the reponse.<br>      response.end();<br>});</pre><ol><li>The .on() method attaches an event listeners to the server object, so that it can respond to certain events, such as the &#39;request&#39; event.</li><li>The callback function inside on() method tells the server how to respond to the event/ based on the what the request is about.</li><li>The server <strong>understands</strong> the event that needs a response through the keyword <strong>“request”</strong> which is the first argument of the on() method.</li><li>This request is fired when a new HTTP request is received by the server.</li><li>Finally, the <strong>server.on()</strong> returns the <strong>server object again</strong>, with the capability of handling the request.</li></ol><p><strong>Now, enable the server to listen to requests through a port</strong></p><pre>serverThatCanHandleEvents.listen(8080) <br>// server can listen to incoming requests on the port 8080<br>// the server has been made capable to handle requests through the callback function which was passed as an argument to ther .on() method</pre><p>Note, it is <strong>important</strong> that the server.listen() method must be called after the event listener/ handler is attached to the server object, otherwise the server will not be able to respond to incoming requests.</p><ol><li><a href="https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_web_server"><strong>Reference</strong></a> (MDN)</li><li><a href="https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/"><strong>Reference</strong></a> (node http transaction)</li><li><a href="https://nodejs.org/api/https.html"><strong>Reference</strong></a> (node documentation)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c408014473b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>