<?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 Abhishek on Medium]]></title>
        <description><![CDATA[Stories by Abhishek on Medium]]></description>
        <link>https://medium.com/@cabhishek712?source=rss-9300bed91204------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8ElVpHwNa6P2E_ISEyQmgA.jpeg</url>
            <title>Stories by Abhishek on Medium</title>
            <link>https://medium.com/@cabhishek712?source=rss-9300bed91204------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:39:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cabhishek712/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[Learn JavaScript: Summarising You Don’t know JS (this & Object Prototypes) Book 3]]></title>
            <link>https://medium.com/@cabhishek712/learn-javascript-summarising-you-dont-know-js-this-object-prototypes-book-3-4052a4fc29d9?source=rss-9300bed91204------2</link>
            <guid isPermaLink="false">https://medium.com/p/4052a4fc29d9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[prototype-in-javascript]]></category>
            <category><![CDATA[you-dont-know-js]]></category>
            <category><![CDATA[javascript-this-keyword]]></category>
            <category><![CDATA[objects-in-javascript]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 11:13:25 GMT</pubDate>
            <atom:updated>2024-01-01T11:13:25.918Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hi, I’m a frontend developer working with JS, and planning to read YDKJS by Kyle Simpson for a long time and never succeeding, this is another try, I’ll be summarising the books in these posts as I read them.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gljoWHJYAkXbaPLr" /><figcaption>Photo by <a href="https://unsplash.com/@oneminch?utm_source=medium&amp;utm_medium=referral">Dawit</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is the third post, and in this one I’m sharing my learnings from the third book of the series, “<strong>this &amp; Object Prototypes</strong>”. If you are interested in the earlier posts, follow these links,<br>Book 1: <a href="https://medium.com/@cabhishek712/learn-javascript-summarising-you-dont-know-js-up-going-book-1-2d3e42664f78">Up &amp; Going<br></a>Book 2: <a href="https://medium.com/@cabhishek712/learn-javascript-summarising-you-dont-know-js-scopes-closures-book-2-3d2a6f4c5e2b">Scopes &amp; Closures</a></p><p>The titles of the books in this series are self explanatory about what the books hold, so this book is all about the this keyword and Object prototypes.</p><h3>What is the “<em>this”</em> keyword in JavaScript?</h3><p>this is a reserved special identifier keyword that’s automatically defined in the scope of every function.</p><p>this points to a context object that is determined by how the function is called and not by lexical scope rules.</p><p>this is a binding to an object, that is made for each function invocation and is based on the call-site (how and where the function is called).</p><p>this mechanism gives a sense of dynamic scope in JavaScript.</p><h3><em>“this”</em> does not point to the function itself</h3><p>A common misconception is to infer that this points to the function itself, also functions in JavaScript are objects. So, the assumption that this points to the function itself is pretty common.</p><p>One example stated in the book, is trying to use this misconception about this, to keep track of the number of times a function is called.</p><pre>function foo(num) {<br>  //do something<br><br>  // update the count on function object<br>  this.count++;<br>}<br><br>// initialize count property in foo object<br>foo.count = 0;<br><br>var i;<br><br>for (i=0; i&lt;10; i++) {<br> if (i &gt; 5) {<br>  foo( i );<br> }<br>}<br><br>console.log( foo.count ); // 0 -- WTF?<br>// this logs 0, seems like count was never updated</pre><p>It is because this in the foo function does not point to the function object at all, that’s why the value of count is not updated.</p><p>For this use-case and others where you need to reference the function inside itself, most likely for recursion or unbinding an event listener, you can directly use the function identifier inside the function body, like this</p><pre>function foo(num) {<br>  // do something<br><br>  foo.count++; <br>  // access count using foo identifier<br>}<br><br>foo.count = 0;<br><br>foo(1);<br>foo(12);<br>foo(13);<br>foo(14);<br><br>console.log(foo.count); <br>// 4 -- works perfectly</pre><h3>What does “this” point to then?</h3><p>To understand what this points to we need to first understand what <strong>call-site </strong>is, call-site is the location where the function is called *not declared*.</p><p>There are a few conditions and rules which decide what this points to, we need to check these conditions at the <strong>call-site</strong>, to see which rules would apply.</p><p>These conditions and rules have different precedence, let us first understand the rules</p><h4>Rule 1: The Default Binding</h4><p>This is like the fallback rule, when no other rule or condition is met this rule applies, according to the rule, this points to the global object. consider this example,</p><pre>function foo() {<br>  console.log(this.a);<br>}<br><br>var a = 10;<br><br>foo(); // logs 10</pre><p>This rule behaves differently in strict mode, in strict mode this will be undefined not a reference to the global object, like in this snippet</p><pre>function foo() {<br>  &quot;use strict&quot;;<br>  console.log(this.a);<br>}<br><br>var a = 10;<br><br>foo(); <br>// TypeError --&gt; cannot find property &quot;a&quot; on undefined</pre><p>One more point to note is that <strong>strict mode must be active in the function itself</strong>, it doesn’t matter if the call-site is in strict mode or not.</p><h4>Rule 2: Implicit Binding</h4><p>This type of binding is created when an object contains or owns the function that is called, a function is said to be owned by an object when a property in the object references the function and the function is called from that object at the call-site, consider this snippet</p><pre>function foo() {<br>  console.log(this.a);<br>}<br><br>var a = 20;<br><br>let obj1 = {<br>  a: 10,<br>  foo: foo,<br>};<br><br>let obj2 - {<br>  a: 30,<br>  obj1: obj1,<br>};<br><br>obj1.foo() <br>// 10 ---&gt; this implicitly binds to obj1 here<br><br>obj2.obj1.foo() <br>// 10 ---&gt; only the last object reference<br>// matters to the call site<br>// so this points to obj1</pre><p>There are some cases where the implicit binding can get lost, and the program falls back to default binding, making this point to the global object or undefined depending on the strict mode.</p><p>The implicit binding can be lost because of the function not being called using the object reference at the call-site, have a look at these examples of how implicit binding can be lost.</p><pre>let object = {<br>  a: 10,<br>  foo() {<br>    console.log(this.a);<br>  }<br>};<br><br>var a = 10;<br><br>let foo2 = object.foo();<br><br>foo2(); <br>// 10 ---&gt; no object reference at call site<br><br><br>// ------------------------------------- //<br><br><br>function callFun(fn) {<br>  fn();  // this is the call site<br>}<br><br>callFun(object.foo); <br>// 10 ---&gt; no object reference at call site<br><br><br>// -----------------------------------//<br><br><br>setTimeout(object.foo, 1000) <br>// 10 ---&gt; no object reference at call site<br>// call-site is in setTimeout&#39;s implementation</pre><h4>Rule 3: Explicit Binding</h4><p>There are utility functions that are present on all function type objects, which allow us to explicitly define the this binding, they are call() and apply(), they both provide the same functionality, they take the context object that we want this to point to as the first parameter and then call the function, the syntax is like foo.call(obj) and foo.apply(obj).</p><p>The difference between call and apply lies in how they take the parameters that the function foo requires, call takes the parameters as comma separated values like this call(obj, param1, param2, param3...) but apply takes the parameters as an array in the second parameter like this apply(obj, [param1, param2, param3...]).</p><pre>function add(a, b, c) {<br>  return this.x + a + b + c;<br>}<br><br>let obj = {<br>  x: 10,<br>};<br><br>add.call(obj, 1, 2, 3); // 16<br><br>add.apply(obj, [1, 2, 3]); // 16</pre><p><strong>Hard binding</strong> is another way to explicitly provide the binding for this to a function, it works by generating a new function that will always be executed with the context object that was bound to the function.</p><p>The utility function for this is bind, it takes the context object as the first parameter and returns a function that will be executed with that context object always.</p><pre>function add(a, b, c) {<br>  return this.x + a + b + c;<br>}<br><br>let obj = {<br>  x: 10,<br>};<br><br>let addWithObj = add.bind(obj);<br><br>addWithObj(1, 2, 3); <br>// 16 ---&gt; addWithObj is just add function<br>// with obj bound as it&#39;s `this`</pre><p>The bind function can take additional parameters as well, these are the parameters that the original function accepts, a call to bind, binds these parameters as well, for instance</p><pre>function add(a, b, c) {<br>  return this.x + a + b + c;<br>}<br><br>let obj = {<br>  x: 10,<br>};<br><br>let addWithObjAndAas1 = add.bind(obj, 1);<br><br>/* obj and a = 1 are bound to the function<br>   so we just provide b and c as params */<br><br>addWithObj(2, 3); </pre><blockquote>Something new, the hard-bound function produced by bind(..) has a .name property that derives from the original <em>target function</em>. For example: bar = foo.bind(..) should have a bar.name value of &quot;bound foo&quot;, which is the function call name that should show up in a stack trace.</blockquote><h4>Rule 4: new Binding</h4><p>Another way of creating a binding is using the new keyword with function calls. In JavaScript new keyword is very different than languages where we have classes, there it is used with constructor functions to create objects of classes.</p><p>But here in JavaScript the new keyword can be used with any function, and the function call with new, is called a constructor function call, there are a few things that happen differently when we call a function with the new keyword, first of all the syntax is like this var x = new foo();</p><p>Now, this calls the function foo, creates an empty object and binds this empty object as the this value for the function call, and if a primitive value or nothing is returned from the function, this newly created object is returned, otherwise whatever object is returned explicitly from the function will be returned.</p><pre>function foo() {<br>  console.log(&quot;in foo&quot;);<br>  this.x = 100;<br>}<br><br>let y = new foo(); // &quot;in foo&quot;<br><br>console.log(y) <br>// { x: 100 } ---&gt; <br>//foo modifies this and implicitly returns it</pre><h4>Precedence of these rules</h4><p>Now that we know the rules, we just need to look at the call-site and see which of these rules apply, but what if more than one rule applies, in that case we have a precedence.</p><p>Ask these questions in the same order and stop at the first match at the call-site of the function to know what would this point to in that function.</p><ul><li>See if the function is called with the new keyword, if yes this would point to the newly created object.</li><li>See if the context is explicitly defined using a call to call, bind or apply, if yes this would point to the explicitly bound object.</li><li>See if the context is implicitly bound, then this would point to that object.</li><li>Lastly, we have the default binding, which is the global object in non strict mode and undefined in strict mode.</li></ul><h4>this for arrow functions / Lexical this</h4><p>The 4 rules that we saw above do not apply to arrow functions, instead arrow functions get their this from the enclosing scope, whatever this points to in the lexical scope of the arrow function, the same object is used inside the arrow function as well, for instance</p><pre>function foo() {<br>  return () =&gt; {<br>    console.log(this.a);<br>  }<br>}<br><br>let foo2 = foo.call({ a: 1});<br><br>foo2.call({ a: 2 }); <br>// 1 ---&gt; this.a = 1 because arrow function is returned<br>// and it gets this in lexical lookup in the closure</pre><p>This ends the section about this, It is an important and often confusing part of JavaScript. The next section is about Objects.</p><h3>Objects in JavaScript</h3><p>Object is a type in JavaScript just like string, number etc. There are subtypes to objects, which are</p><ul><li>String</li><li>Number</li><li>Array</li><li>Function</li><li>RegEx</li><li>Object</li><li>Boolean</li><li>Date</li><li>Error</li></ul><p>We can create objects using the object literals like let object = { a: 10} or using Object constructor like let object = new Object(); object.a = 10;. The literal format is the one used most commonly.</p><p>The contents of an object consist of values (any type) stored at specifically named <em>locations</em>, which we call properties/keys.</p><p>It is not like that the the values are stored “inside” the object against the keys, rather the keys are pointers (references) to where the actual values are stored in memory.</p><p>There are two ways to access the values stored against a key, one is using . operator and other is using the [] operator, for instance if we want to access user property on object then we can either use object.user or object[&quot;user&quot;]. Both do the same thing, the only difference is that the . operator can only be used to access values which are stored against a “identifier compatible” property name (property names which are valid variable identifiers) but [] operator can be used on any string type key, even computed keys can be used with the [] operator.</p><p>The [] operator is the same that we use to access values in an Array, an Array is also an object where the keys are positive integers, there are some extra optimizations in terms of how the values are stored in Arrays as compared to regular objects.</p><p>Arrays being objects, there is a possibility to store values against non number keys as well, for instance</p><pre>var arr = [1, 2, 4, 5];<br>arr.length; // 4<br><br>arr.bar = &quot;foo&quot;;<br><br>arr.length; // 4<br><br>arr.bar; // foo</pre><p>The key “bar” is added to the arr object but this does not change the length of the Array.</p><p>So adding string keys to Arrays is possible but it’s not a good practice to do so, using Arrays for their intended use is preferred, that is storing values against numeric indices, and use regular objects to store values against string type keys.</p><h4>Duplicating an object in JavaScript</h4><p>One common requirement developers face, is to duplicate the contents of an object to another object, but there is no built in method that does this, the reason is that, there is no specific algorithm for duplication because of the nested nature of objects, meaning that the values present against keys in objects can be any type, so the values can be objects, arrays etc so we would need to loop through the keys recursively and make a copy of the nested objects as well. One more problem with this is that there could be circular references which could lead to infinite loop and the program could hang.</p><p>There are two types of copies for objects, <strong>shallow</strong> and <strong>deep </strong>copies. A shallow copy makes a copy on the first level of the object only, consider this object</p><pre>var obj1 = { a: 10};<br>var obj2 = { b: 20};<br>var object = {<br>  a: 1,<br>  b: true,<br>  obj1: obj1,<br>  obj2: obj2,<br>};</pre><p>If we make a shallow copy of the object, then the values against obj1 and obj2 are references and not truly copies, any change you do to obj1 and obj2 will reflect in the new copied object as well.</p><p>If we made a deep copy instead, then the value will also be copied and changes done in the source object won’t reflect in the copied object.</p><p>One way to make deep copy of an object which which is JSON safe (objects which can be converted to JSON strings and parsed back to object) is using JSON.parse(JSON.stringify(object)).</p><p>There is a method Object.assign() which can be used to make shallow copies, it takes a target object as the first parameter and one or more source objects as it’s subsequent parameters, copies the properties of the source objects into the target object and finally returns the target object, for instance,</p><pre>let sourceObj1 = {<br>  a: 10,<br>  arr: [1, 2, 3],<br>  obj: {<br>    c: 20,<br>  },<br>}<br><br>let sourceObj2 = {<br>  d: 2,<br>}<br><br>let targetObj = Object.assign({}, sourceObj1, sourceObj2);<br><br>targetObj.a; // 10<br>targetObj.d; // 2<br><br>sourceObj1.obj.c; // 20<br>targetObj.obj.c = 100; // changes on source obj as well (shallow)<br>sourceObj1.obj.c; // 100</pre><h4>Adding properties to an object</h4><p>Until now we have been adding properties to objects using the . operator and [] operator with the = assignment operator, there is another way to do it in a more verbose way, it’s the method Object.defineProperty(obj, propertyName, propertyDescriptors)and also introduces <strong>property descriptors.</strong></p><pre>const obj = {};<br><br>Object.defineProperty(obj, &quot;a&quot;, {<br>  value: 10,<br>  writable: true,<br>  configurable: true,<br>  enumerable: true,<br>});<br><br>obj.a; // 10<br><br>Object.getOwnPropertyDescriptor(obj, &quot;a&quot;); <br>/*<br>  value: 10,<br>  writable: true,<br>  configurable: true,<br>  enumerable: true,<br>*/</pre><p>The properties, value, writable, configurable and enumerable are property descriptors and they are present for every value in the object, even if the value is added using the literal syntax, in that case the default values for these properties are taken, which are true.</p><p>These property descriptors define the property, what operations can be performed on the given property? Can the value be overwritten? etc</p><h4>Writable</h4><p>This property tells if the value can be changed or not. If it’s value is true then the key’s value can be changed, when false the key’s value cannot be changed and any assignment to a property that has writable as false will fail silently in non-strict mode, in strict mode it would result in a TypeError.</p><h4>Configurable</h4><p>We can change the property descriptors by calling the Object.defineProperty() again until the configurable descriptor is true, If you try to change the property descriptors for a non-configurable property it will result in a TypeError regardless of strict mode.</p><p>So, setting configurable = false is irreversible because we cannot set the property descriptor again after setting configurable as false.</p><p>Also, if a property’s configurable is set to false, we can’t delete that property, the delete operation fails silently.</p><p>One exception, even when configurable = false, if the writable is true it can be set to false without any error but the opposite from false to true can’t be done.</p><h4>Enumerable</h4><p>enumerable property decides that if a property should show up in a object-property enumeration, like the for..in loop or not. If the value is true then it would show in the loop otherwise not.</p><p>Object.keys(obj) returns a list of all enumerable properties of an object.</p><p>Object.getOwnPropertyNames(obj) returns the list of all enumerable and non-enumerable properties on the object.</p><h4>Ways to reduce changes to objects</h4><p><strong>Immutable objects</strong>: There is often a need to have objects or properties on objects which cannot be changed either intentionally or by mistake. This can be achieved by setting writable and configurable as false, this way the property cannot be updated, redefined or deleted.</p><p><strong>Prevent Extensions</strong>: If you want to stop an object from adding any new properties to it, there is a method Object.preventExtensions(obj) which does exactly this, in non-strict mode adding new property to this object fails silently, but in strict mode it throws a TypeError.</p><p><strong>Seal: </strong>Object.seal(obj) when called on an object, makes obj sealed, meaning new properties can not be added to the object and existing properties cannot be redefined or deleted. It basically calls preventExtension and sets configurable = false for the object.</p><p><strong>Freeze: </strong>Obj.freeze(obj) when called on an object, makes the existing properties immutable, this calls Object.seal() and sets writable = false for all the properties of the object.</p><h4>Getters and Setters in JavaScript</h4><p>When we access or set a property’s value in an object, we are using the default getters and setters, so doing obj.a is basically calling a getter function which gets the value of a in obj if it’s present, otherwise returns undefined. It also checks if the property exists in the prototype chain of the object.</p><p>We can also define custom getters and setters for properties in an object, there are two ways to do this, one is the literal syntax and other one is using the Object.defineProperty() method and adding the getters and setters in the property descriptors.</p><pre>var obj = {<br>  get a() { // getter for property &quot;a&quot;<br>    return 10;<br>  }<br>}<br><br>// above example defined getter for &quot;a&quot; using literal syntax<br><br>Object.defineProperty(<br>  obj, <br>  &quot;b&quot;, <br>  {<br>    get: function() {<br>      return this.b;<br>    },<br>    set: function(val) {<br>      this.b = val;<br>    },<br>    enumerable: true<br>  }<br>)<br><br>// this example defined getter for b using literal syntax</pre><p>When we provide getters and setters for any property, it’s value and writable property descriptors are ignored, the get, set, enumerable and configurable property descriptors are considered.</p><p>When we try to access a property on a object but it returns undefined, It could be so in two cases, either the property does not exist on the object or the value stored against the property is undefined. How can we distinguish between these?</p><p>Using in operator, we can check if a property exists on the object or at any level higher in the prototype chain of the object, the syntax is like &quot;a&quot; in obj, returns boolean.</p><p>If we need to check if the property exists directly in the object and not check the prototype chain, we can use obj.hasOwnProperty(property)</p><h4>Enumerability and iteration</h4><p>We already know about enumerability, iteration is basically iterating over values of an object, for example Arrays, we can iterate over arrays using a general for loop, or we can use a for..of loop to iterate over values in an array.</p><p>The for..of loop on an array uses the iterator function in the array object, arrays have an iterator by default, an iterator is a function which returns an iterator object having a next() function which returns an object having value and done properties, it works like this on arrays</p><pre>var arr = [1, 2, 3];<br>var iterator = arr[Symbol.iterator]();<br><br>iterator.next(); // {value: 1, done: false}<br>iterator.next(); // {value: 2, done: false}<br>iterator.next(); // {value: 3, done: false}<br>iterator.next(); // {done: true}</pre><p>Objects other than arrays do not have an iterator by default, but we can add custom iterator, by defining a Symbol.iterator key on the object using literal syntax or using Object.defineProperty().</p><pre>var obj = {<br>  a: 10,<br>  b: 20,<br>  c: 30,<br>  [Symbol.iterator]: function() { // add Symbol.iterator key as function<br>    var o = this;<br>    var keys = Object.keys(o);<br>    var idx = 0;<br>    return { // return iterator object with next function<br>      next: function() {<br>        return { value: o[keys[idx++]], done: idx &gt; keys.length };<br>      } // on every call of next return {value, done} object<br>    }<br>  }<br>}<br><br><br>// or you can declare the iterator using Object.defineProperty<br><br>Object.defineProperty(obj, Symbol.iterator, {<br>  value: function () {<br>    // same definition as above example<br>  },<br>  enumerable: false,<br>  writable: false,<br>  configurable: true,<br>});</pre><h4>Classes in JavaScript</h4><p>The books deep dives into how “class” is a design pattern and that some languages provide syntax which naturally enables the ability for class-based software development, but JavaScript does not have that syntax.</p><p>It tries to mock the class-based development using whatever language features it has using syntactic sugar like the class keyword, and it does not do a good job because objects in JavaScript are not classes and they don’t have the functionalities that objects and classes in a language like Java have.</p><p>The author discusses what it takes to mock the behaviours of classes in JavaScript and what challenges and differences in the behaviour occur.</p><p>One major feature in classes is “inheritance”, difference between JavaScript and other languages like Java is that, when a class inherits from another class, the inheriting class does not link to the inherited class but rather the inheriting class gets a copy of what it needs from the parent class. But in JavaScript as there are no classes, only objects and objects don’t get copied into other objects, they only get linked together, inheritance is not achieved in it’s true form in JavaScript.</p><p>Also in a language like Java, a class is like a blueprint or an abstraction of how the objects will look and operate, but in JavaScript we don’t get a blueprint, we just have objects.</p><h4>Prototypes in JavaScript</h4><p>When we try to access a property on an object like obj[key] or obj.key, the engine does not just search in the obj object but all other objects that are linked to obj through the [[Prototype]] linkage.</p><p>All objects in JavaScript have an internal property, denoted in the specification as [[Prototype]], which is an object reference and this property is assigned a non-null value at the time of object creation.</p><p>When a property is not found in the object’s own keys, then the engine iterates through the prototypes (because there can be prototype of a prototype object as every object has it, so it’s like chain) and searches for the property in them, if found provides that value otherwise undefined.</p><p>Using Object.create(obj) we can create an empty object which is linked to another object obj, obj is added as prototype of the newly created empty object.</p><pre>var someObj = {<br>  a: 10,<br>}<br><br>var obj = Object.create(someObj);<br><br>obj; // {} -&gt; empty<br><br>obj.a; // 10</pre><p>obj.a gives 2 because obj is linked to someObj through prototype linkage, so even though obj does not have a in it’s keys, the engine checks it’s prototype which is someObj and finds the key in it and gives 2 as the output.</p><p>The prototype chain is considered when using the for..in loop and also when using the in operator. So the for..in will loop over all enumerable properties in the object as well as the prototype chain, and the in operator will check in the object as well as the prototype chain to check if the property exists or not.</p><p>The last object in a prototype chain is the Object.prototype object, because all object are prototype linked to it, this contains all the object utility functions like toString, hasOwnProperty etc.</p><p>You can not create mutually linked objects, both objects connected to each other, for example</p><pre>var obj1 = { a: 100 }<br>var obj2 = Object.create(obj1);<br>obj1.__proto__ = obj2; //trying to create a cyclic <br><br>// throws TypeError: Cyclic __proto__ value</pre><h4>How does setting a property’s value work?</h4><p>While setting a property the following steps are followed, for instance we are performing this obj.foo = &quot;hello&quot;</p><p>If foo is not found in obj or anywhere higher in the prototype chain then foo is added to obj with value hello.</p><p>If foo is found in obj then it’s value is set to hello.</p><p>If foo is found at a higher level in the prototype chain,</p><ul><li>and that property’s <strong>writable </strong>property descriptor is <strong>true</strong>, the same property is added directly to obj with value hello, shadowing the value that was already present in the prototype object.</li><li>The property’s <strong>writable </strong>property descriptor is <strong>false</strong>, the property is not shadowed and not updated, in non-strict mode this operation fails silently but in strict mode, a TypeError is thrown.</li><li>If the property has a setter defined then the setter will be called on that property, new property will not be added to obj so no shadowing occurs in this case too.</li></ul><p>If you still wish to shadow the property in the below two cases then Object.defineProperty() will do the job.</p><p>Shadowing can happen implicitly and cause unwanted results, for instance</p><pre>var obj1 = {<br>  a: 10,<br>}<br><br>var obj2 = Object.createObject(obj1);<br><br>obj2.a; // 10<br><br>obj2.a++; // or -&gt; obj2.a = obj2.a + 1; shadowing happens<br><br>// correct way is obj1.a++ to keep in sync<br><br>obj2.a; // 11<br>obj1.a; // 10</pre><h4>How is new Foo() syntax different in JavaScript</h4><p>In class based languages like Java, to instantiate an object of a class we use a constructor function and create an object of the class like this Car car = new Car(), this syntax is also present in JavaScript, but it definitely does not behave the same way.</p><p>First of all there are no constructor functions in JavaScript, only constructor calls. Any regular function when called with the new keyword it becomes a constructor call, we discussed what it does in a section about this keyword in the beginning of the article.</p><p>Every function in JavaScript, by default has a non-enumerable property prototype in it, which points to an arbitrary object, and whenever we call a function with new like this a = new Foo(), there is a prototype linkage that happens, the Foo.prototype object is added as a [[Prototype]] to a automatically. This is done by the language to “mock” class like behaviour, but it fails to do so because in classes every object we create is a new copy of the structure defined in the class, but here in JavaScript we are just linking all the objects created by using new Foo() to a common Foo.prototype object and not creating any copies.</p><p>So all this does is create multiple objects that are linked to the same object.</p><h4>instanceof operator in JavaScript</h4><p>The instanceof operator is used to introspect (check ancestry of any object, if an object is an instance of a function). It takes two operands like a instanceof Foo, where the left operand is an object and the right operand is a function, instanceof checks if at any level in the prototype chain of a, does the object pointed to Foo.prototype ever appear.</p><p>So it can be used to check if a function is present in the prototype chain of any object, but we know there can be regular objects that can be linked to other objects, is there a way to check if an object is linked to another object? Yes, the function obj1.isPrototypeOf(obj2) can be used to check if two objects are linked.</p><h4>How do we access the prototype object of objects (not functions)?</h4><p>The prototype of functions is accessible using the Foo.prototype property, but it’s not accessible the same way for objects, we can use Object.getPrototypeOf(obj) to get the prototype of obj or we can use obj.__proto__ also to access it, though the latter one is not supported everywhere.</p><h4>Prototypal inheritance</h4><p>This linking of objects and a kind of inheriting of properties from other objects using prototype linkage is termed as prototypal inheritance in JavaScript.</p><h3>Behaviour delegation vs Classes as a design pattern in JavaScript</h3><p>We have seen previously that there is no inbuilt support for classes in JavaScript, the developers of the language have tried to mock the behaviours of classes using prototypes, functions and some syntactic sugar like the class syntax etc, but this does not give the complete capabilities of classes like other object oriented languages such as Java.</p><p>To give a generic example of trying to mock the class behaviour of inheritance, overloading etc using JavaScript syntax we have to write this,</p><pre>function Vehicle(wheels) { // this represents a class<br>  this.wheels = wheels;<br>}<br><br>Vehicle.prototype.accelerate = function() {<br>  console.log(`running on all ${this.wheels} wheels`);<br>}<br>// added a method on the class<br><br><br>function Car() { // this represents another class<br>  Vehicle.call(this, 4); // creates a vehicle with 4 wheels<br>}<br><br>Car.prototype = Object.create(Vehicle.prototype);<br>// links the classes together, creating inheritance<br><br>Car.prototype.start = function() { // added function to Car<br>  console.log(&quot;ignition on&quot;);  // cant be called on Vehicle<br>}<br><br><br>// creating objects now<br>var carObj = new Car();<br>carObj.start(); // output: ignition on<br>carObj.accelerate(); // output: running on all 4 wheels</pre><p>The author emphasises that this syntax is too complex and does not even do the job of mocking classes. Using the syntactic sugar of class keyword and more, the syntax gets simplified a bit like so,</p><pre>class Vehicle {<br>  constructor(wheels) {<br>    this.wheels = wheels;<br>  }<br><br>  accelerate() {<br>    console.log(`running on all ${this.wheels} wheels`);<br>  }<br>}<br><br>class Car extends Vehicle {<br>  constructor(wheels) {<br>    super(wheels);<br>  }<br><br>  start() {<br>    console.log(&quot;ignition on&quot;);<br>  }<br>}<br><br>var car = new Car(4);<br>carObj.start(); // output: ignition on<br>carObj.accelerate(); // output: running on all 4 wheels</pre><p>Still there are issues with this because the behaviour is not completely same as classes, because this is just syntactic sugar, behind the scenes [[Prototype]] mechanism is used, so doing this Vehicle.prototype.accelerate = null; would change the accelerate method on objects created before or after this to be null and break the program, this should not be possible if it were actual classes.</p><p>So, a better design pattern that can be achieved with the available JavaScript syntax is behaviour delegation.</p><h4>What is behaviour delegation?</h4><p>It is a design pattern that uses the prototype linking to create objects linked to each other, we can use it to do the same job as above but with better and easy to understand syntax like this</p><pre>var Vehicle = {<br>  accelerate: function() {<br>    console.log(`running on all ${this.wheels} wheels`);<br>  },<br>  init: function(wheels) {<br>    this.wheels = wheels;<br>  }<br>}<br><br>var Car = Object.create(Vehicle); // prototype link car to vehicle<br>Car.init(4);<br><br><br>// creating objects now<br>var carObj = Object.create(car);<br>carObj; // {}, prototype chain: carObj -&gt; Car -&gt; Vehicle<br>carObj.accelerate(); // output: running on all 4 wheels</pre><p>It’s called delegation because the properties that are not found in it’s own properties, the engine delegates the search to other linked objects through the prototype chain.</p><p>That’s it for this book, this one was filled with new knowledge for me and took some time to get my head around things. If something is not clear please ask away in the comments. Thanks for reading ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4052a4fc29d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn JavaScript: Summarising You Don’t know JS (Scopes & Closures) Book 2]]></title>
            <link>https://medium.com/@cabhishek712/learn-javascript-summarising-you-dont-know-js-scopes-closures-book-2-3d2a6f4c5e2b?source=rss-9300bed91204------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d2a6f4c5e2b</guid>
            <category><![CDATA[learn-javascript]]></category>
            <category><![CDATA[closure-in-javascript]]></category>
            <category><![CDATA[javascript-hoisting]]></category>
            <category><![CDATA[you-dont-know-js]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Sat, 26 Aug 2023 12:35:21 GMT</pubDate>
            <atom:updated>2023-12-02T16:26:21.046Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hi, I’m a frontend developer working with JS, and planning to read YDKJS by Kyle Simpson for a long time and never succeeding, this is another try, I’ll be summarising the books in these posts as I read them.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k7auUlsPnQXdgDyi" /><figcaption>Photo by <a href="https://unsplash.com/@nickmorrison?utm_source=medium&amp;utm_medium=referral">Nick Morrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is the second post, and in this one I’m sharing my learnings from the second book of the series, “<strong>Scopes &amp; Closures</strong>”. If you are interested in the first post (about book 1, Up &amp; Going), the post is <a href="https://medium.com/@cabhishek712/learn-javascript-summarising-you-dont-know-js-up-going-book-1-2d3e42664f78"><strong>here</strong></a><strong>.</strong></p><p>As the title of the book suggests, this book is all about scopes and closures, we get a deep dive into the compilation process, scopes, how are scopes achieved, different types of scopes, hoisting and closures and it’s implementations and uses.</p><h3>Is JavaScript a compiled or an interpreted language?</h3><p>Although JavaScript falls under the category of <em>dynamic </em>or <em>interpreted</em> languages, it is in fact <strong>a compiled language.</strong></p><p>It is not compiled well in advance like most compiled languages, where the compiled version is stored and run later in time, like .c files are compiled to .exe files, which are run later.</p><p>Nor is the result of the compilation portable among various distributed systems, like in Java.</p><p>The JavaScript engine has a compiler, which generates the machine code from the human readable JS code, and the engine then runs this compiled machine code.</p><p>Few important pointers on compilation are-</p><ul><li>In most of the compiled languages, the code goes through three main steps before it is executed, collectively called compilation. The steps are<br>- <strong>tokenising/lexing </strong>(creating a stream of tokens from code),<br>- <strong>parsing </strong>(creating AST from the stream of tokens),<br>- <strong>code-generation </strong>(creating machine code from the AST)<br>This is just a simplified explanation, compilation and compilers are far more complicated than this, there are various optimizations which are made for efficient execution of the code.</li><li>The JavaScript engine does not get the luxury of having plenty of time for optimizing like other languages, because in those languages the code is compiled at build time, like in Java, C++, unlike JavaScript, in which the code is compiled mere microseconds before it is executed. <br>To ensure the fastest performance, JS engines use all kinds of tricks (like JITs, which lazy compile and even hot re-compile, etc.)</li></ul><h3>What is Scope?</h3><p>One of the most fundamental feature of all programming languages is the ability to store data in variables, and access and update the data using the variable identifiers.</p><p>The well-defined set of rules for storing variables, and finding those variables at a later time are <strong><em>Scope</em></strong>. Rules for looking up variables by their identifier names accessible to the currently executing code.</p><p>The author tries to explain how the engine works end to end, from compiling to executing the code by trying to show it as a conversation between the engine and it’s friends, the compiler and scope.</p><p>var a = 2; looks like a single statement, for which we can assume that the compiler will produce the code which summed up in pseudo-code is “<em>allocate memory for a variable, label it </em><em>a, put the value 2 in it”</em>, but that’s not how the engine sees it, the engine sees it as two separate statements, one of which the compiler will handle during compilation, and one which the engine will handle during execution.</p><ul><li>The compiler encounters var a, checks with scope if a variable named a already exists for that scope collection, if it exists the statement is ignored, otherwise the compiler asks scope to declare a variable labelled a for that scope collection.</li><li>The compiler then encounters a = 2, and generates code be executed later by the engine, the engine will ask scope if there is a variable named a in the current scope collection, if found the value 2 is assigned to a, if not found the scope looks in the enclosing scopes, if the variable is not found anywhere, the engine then shows an error.</li></ul><h3>LHS and RHS lookup</h3><p>One new thing that I learned is, there are two types of variable lookups that scope performs, LHS and RHS, the type of lookup performed depends on the operation being performed, is the variable being assigned something? or just the current value of the variable is required?</p><blockquote>who’s the target of the assignment (LHS) and who’s the source of the assignment (RHS)</blockquote><p>When the variable is the target of assignment, a LHS lookup is done, in which we need to find the memory address of the variable, so we can store the new value that is being assigned.</p><p>When the variable is the source of assignment, a RHS lookup is done, in which we just need to know what data is stored in the variable.</p><p>LHS and RHS result in different errors when the variable being looked for is not found</p><ul><li>In case of RHS lookup if the variable is not found, it results in a <em>ReferenceError.</em></li><li>In case of LHS lookup, if the variable is not found, a variable is created in the global scope and the assignment is completed when <strong>strict mode is disabled. </strong>A <em>Reference Error </em>is thrown if <strong>strict mode is enabled.</strong></li><li>In case of LHS, if the lookup is successful but you try to perform an action that is not possible on the type of value that is found, it results in a <em>TypeError.</em></li></ul><h3>Lexical scope in JavaScript</h3><p>There are two predominant models on which scope works, <em>lexical scope </em>and <em>dynamic scope.</em></p><p>Lexical scope is the scope that is defined at lex-time, lex-time is the time at which lexing is done, as discussed earlier, lexing is the first step of the compilation process which is responsible for tokenising a stream of characters that is your code.</p><p>Lexical scope is based on where the variables and the blocks of scopes are authored by you.</p><p>The lookups in lexical scope are hierarchical, if the variable is not found in the current enclosing scope, then it is searched in an outer scope till it reaches the global scope, the first found instance is used and no further searching is done, and if the variable is not found even in global scope then an error is thrown.</p><p>The scope is set at the time of authoring and cannot be changed later during execution, except there are some frowned upon ways to do this (change the scope set during author time later during execution).</p><p>One such way is using eval(), consider this example,</p><pre>function foo(str, a) {<br> eval( str ); // cheating!<br> console.log( a, b );<br>}<br><br>var b = 2;<br><br>foo( &quot;var b = 3;&quot;, 1 ); // 1 3</pre><p>By default, if a string of code that eval(..) executes, contains one or more declarations (either variables or functions), this action modifies the existing lexical scope in which the eval(..) resides. eval(..) can at runtime modify an author-time lexical scope.</p><blockquote>there is one catch though, if eval() is executed in strict mode, it is executed in it’s own lexical scope, which means declarations made inside eval do not affect the enclosing lexical scope.</blockquote><p>Other such ways of hampering the author-time lexical scope during execution are</p><ul><li>setTimeout and setInterval, they can take strings as their first argument which is evaluated using eval</li><li>the new Function() function constructor takes a string of code as it’s last parameter, which is turned into a dynamically generated function.</li></ul><p>These look like good features which provide capabilities to have dynamic code which can probably work better in certain scenarios. Then why are they frowned upon?</p><p>The JavaScript Engine performs a number of performance optimizations during the compilation phase. Some of these are majorly about, being able to statically analyze the code as it lexes, and pre-determine where all the variable and function declarations are, so that it takes less effort to resolve identifiers during execution.</p><p>But when the engine encounters eval and these other constructs discussed above, it assumes that the optimizations would render invalid because the code inside eval could modify the lexical scope.</p><p>So the engine does not perform those optimizations at all, because of this even if the code passed to eval does not change the lexical scope, the code would tend to run slower, just because of the presence of eval.</p><h3>Function vs Block Scope in JavaScript</h3><p>We know that scope is created by enclosing a block of code inside a function body, which creates a new scope and the variables in that function are only accessible to that function and not outside.</p><p>Common thinking about functions is that you declare a function, and write the code in it, another way to think about functions is <strong><em>take any section of code and enclose it inside a function</em></strong><em>.</em></p><p>This creates a scope for that section of code, and the variables and functions inside that block of code are now accessible only inside the block and not outside, this “hides” the variables which the outer scope does not need or is not allowed to use. Let us see this code snippet</p><pre>function doSomething(a) {<br> b = a + doSomethingElse( a * 2 );<br><br> console.log( b * 3 );<br>}<br><br>function doSomethingElse(a) {<br> return a - 1;<br>}<br><br>var b;<br><br>doSomething( 2 );</pre><p>this looks perfectly normal, but do you see that var b is declared in the global scope and so is doSomethingElse, but they are only used inside doSomething so their presence in the global is not necessary, a better way to structure the above code is this,</p><pre>function doSomething(a) {<br> function doSomethingElse(a) {<br>  return a - 1;<br> }<br><br> var b;<br><br> b = a + doSomethingElse( a * 2 );<br><br> console.log( b * 3 );<br>}<br><br>doSomething( 2 ); // 15</pre><p>Now, we have doSomethingElse and b declared inside doSomething and are not exposed to the global scope, this is useful when doSomething performs some critical task, which if present in the global or outer scope may be dangerous or undesirable in any way.</p><p>Another benefit is that, after doSomething has completed executing, the memory assigned to b and doSomethingElse can be freed to be used elsewhere.</p><p>One other benefit of hiding code inside scope is, it avoids collision of variable names.</p><p>Now it may look like enclosing everything in function scope is the solution to hiding variables and functions from the outside scope, it works but it’s not the ideal solution because we declare a function which is also identified by a name, which itself pollutes the enclosing scope.</p><p>This problem could be solved if there was a way to have functions without names, or the names didn’t pollute the enclosing scope, or the function could automatically be executed.</p><p>JS provides a solution for this</p><h3><strong>Immediately Invoked Function Expression (IIFE) in JavaScript</strong></h3><p>A function expression that is immediately invoked or executed is an IIFE. For instance this code snippet, foo pollutes the enclosing scope with the function name,</p><pre>var a = 2;<br><br>function foo() { // foo pollutes the enclosing scope<br> var a = 3;<br> console.log( a ); // 3<br>} <br>foo(); // have to call foo() separately in the enclosing scope<br><br>console.log( a ); // 2</pre><p>The above code can be transformed to use IIFE and prevent polluting of the enclosing scope like this,</p><pre>var a = 2;<br><br>(function() { // inserted &quot;(&quot; before function<br> var a = 3;<br> console.log( a ); // 3<br><br>})();  // enclosed with &quot;)&quot; and &quot;()&quot; in the end<br><br>console.log( a ); // 2</pre><p>A function expression is a statement in which the first identifier is not function, like the above snipped the first identifier is ( and not function.</p><p>So, by adding enclosing the function expression in a ( ) pair, we execute the function immediately by adding () in the end.</p><p>Arguments can also be added to an IIFE, like this</p><pre>var argToPass;<br>(function foo(arg1) {<br>  ...<br>})(argToPass);</pre><h3>Named and Anonymous functions</h3><p>While writing a function expression it is possible to skip the function name and write it as function() { ... } this is an anonymous function.</p><p>Only function expressions can skip the name, function declarations must have a name, otherwise it would be invalid JS and will throw an error.</p><p>Function expressions are mostly seen in callback functions for instance as a callback to setTimeout and setInterval like this</p><pre>setTimeout(function() {<br>  // do something<br>}, 1000);</pre><p>these expressions can be named functions as well, like this</p><pre>setTimeout(function doSomething() {<br>  // do something<br>}, 1000);</pre><p>There are certain drawbacks of using anonymous function expressions,</p><ul><li>As anonymous functions don’t have a name, there will be no name present in the stack trace in case of any error, making debugging difficult.</li><li>Without name the function cannot refer itself, for recursion, or in an event handler if it needs to unbind itself from the event after execution.</li><li>A name can give an idea to the developer what the block of code does, anonymous functions take away that benefit.</li></ul><p>All these drawbacks are gone if we use named function expressions, without any downside, so it is advised <strong>to always use Named Function Expressions.</strong></p><h3>Block Scope in JavaScript</h3><p>While function scope being the major unit of scope for JavaScript, many other languages support block scope.</p><p>Block scope means that any variables or function declarations present in a block, i.e. enclosed within { } pair are only accessible to that block of code and not outside. Take this code snippet for instance,</p><pre>for(var i = 0; i &lt; 10; i++) {<br>  // do something with i<br>}</pre><p>here we declare var i which is used inside the block of code created by the loop and not outside, we don’t need i outside of the block. But, because variables declared using var are not block scoped, we would be able to access i outside of the block, i will also pollute the enclosing scope and ideally the memory allocated to i should be cleared once the execution exits the code block because it’s not used outside the block.</p><p>JavaScript did not support block scope out of the box in earlier versions,</p><blockquote>One new thing I learned is that, the variable declarations in a catch block in a try catch statement are block-scoped to the catch block, they cannot be accessed outside of the catch block.</blockquote><p>In ES6 specification of the language, let was introduced, which is a way to declare variables just like var, but the variables declared using let are scoped to the block they are declared in.</p><p>the above for loop code snippet works much better with let, like this</p><pre>for(let i = 0; i &lt; 10; i++) {<br> // do something with i<br>}</pre><p>now i will be scoped to the block created by the for loop.</p><p>One other feature that ES6 added was const, it is also a way to declare variables (constants more appropriately) just like let and var. const is also block scoped like let, the difference is that it creates a constant, the value assigned to a variable declared using const can not be changed in the future. An attempt to change the value results in an error.</p><h3>Hoisting in JavaScript</h3><p>Assuming you have read the content above, you would have a good understanding of how scope works, what according to you would be the output of the following code snippet?</p><pre>a = 2;<br>var a;<br>console.log(a);</pre><p>It would be 2, and the reason for that is <strong>Hoisting. </strong>One more interesting snippet is this,</p><pre>console.log(a);<br>var a = 2;</pre><p>this one logs undefined, also because of <strong>Hoisting. </strong>What is hoisting?</p><p>We discussed in the starting of this article about how the engine compiles your code before executing it, part of which was to find and associate variable and function declarations to their respective scopes.</p><p>So, in other words, the declarations in your code are processed first, during compilation, before any of the code is executed.</p><p>Which makes our code snippets work like, if it were written like this,</p><pre>// snippet 1<br><br>var a;<br>a = 2;<br>console.log(a);<br><br>// snippet 2<br><br>var a;<br>console.log(a);<br>a = 2;</pre><p>You see how the declarations of a are moved to the top, <strong>this is Hoisting.</strong></p><p>Function declarations are also hoisted. But function expressions are not. For instance</p><pre>foo(); // works fine because the declaration is hoisted<br>bar(); // throws type error because bar is undefined as <br>       //function expression is not hoisted<br><br>function foo() {<br>  // do something<br>}<br><br>var bar = function bar() {<br> // do something else<br>}</pre><p>Considering hoisting, the above code can be interpreted as,</p><pre>function foo() {<br>  // do something<br>}<br>var bar;<br><br>foo();<br>bar(); // cannot execute undefined, so type error<br><br>bar = function bar() {<br>  // do something else<br>}</pre><blockquote>Only declarations are hoisted, not assignments, because changing the order of assignments would change the way your code works completely.</blockquote><blockquote>Hoisting is per scope, this process is repeated for every scope in your code.</blockquote><blockquote>Functions are hoisted first, before variables.</blockquote><p>Consider this snippet and analyze that functions are hoisted first.</p><pre>foo(); // 1<br><br>var foo;<br><br>function foo() {<br> console.log( 1 );<br>}<br><br>foo = function() {<br> console.log( 2 );<br>};</pre><p>Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this code implies:</p><pre>foo(); // &quot;b&quot;<br><br>var a = true;<br>if (a) {<br>   function foo() { console.log( &quot;a&quot; ); }<br>}<br>else {<br>   function foo() { console.log( &quot;b&quot; ); }<br>}</pre><h3>Closures in JavaScript</h3><p>The author points out that, “<em>understanding closure can seem like a special nirvana that one must strive and sacrifice to attain</em>”.</p><blockquote>Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope.</blockquote><p>Let us see a code snippet which will make the definition clearer,</p><pre>function multiplyBy(multiplier) {<br>  // multiplier is in multiplyBy&#39;s scope<br><br>  function multiply(number) {<br>    // number is in multiply&#39;s scope<br>    // multiplier is also accessbile in multiply&#39;s scope<br>    // as per lexical scope rules<br><br>    return number * multiplier;<br>  }<br>  return multiply;<br>}  <br><br>var multiplyBy2 = multiplyBy(2); // returns a function<br>multiplyBy2(4) // returns 8</pre><p>Here we have a multiplyBy function which takes a multiplier parameter and returns a function which takes a number parameter and returns the result of multiplier*number , multiplyBy can be used to create functions which can multiply a number by any multiplier. How does it work? and where is the closure?</p><p>The multiply function has a lexical scope access to multiplier which is in the inner scope of multiplyBy, but we are then returning the function multiply from multiplyBy, and multiplyBy finishes executing. In this case, normally we would expect that the inner scope of multiplyBy would go away, because the garbage collector used by the engine works for freeing up memory that is no longer in use, so is the inner scope of multiplyBy, not in use.</p><p>But closures does not let it happen, that inner scope of multiplyBy is still in use, it is being used by the returned function multiply.</p><p>we create a variable multiplyBy2 = multiplyBy(2) by executing multiplyBy with the multiplier parameter = 2, and it returns a function which would be stored in multiplyBy2 and upon execution, will return the result of multiplying whatever number you pass, by 2.</p><p>As you can see that when multiplyBy2 is executed, we are basically executing the multiply function, just using a different identifier, but we are executing it outside it’s declared lexical scope, which was the inner scope of multiplyBy .</p><h4>The most asked loop question in interviews</h4><p>What is the output of this code snippet?</p><pre>for(var i = 1; i &lt;= 5; i++) {<br>  setTimeout(function timer() {<br>    console.log(i);<br>  }, 1000);<br>}<br><br>// it logs &quot;6&quot;, five times</pre><p>because the function timer has a closure over i, but i is not block scoped because it is declared using var, so all executions of timer have a closure over the same instance of i, which has the value 6 at the time timer is executed.</p><p>To fix this we need the closure of i to be different per iteration of the loop, for this we need to introduce a function scoped variable in between or use let to declare i instead of var.</p><pre>// solution 1<br>for(var i = 1; i &lt;= 5; i++) {<br>  (function IIFE() {<br>    var j = i;<br>    setTimeout(function timer() {<br>      console.log(j);<br>    }, 1000);<br>  })();<br>}<br><br>// solution 2<br>for(var i = 1; i &lt;= 5; i++) {<br>  (function IIFE(j) {<br>    setTimeout(function timer() {<br>      console.log(j);<br>    }, 1000);<br>  })(i);<br>}<br><br>// solution 3<br>for(let i = 1; i &lt;= 5; i++) {<br>  setTimeout(function timer() {<br>    console.log(j);<br>  }, 1000);<br>}</pre><h3>Modules in JavaScript using Closures</h3><p>Modules are a very powerful use-case of Closures, modules are basically a code pattern which expose public features as properties of an object and keeps the private code internal and does not expose it. For instance take this code snippet</p><pre>function ApiModule(endpoint) {<br>  var apiKey = &quot;dfgdg&quot;;<br>  var apiEndpoint = endpoint;<br>  var user = &quot;&quot;;<br><br>  function loginUser(user) {<br>    // do something<br>  }<br><br>  function fetchData() {<br>    //do something<br>  }<br><br>  /* the functions and data declared above<br>   * are in the internal scope of ApiModule<br>   * and are not exposed until returned from the function<br>  */<br><br>  return {<br>    loginUser,<br>    fetchData,<br>    user,<br>  };<br><br>  // only this returned data is accessible outside<br>}<br><br>var Module = ApiModule(&quot;endpoint&quot;);<br>Module.loginUser(user);<br>Module.fetchData();<br>Module.apiKey; //undefined as it&#39;s not exposed</pre><p>The snippet is self explanatory, but to give more details, the function ApiModule is a normal JS function, which has some variables and functions in it’s inner scope, and the function returns an object of the data that will be exposed to the users to be used.</p><p>The ApiModule can be executed any number of times to create any number of copies of the module with different endpoints, a slight variation of the above code pattern, which allows to create only a single module instance is this</p><pre>var foo = (function CoolModule() {<br>  var something = &quot;cool&quot;;<br>  var another = [1, 2, 3];<br><br>  function doSomething() {<br>    console.log( something );<br>   }<br><br>  function doAnother() {<br>    console.log( another.join( &quot; ! &quot; ) );<br>  }<br><br>  var publicApi = {<br>    doSomething: doSomething,<br>    doAnother: doAnother<br>  };<br><br>  return publicApi;<br>})();<br><br>foo.doSomething();<br>foo.doAnother();</pre><p>This pattern leverages IIFE to execute the module creating function only once.</p><h3>ES6 modules</h3><p>ES6 introduces first-class syntax support for the concept of modules, ES6 treats each file as a separate module, each module can import other modules, as well as export their public members.</p><p>There can be only one module per file.</p><p>ES6 modules are static, that is the API that is exported can not change at runtime like it can, by changing the publicApi in our function based modules.</p><p>The compiler also checks when importing stuff from modules, if the imported stuff even exists in the module, if it does not, the compiler throws an early error.</p><h3>Some pointers from the Appendix</h3><h4>Dynamic scope</h4><p>While lexical scope is decided at author time, Dynamic scope is decided at run time and it’s not based on the order of how the code is written but how it is called, dynamic scope is based on the call stack, this in JS is kind of like dynamic scope. Lisp, LaTeX, Emacs use dynamic scope.</p><h4>Polyfilling block scope</h4><p>We can now use let to access block scope, but it is not available in pre-ES6 environments, how can we polyfill block scope in those environments?</p><p>catch is block scoped in ES6, so that is used by many transpilers like Babel to polyfill block scope in pre ES6, how?</p><pre>try { throw 2 }<br>  catch(a) {<br>  // a is not block scoped<br>  console.log(a)<br>}</pre><p>Not very neat, but we should not use IIFE because a function wrapped around any arbitrary code changes the meaning, inside of that code, of this, return, break, and continue.</p><p>Performance wise IIFE is better than try catch, but its not the most wise polyfill to use because of the above reaons.</p><p>This wraps up the second book of the series. It was a good learning for me as always, I hope this was helpful. On to the next one. ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d2a6f4c5e2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn JavaScript: Summarising You Don’t know JS (Up & Going) Book 1]]></title>
            <link>https://medium.com/@cabhishek712/learn-javascript-summarising-you-dont-know-js-up-going-book-1-2d3e42664f78?source=rss-9300bed91204------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d3e42664f78</guid>
            <category><![CDATA[javascript-interview]]></category>
            <category><![CDATA[you-dont-know-js]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Wed, 02 Aug 2023 18:05:45 GMT</pubDate>
            <atom:updated>2023-12-02T16:25:54.029Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hi, I’m a frontend developer working with JS, and planning to read YDKJS by Kyle Simpson for a long time and never succeeding, this is another try, I’ll be summarising the books in these posts as I read them.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IR8GS6khtPC0CViV" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Emile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is the first post, and in this one I’m sharing my learnings from the first book of the series, “<strong>Up &amp; Going</strong>”.</p><p>This book is more like an introduction to JavaScript, and emphasizes on how understanding JavaScript in deep can benefit the people who use it and are not aware of the concepts, features and caveats of the language or choose to ignore what they don’t understand and go on working with the incomplete knowledge that they have of the language.<br>Some statements from the book that ring a bell for me are,</p><blockquote>One of the most important lessons you can learn about writing code is that it’s not just for the computer. Code is every bit as much, if not more, for the developer as it is for the compiler.</blockquote><blockquote>Your computer only cares about machine code, a series of binary 0s and 1s, that comes from compilation. There’s a nearly infinite number of programs you could write that yield the same series of 0s and 1s. The choices you make about how to write your program matter — not only to you, but to your other team members and even to your future self.</blockquote><p>The preface of the book emphasizes on how important it is to understand the <strong>“tough parts” </strong>of JavaScript. I believe that, and thus trying to understand these so called tough parts through these books.</p><p>The first chapter is a introduction to programming and JS, there is basic intro to these concepts,<br>Variables, conditionals, expressions, statements, loops, functions, scopes.</p><p>One key point from this chapter is, <strong>JavaScript is dynamically typed.</strong></p><p>Some programming languages have variables which can hold only a specified type of value like number, string etc, called static typed languages.</p><p>While some emphasize on the type of values rather than variables, meaning a variable can hold any type of value at any time.<br>JavaScript follows the second one, thus it is dynamically typed.</p><h3><strong>What are types in JavaScript?</strong></h3><p>“JavaScript has typed values and not typed variables”.<br>There are 7 types in JavaScript<br>number, string, boolean, object, null, undefined, symbol.<em> </em><br>Any variable can hold a value of any of these types at any time.</p><blockquote><em>One long standing bug in JavaScript, that is probably never going to be fixed is that</em> typeof null<em> returns</em> object <em>and</em> <em>not</em> null<em>.</em></blockquote><p>object<em> </em>is one of the most useful value type.<br>There are couple other types which are very useful and commonly used, array<em> </em>and function<em>, </em>these are not types as such but are specialised or subtypes of the object<em> </em>type.</p><h3><strong>Built in type methods</strong></h3><p>The built in types and subtypes have behaviours exposed as properties and methods, for example a string type has a toUpperCase()<em> </em>method exposed which returns a new string which is the uppercase version of the string on which toUpperCase()<em> </em>was called.</p><pre>let x = &quot;hello world&quot;; // x has a string type value stored in it<br>let y = x.toUpperCase() //y now has string &quot;HELLO WORLD&quot; stored in it</pre><p>There is a lot going on internally in this example, for the primitive types string<em>, </em>number<em>, </em>boolean there are wrapper objects String<em>, </em>Number<em>, </em>Boolean<em> </em>respectively, which have these behaviours exposed as methods and properties.</p><p>When you try to use these behaviours on the primitive values, JavaScript automatically boxes the value in it’s respective wrapper object.</p><h3><strong>Conversion of types in JavaScript (Coercion)</strong></h3><p>Types in JavaScript can be converted from one type to another, this process of converting types is called <strong><em>coercion</em></strong><em>.<br></em><strong><em>Coercion</em></strong> can be implicit or explicit, when it is clear from the code that there will be a conversion is explicit coercion, for instance</p><pre>let numberString = &quot;55&quot;; //typeof numberString == &quot;string&quot;<br>let number = Number(numberString); //typeof number == &quot;number&quot;<br>// the string is converted to number explicitly</pre><p>when it’s not clear from the code that value conversion is happening, it’s called implicit coercion, for instance</p><pre>let numberString = &quot;55&quot;; //typeof numberString == &quot;string&quot;<br>let twiceNumber = numberString * 2; //typeof twiceNumber == &quot;number&quot;<br>//the string is converted to a number implicitly</pre><h3><strong>Truthy and Falsy values in JavaScript</strong></h3><p>When converting other value types to boolean type, only 6 values are converted to false<em>, </em>these values including false are called <strong><em>falsy</em></strong><em> </em>values.</p><pre>&quot;&quot;<br>0<br>-0<br>undefined<br>null<br>NaN<br>false</pre><p>only these values(except false) are converted to false during a coercion, all other values are converted to true<em>.</em></p><h3><strong>Comparing values in JavaScript</strong></h3><p>There are two types of comparisons, <strong><em>equality</em></strong><em> </em>and <strong><em>inequality</em></strong><em>.<br></em>The result of any comparison is strictly a boolean i.e. true<em> </em>or false<em>, </em>regardless of the types that are being compared.</p><p>The comparison operators available in JavaScript are</p><pre>------------- equality operators --------------<br><br>== // loose equality<br>!= // loose non-equality<br>=== // strict equality<br>!== // strict non-equality<br><br>------------- inequality operators ------------<br><br>&gt; // greater than<br>&lt; // lesser than<br>&gt;= // greater than or equals to<br>&lt;= // lesser than or equals to</pre><p>==, ===, != and !== are equality comparison operators, don’t confuse != and !== as inequality operators, they are <strong>non-equality</strong> operators and are just negated counterparts of their respective equality operators.</p><h3><strong>Loose-equality vs strict-equality in JavaScript (== vs ===)</strong></h3><p>It is believed that the difference in == and === is that, == checks for value equality and === checks for value and type equality, the author states that this is <strong>inaccurate, </strong>and the accurate difference is</p><blockquote>== checks for equality with coercion allowed, and === checks for equality with coercion <strong>not</strong> allowed</blockquote><p>What this means is that when the types of the operands are different the values are not equal in case of === (strict equality) but in the case of == (loose equality) the values are coerced to a common type and then the values are compared for equality.</p><p>The algorithms for both these operators can be found <a href="https://262.ecma-international.org/5.1/#sec-11.9.3">here</a>, I urge you to read it.</p><p>The == operator is not transitive, i.e.</p><pre>// a == b and b == c does not mean a ==c. for example <br>new String(&quot;a&quot;) == &quot;a&quot; // true<br>&quot;a&quot; == new String(&quot;a&quot;) //true<br>new String(&quot;a&quot;) == new String(&quot;a&quot;) // false</pre><p>This is because when comparing the new string object with primitive string “a”, the object is coerced to it’s primitive value as per the loose equality algorithm, so the result is true, but when comparing two new string objects, the references to the objects are compared and not the values, and the references of both these objects are not same, so the comparison yields false.</p><p>The === (strict equals) and sameValue algorithm, which is used in Object.is() differ in-</p><ul><li>their treatment with signed zeroes, 0 and -0 and +0 are equal according to === but not Object.is() and,</li><li>NaN values, NaN === NaN is false but Object.is(NaN, NaN) is true</li></ul><h3>Scopes in JavaScript</h3><p>You can declare a variable that will belong to the current function scope, or the global scope if it is declared outside of any function.</p><pre>function foo() {<br>  var a = 100; //the variable a belongs to the scope of function foo<br>  /*<br><br>    function body <br><br>  */<br>}<br><br>var b = 1000; <br>//the variable b is outside any function so it belongs to the global scope<br>var c = a * 100; //Error:: a cannot be accessed outside foo</pre><p>this is function scope in JS, one important concept is Hoisting.</p><h3>Hoisting in JavaScript</h3><p>In the above code example, the variable a is declared in the function foo’s scope and also it is declared at the top, so it is accessible inside the complete scope of the function.</p><p>But, if it were to be declared not at the top, then also it will be accessible throughout the scope of the function foo, because</p><p><em>the var declaration is moved to the top of the enclosing scope.</em></p><p>This is called <strong>Hoisting</strong>.<br>The code is not rearranged or anything of that sort, it just appears that the declaration is moved to the top of the scope, but the details of this lie in the compilation process which we will discuss later.</p><blockquote>Just the declaration is moved to the top, not the assignment. So if you try to use variable a before it’s declared, then you’ll get the value as undefined, only after it’s assignment can you get the actual value of the variable.</blockquote><h3>Strict mode in JavaScript</h3><p>The “strict mode” is basically a strict mode only, when strict mode is enabled the rules are tightened for certain behaviours, and these restrictions are seen to keep the code safer and also strict mode’s restrictions make your code more optimizable by the engine.</p><p>strict mode can be applied to any level, be it the entire file or a function scope, it’s determined by where you put the strict mode pragma</p><pre>&quot;use strict&quot;;<br>// this enforces strict mode<br><br>function foo() {<br>  &quot;use strict&quot;;<br>}<br>// this way strict mode is enabled for function scopes</pre><p>The author recommends using strict mode.</p><h3>Functions in JavaScript</h3><p>We know what functions are and how they are declared and called and stuff.</p><blockquote>But one interesting thing about functions in JavaScript is that functions are just values that are assigned to variables, just like other values (numbers, strings etc). Functions can be assigned to variables, passed to functions as parameters, returned from functions.</blockquote><p><strong>Immediately invoked function expressions (IIFE) in JavaScript<br></strong>One way to invoke a function is by adding a () to the name of the function, there is another way</p><pre>(function foo() {<br>  /*<br>    function body<br>  */<br>})();</pre><p>this is an example of an IIFE, there are many use cases for IIFEs, they are discussed in subsequent books of the series.</p><h3><strong>Closures in JavaScript</strong></h3><p>Closure is a very important part of the language, it’s everywhere, and you might be using it without even knowing that your are using it.</p><blockquote>Closure is basically when we are able to access a function’s scope’s variables even after it has finished executing, and all it’s variables’ memories should have been cleared.</blockquote><p>Closures are experienced mostly when a function returns another function which uses the variables from the outer function’s scope, for instance</p><pre>function outer() {<br>  var x = 10;<br>  return function inner(value) {<br>    return x + value;<br>  }<br>}<br><br>var y = outer(); <br>// the execution of outer has finished here<br>// the memory assigned to variable x should be freed<br>// and we must not be able to access the value of x from here on<br><br>y(100);<br>// because of closures we can access x when we are calling y()<br>// this call returns 110 because x is accessible to the inner function</pre><p>There are so many uses of closures, we will surely discuss them in the post of the second book <strong>Scopes &amp; Closures</strong>. One example discussed in this book is this</p><pre>function makeAdder(valueToAdd) {<br>  function add(x) {<br>    return x + valueToAdd;<br>  }<br>  return add;<br>}<br><br>var addOne = makeAdder(1);<br>var addFive = makeAdder(5);<br><br>addOne(2) // returns 3<br>addFive(2) // returns 7</pre><p>Try to understand the above code, this is what makes closures so powerful.</p><h3>Modules in JavaScript</h3><p>One major use of closures is modules, modules help you create functionalities in which you can hide the private implementation details like functions and variables, and expose only the public API which is accessible from the outside. for instance</p><pre>function App() {<br>  function somePrivateMethod() {<br>    // function body<br>  }<br><br>  function somePublicMethod() {<br>    // function body<br>  }<br><br>  var somePublicVariable = 100;<br><br>  var somePrivateVariable = &quot;key&quot;;<br><br>  var publicApi = {<br>    somePublicVariable,<br>    somePublicMethod,<br>  }<br><br>  return publicApi;<br>}<br><br><br>var appAPI = App(); <br>// only public api is exposed to the user<br>// rest of the implementation details are hidden<br><br>appAPI.somePublicMethod() // is accessible<br><br>appAPI.somePrivateMethod() // ERROR: is not accessbile so is undefined</pre><h3>this<strong> identifier in JavaScript</strong></h3><p>this is another widely misunderstood concept of JS, people with knowledge of other languages like Java may believe that this is related to object oriented behaviours, but it’s not the case in JavaScript.</p><p>this reference in a function usually refers to an object, which object depends on how the function was called. It <strong>does not</strong> refer to the function itself.</p><p>There are various ways a function is called, we will discuss how this identifier’s value differs in these cases briefly, this is a code snippet from the book</p><pre>function foo() {<br>  console.log(this.bar);<br>}<br><br>bar = &quot;hello&quot;;<br><br>var obj1 = {<br>  bar: &quot;hi&quot;,<br>  foo: foo,<br>};<br><br>var obj2 = {<br>  bar: &quot;obj2 hi&quot;,<br>};<br><br>foo(); <br>/* logs hello without strict mode <br>  ** without strict mode the this identifier defaults to the global object<br>  ** in strict mode the this identifier defaults to undefined <br>*/<br><br>obj1.foo();<br>// logs hi -&gt; this way of calling sets this identifier to obj1<br><br>foo.call(obj2)<br>// logs obj2 hi -&gt; this way of calling sets this identifier to obj2<br><br>new foo();<br>// logs undefined -&gt; this way of calling sets this identifier to an empty object</pre><p>these are basic rules related to this , there are chapters dedicated to it in next books, will discuss in detail in future posts.</p><h3>Prototypes in JavaScript</h3><p>Prototype mechanism in JavaScript is related to objects, when you try accessing a property on an object, if that property is not present in the object, JS tries to find another object from the internal prototype reference of the object to search for that property, it is like a fallback.</p><p>This internal prototype linking happens when the object is created, an example stated in the book is</p><pre>var obj1 = {<br>  bar: &quot;bar&quot;,<br>}<br><br>var obj2 = Object.create(obj1);<br><br>obj2.foo = &quot;foo&quot;;<br><br>obj2.foo; // &quot;foo&quot;<br>obj2.bar; // &quot;bar&quot;<br><br>// bar does not exist directly in obj2 but is present in obj1<br>// and obj1 is added as the prototype of obj2 using object.create()<br>// so JS looks for bar in obj1 and finds &quot;bar&quot;</pre><p>This is just an introduction, prototypes is discussed in detail in the third book <strong>this &amp; Object Prototypes.</strong></p><h3>Polyfilling and transpiling in JavaScript</h3><p>There are new versions of the language released with new features every now and then, but the support for these features are not necessarily available instantly or sometimes even later.</p><p>To tackle this issue we have polyfilling, it works by adding a piece of code that is equivalent to the behaviour of the new feature, for instance the book shows how Number.isNaN() is a new feature and might not work in old browsers, so to polyfill it we add this piece of code</p><pre>if (!Number.isNaN) {<br>  Number.isNaN = function isNaN(x) {<br>    return x !== x;<br>  };<br>}</pre><p>It checks if the feature is available, if not it adds it.</p><p>Polyfilling works with new features, but in case of syntax changes that come with new updates of the language, polyfilling cannot be used, in that case <strong>transpiling </strong>the code is used.</p><p>Converting the new syntax code to old syntax code is transpiling, transpilers are used to transpile code, <strong>babel</strong> is a widely known and used transpiler.</p><h3>Some interesting stuff about using JavaScript</h3><p>As we know JS is mostly written to interact with environments like the browser. A lot of code that we write is not controlled by JavaScript because when we use stuff like document.getElementById() it looks like document is a JS object but it is not, it’s a global variable which is a special object which are called host objects .</p><p>The getElementById function we are calling on it also looks like a JS function, but it’s just an interface exposed to us by the DOM from the browser. In some browsers it might be implemented in JS itself but most commonly it is implemented in languages like C/C++ etc.</p><p>console.log() and alert are also not JS.</p><h3>What the series holds for us developers?</h3><p>This first book was a introduction to the language, all these concepts are explained extensively in the following books, the list of the books in YDKJS is-</p><ul><li><strong>Scopes &amp; Closures</strong>- this book aims to clear the fundamentals of scopes and closures in JS which are crucial for understanding JS. The book starts by debunking the misconception that JS is interpreted, it is not, and thus we dive deep into how the compiler reads our code and deals with function and variable declarations, then the book moves to understanding lexical scope and then finally closures and some use cases like the module pattern which we discussed a little bit earlier.</li><li><strong>this &amp; Object Prototypes</strong>- talks about the this keyword which we discussed earlier, and the four rules that determine what will be it’s value in a function call, then it moves on to discuss prototypal inheritance in JS, and that it is not the same as classes and inheritance but rather behaviour delegation, the author argues that behaviour delegation is a better design pattern than classes and inheritance.</li><li><strong>Types &amp; Grammar</strong>- this book talks about coercion, debates how it’s easy and essential to understand rather than ignoring and avoiding coercion and labelling it as a flaw of the language</li><li><strong>Async &amp; Performance</strong>- This book discusses asynchronous programming in JS, clears out concurrent, async and parallel, discusses callbacks as a method for async programming then the issues with it and moves to discuss the solutions to those issues provided by promises and generators, Also covers web workers and SIMD, this book is designed to give you the tools and skills to write reasonable and performant JS code</li><li><strong>ES6 &amp; Beyond</strong>- this book states that JS is ever evolving and thus focuses on new features added to the language in ES6</li></ul><p>This is it for the first book of the series, It was a good read and learning for me, I hope this was helpful. Hoping to keep up and read the full series and get to know JS.</p><p>Done with the second book of the series,<strong> </strong><a href="https://medium.com/@cabhishek712/learn-javascript-summarising-you-dont-know-js-scopes-closures-book-2-3d2a6f4c5e2b"><strong>here</strong></a><strong> </strong>is the link to the post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d3e42664f78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add a loading spinner in React Function components]]></title>
            <link>https://medium.com/@cabhishek712/implementing-a-loader-loading-spinner-in-react-function-components-950eef0f4253?source=rss-9300bed91204------2</link>
            <guid isPermaLink="false">https://medium.com/p/950eef0f4253</guid>
            <category><![CDATA[loading-animation]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-tutorial]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Sat, 15 Jul 2023 09:47:53 GMT</pubDate>
            <atom:updated>2023-07-22T09:15:58.119Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post we will be adding a loader/loading spinner in a ReactJS function component, I had earlier written an article in which I did the same thing using React’s class based components, <a href="https://medium.com/@cabhishek712/how-i-implemented-a-loading-spinner-in-a-react-application-d4cd46a3a2e0">How I implemented a loading spinner in a React Application</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SSL1bVtr6R-T7stk" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The use case is basically that when we are fetching data using a network call to the backend or a content provider, it takes some time to get the response, and as soon as we get the response we populate the data on the screen, this creates a not so good user experience, one second the screen is empty and the next second it’s filled with data, like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*l50c66durjVSBIn-re_mLg.gif" /><figcaption><strong>example of a table where data is loaded by a network call and it just flashes in creating a bad user experience</strong></figcaption></figure><p>now we will improve this by adding a loader, but first let’s understand, How? <br><strong>The requirement: </strong>we need to show a loader when the network call is in progress and remove the loader, and show the data when we receive the data from the network call.</p><p><strong>How can we do this? <br>STATE!! </strong>We can use state for this, we can have a state variable, which tells that the network call is in progress, we can have a boolean named “isDataLoading”, which is <strong>false</strong> initially and when we trigger the network call, we change it to <strong>true, </strong>in which case we will show the loader, and when the network call has finished, we change it to <strong>false</strong> again, which will remove the loader and show the data, it can be coded like this,</p><pre>function TableComponentWithLoader() {<br>  const [isDataLoading, setIsDataLoading] = useState(false);<br>  <br>  useEffect(() =&gt; {<br>    getDataFromBackend();<br>  }, [])<br><br>  async getDataFromBackend() {<br>    //set the state isDataLoading = true before making the network call<br>    setIsDataLoading(true);<br>    //make the network call here<br>    await asyncFunctionThatMakesNetworkCall();<br>    //reset the state isDataLoading = false when network call has finished<br>    setIsDataLoading(false);<br>  }<br><br>  return (<br>    &lt;&gt;<br>      {isDataLoading ? &lt;Loader /&gt; : &lt;RenderData /&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><p>For now let’s take a paragraph element which says “loading data please wait…….”, the UI looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*xkRK9ZKtJ_sxdfFolKw5OQ.gif" /><figcaption><strong>Nice! this is better, text saying that please wait data is loading, at least the user now knows what’s happening</strong></figcaption></figure><p><strong>Now let’s add an actual loader to this<br></strong>You can use anything as a loader, a gif, a video, an image, whatever you feel like, I’ll be using a npm package for the loader, <a href="https://www.npmjs.com/package/react-loader-spinner"><strong>react-loader-spinner</strong></a><strong>.<br></strong>This package has a number of variations of loaders available to use directly, checkout their <a href="https://mhnpd.github.io/react-loader-spinner/docs/components/rotating-lines"><strong>website</strong></a><strong> </strong>to know more. Now run</p><pre>npm install react-loader-spinner</pre><p>in your project, I’ll be using the classic spinner here which can be used like this,</p><pre>import { RotatingLines } from &quot;react-loader-spinner&quot;;<br><br>function Loader() {<br>  return (<br>    &lt;RotatingLines<br>      strokeColor=&quot;grey&quot;<br>      strokeWidth=&quot;5&quot;<br>      animationDuration=&quot;0.75&quot;<br>      width=&quot;96&quot;<br>      visible={true}<br>    /&gt;<br>  )<br>}<br><br>// you need to use this Loader component in the <br>// TableComponentWithLoader component</pre><p>Now our table looks like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-XLsu-3TWA5bYjEtqXI2cA.gif" /><figcaption><strong>Now we have a loading spinner telling our users that wait, we are getting your data</strong></figcaption></figure><p>Try it out, also check out the different loaders that react-loader-spinner provides, there are a lot of interesting ones, I hope I was of help. ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=950eef0f4253" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Branching in git and collaboration]]></title>
            <link>https://medium.com/@cabhishek712/branching-in-git-and-collaboration-4f5de6f5564?source=rss-9300bed91204------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f5de6f5564</guid>
            <category><![CDATA[git-branch]]></category>
            <category><![CDATA[git-merge]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 18:09:36 GMT</pubDate>
            <atom:updated>2023-07-11T18:09:36.246Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi there! This article aims to explain what are git branches and how we use them for collaborating with our teammates, this will not be very exhaustive in terms of features that git offers, but will explain what we mostly use everyday, in other complicated cases StackOverflow comes to the rescue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wyQTA7GaIahbRL_V" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a> R❤</figcaption></figure><p>Now before we get started, I had earlier published an article explaining the <a href="https://medium.com/@cabhishek712/git-and-github-what-are-they-5e56dde88dd4">basics of git and Github</a>, it’s about setting up a repository, committing and other really basic stuff, check it out if needed.</p><p>We are good to go now.</p><p><strong>What is a branch?<br></strong>In simple words a git branch is a version of the repository which diverges from the main repository.<br>There is initially one branch in every git repository, it’s called main/master branch.<br>I will be using simple diagrams to give a visual representation of what we are doing to get a better understanding, one sample diagram is this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*a3-ULt6e6I2OFiRmW9Mkiw.png" /><figcaption><strong>master branch with two commits</strong></figcaption></figure><p>When working on our personal projects, if we are using any version control software, we don’t give attention to creating branches and we tend to keep all our code in the default main/master branch, so we keep on creating new commits on the main branch and updating our code on the remote repository.</p><p>But consider working in a large team collaborating on a big project, you won’t be committing everything on the main branch, you might not even have access to commit or push to master branch in most cases, in that case we generally create a new branch from the main branch, work on the separate branch, write code, create commits and when we are done we get our branch merged in the main branch.</p><p><strong>But how do we create these branches?<br></strong>To create a new branch using git commands we use this,</p><pre>git branch &lt;branch_name&gt;</pre><p>this creates a new branch with the name that you provide, this must be unique and no other branch with the same name can exist, the branch name is the identifier of the branch, so it has to be unique.<br>This command just creates a new branch from the current state of the repository (whatever branch and commit you are on), you need to explicitly checkout to the new branch to actually move to that branch and start working on it, the command for that is</p><pre>git checkout &lt;branch_name&gt;</pre><p>Yes, that’s two steps, there is a shorthand also that combines creating a branch and moving to that branch, it is</p><pre>git checkout -b &lt;branch_name&gt; <br><br>// pay attention to the -b</pre><p>This creates a branch from the <strong>current branch</strong>, if you need to create a new branch from some other branch there is an optional parameter you can provide, &lt;source-branch-name&gt;</p><pre>git checkout -b &lt;branch_name&gt; &lt;source_branch_name&gt;</pre><p>To delete a branch also there is a command,</p><pre>git branch -d &lt;branch_name&gt;<br>// this is safe delete and deletes only if the branch is merged<br><br>git branch -D &lt;branch_name&gt;<br>// this deletes the branch without any safety</pre><p>You can also rename the current branch using this command,</p><pre>git branch -m &lt;new_branch_name&gt;</pre><p>Now that you are on the new branch, you can work and commit on it, this makes the current state of our repository somewhat like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*lKxDGqjXUgV3Tx8YLkQujA.png" /><figcaption><strong>a new branch “feature/blue” created from the master branch after 2 commits on master, the feature/blue branch also has a commit</strong></figcaption></figure><p><strong>Merging<br></strong>Let’s say it was a small feature and it’s completed with just a single commit and finally we need to get our branch merged into the master branch.<br>We can create pull requests to get our branches merged into the master branch, or if you have access to the master branch you can directly merge the feature branch into the master branch and publish the updated master branch to the remote repository.</p><p>There are basically two branches that we merge, one is called the source branch and one is called the target branch, <strong>source</strong> branch is the branch that we are merging and <strong>target </strong>branch is the branch that we are merging into.</p><p>Before creating a pull request or merging the source branch into the target branch, we should always pull the latest code from the target branch into our source branch, this is also a merge, but in the reverse order, we merge the target(master) branch into the source(feature/blue) branch first, this is done because there might be some changes in the master branch since we created the feature branch, and we should keep our feature branch updated with the latest code from master branch and to test our feature with the master branch’s changes or resolve any merge conflicts(more on these later)</p><p>The command that is used for merging is this,</p><pre>git merge &lt;branch_name&gt;</pre><p>This command merges the branch with &lt;branch_name&gt; into the current branch, making the current branch the target branch and &lt;branch_name&gt; the source branch, so for merging the master branch into the feature branch, the command is</p><pre>git merge master</pre><p>git does the merging(combines the changes of both branches).<br>The merge will need user intervention if there are some parts of files which were changed in both the branches, this is called a <strong>merge conflict</strong>, the user needs to specify which changes to keep, this is called <strong>resolving conflicts</strong>, after resolving the conflicts you need to make a commit, this will be the merge commit, and now the branches are merged. The image depicts the current state of the repository</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1lXyWPDoNfxArmUJnFN7A.png" /><figcaption><strong>feature/blue merged into master with a merge commit</strong></figcaption></figure><p>Now if you have access to the master branch you can switch to the master branch, merge the feature branch into the master branch and publish the master branch to the remote repository</p><pre>git checkout master<br>git merge feature/blue<br>git push origin master</pre><p>If you don’t have access to the master branch, you can publish the merged feature branch to the remote repository and create a pull request where the repository is hosted(Github, Gitlab etc).</p><p>The merge command combines the commit history of both the branches, and a new merge commit is created on the target branch, the source branch remains unchanged.</p><p>There is an option in the merge command, which makes the merge work differently, its <strong>Squash merge</strong></p><pre>git merge --squash &lt;branch_name&gt;</pre><p>this will take all the changes from the &lt;branch_name&gt;, squash them into a single commit and add that commit to the current branch (the target branch), this option does not preserve the commit history of the source branch in the target branch.</p><p>There is another way to collaborate or combine changes of two branches, its <strong>rebase,</strong> there is a command like <strong>git merge</strong> for this its <strong>git rebase</strong></p><pre>git rebase master</pre><p>This is run when we are on the feature branch and what this does is, integrates changes from the master branch to the feature branch, and the git logs are modified once the action is complete.</p><p>Git rebase takes all the changes, and compresses them into a single patch and integrates this new patch onto the target branch. Then, it moves the completed work from one branch to another, typically the master branch. In the process, rebase flattens the history, removing unwanted entries. Rebase changes the commit history as it flattens it, while merge preserves the commit history.</p><p>After rebasing your feature branch and publishing it on the remote repository, you can create a pull request to get it merged into the master branch.</p><p>If there were multiple team members working on multiple features at the same time, the repository would look something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtK40SyuPbDCIluXUoRPFQ.png" /><figcaption><strong>A bigger project repository with multiple features developed simultaneously in multiple branches</strong></figcaption></figure><p>The article has been long as it is, will be back in a new one with details on forks and merging strategies. Thanks for your time, hope it was helpful. ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f5de6f5564" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I implemented a loading spinner in a React Application]]></title>
            <link>https://medium.com/@cabhishek712/how-i-implemented-a-loading-spinner-in-a-react-application-d4cd46a3a2e0?source=rss-9300bed91204------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4cd46a3a2e0</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-tutorial]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[loading-control]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 16:50:38 GMT</pubDate>
            <atom:updated>2023-08-26T06:44:12.950Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9dSHBk33nDyl2Pyk" /><figcaption>Photo by <a href="https://unsplash.com/@hautier?utm_source=medium&amp;utm_medium=referral">Christophe Hautier</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi, sorry to bother but this is a fairly old tutorial with Class based components, I have written a new and better one with Function components, head on to <a href="https://medium.com/@cabhishek712/implementing-a-loader-loading-spinner-in-react-function-components-950eef0f4253"><strong>How to add a loader/loading spinner in React Function components.</strong></a></p><p>Let’s start with my story 😅.</p><p>I was working on a project on the MERN stack, On the front end when I was making calls to the API, it took some time to get the response, but the view was rendered without the data. It was ugly, imagine that one second there is an empty table and another second it’s filled with data. Doesn’t feel right for the user.</p><p>I thought about loading spinners, like the buffering spinner on youtube. I immediately thought of using the component state for this. I’ll have a boolean state variable that tells if the data is loading or not. When the variable is true, render the loading spinner, and when it’s false, render the actual data. Simple, right? Yes, it is!</p><p>What I’m saying is, Let’s suppose you have a component that makes an asynchronous call to some API and then populates the response of the API on the view.</p><p>So, the class component looks like this,</p><pre>class MyComponent extends React.Component{</pre><pre>  constructor(props){<br>    super(props);<br>    this.state={<br>      loading:true,<br>      ... // data<br>      ... // data<br>    };<br>  }<br>  <br>  async loadData(){<br>    const data = //asynchronous call to the API ;<br>    setState({<br>      loading:false,<br>      ... //data<br>      ... //data<br>    });</pre><pre>  componentDidMount(){<br>    this.loadData();<br>  }</pre><pre>  render(){<br>    if(this.state.loading){<br>      return ( &lt;Loader /&gt; );<br>    }<br>    else {<br>      return ( &lt;Data /&gt; );<br>    }<br>  }<br>}</pre><p>Did you understand the code snippet above? Let me explain what I did.</p><p>You have a component named MyComponent, in its constructor, you describe the state, one variable is a boolean named loading that tells if the component is loading data or not. The others are the data to be populated on the view. Remember the table that I talked about, it’s that table’s data.</p><p>And we have the loadData() function which is async because we will be making an asynchronous call to the API in this function. We get the response from the API in the data variable and then perform a setState, making the loading state variable false, because we have loaded the data and now we’re not loading and set other state variables too. After we’ve done a state update, the component updates and the render() is called again with the new state.</p><p>In componentDidMount() we just make a call to the async loadData() function.</p><p>In render() method we check the loading state of the component, if the component is in loading state, we render the Loader otherwise, we render the data that we want to populate on the view.</p><h3><strong>Where to get the Loader?</strong></h3><p>Well for first trying out you could just use text like “<strong>Loading…</strong>”, but if you want to use animated spinning loaders follow along.</p><p>I used an npm package called ‘<strong>react-loader-spinner</strong>’. Do an npm install of this package.</p><p>Then in your component file import Loader from ‘react-loader-spinner’</p><pre>import Loader from &#39;react-loader-spinner&#39;;</pre><p>You can see various styles and properties of the Loaders available in this package at <a href="https://www.npmjs.com/package/react-loader-spinner">https://www.npmjs.com/package/react-loader-spinner</a>.</p><p>Now for basics, I’ll show you one such example,</p><pre>&lt;Loader type=&quot;Circles&quot; color=&quot;#00BFFF&quot; height={80} width={80}/&gt;</pre><p>This renders a Loader spinner with three circles doing some animated stuff, the height, width, and color are also specified. You can also add style props to this to give CSS styles.</p><p>That’s all my friend. All the best! ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4cd46a3a2e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Lifecycle of a ReactJS Component]]></title>
            <link>https://medium.com/@cabhishek712/the-lifecycle-of-a-reactjs-component-ce36edfbaa86?source=rss-9300bed91204------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce36edfbaa86</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[lifecycle-methods]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-lifecycle]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 14:59:49 GMT</pubDate>
            <atom:updated>2020-06-30T14:59:49.211Z</atom:updated>
            <content:encoded><![CDATA[<p>Every component in React has a lifecycle, let’s learn about that in this post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*mgHQ4K2fIv8FW76BnAjz0A.png" /></figure><p>The components in React have a lifecycle, what it means is that from the component appearing on the DOM to getting removed from it, there is a defined flow. This is the lifecycle of a React component.</p><p>The lifecycle is divided into three phases,</p><ul><li>Mounting</li><li>Updating</li><li>Unmounting</li></ul><p>Let’s start with the mounting phase,</p><h3><strong>Mounting</strong></h3><p>This phase of the lifecycle deals with getting the Component on the DOM for the first time.</p><p>The methods associated with this phase of the lifecycle are,</p><ul><li>constructor()</li><li>getDerivedStateFromProps()</li><li>render()</li><li>componentDidMount()</li></ul><p>These methods are invoked in the same order they are listed here.</p><p>Firstly, the constructor() of the component is called, it’s used to declare the state of the component or some other data related to the component.</p><p>Then, getDerivedStateFromProps() is called, it’s used to set the state of the component based on the props received from the parent component. The method takes two arguments, the state, and the props, and returns an object with changes to the state.</p><p>Then, the render() method is called, this method returns the actual JSX element which describes the view of the component.</p><p>Finally, the componentDidMount() method is called after the component is rendered on the DOM, it’s used to perform functions that require the component to be present on the DOM.</p><p>Let’s move to the next phase, that is updating.</p><h3><strong>Updating</strong></h3><p>This phase of the lifecycle deals with the updating of the component after being mounted on the DOM, so, the component updates when it’s state or props are changed.</p><p>The methods associated with this phase are,</p><ul><li>getDerivedStateFromProps()</li><li>componentShouldUpdate()</li><li>render()</li><li>getSnapshotBeforeUpdate()</li><li>componentDidUpdate()</li></ul><p>getDerivedStateFromProps() has the same function as mounting phase here too, to set the state of the component from the props.</p><p>Then, shouldComponentUpdate() is called, this just returns true or false. By default, it returns true, if you want to stop a component from updating, you should return false.</p><p>Then, render() is called, this serves the same purpose as in the mounting phase.</p><p>Then, getSnapshotBeforeUpdate() is called, this method gets state and props as parameters for you to check what the values of state and props were currently of the component,</p><p>Then finally, componentDidUpdate() is called after rendering the updated component to the DOM.</p><p>Let’s move to the final phase, that is unmounting.</p><h3><strong>Unmounting</strong></h3><p>This phase deals with the operations associated with the removal of the component from the DOM.</p><p>This phase has only one method, that is componentWillUnmount()</p><p>This method is called when the component is about to be removed from the DOM.</p><p>Now that you know the theory of the concept. One way you can try for yourself how this works is to define these methods in your app and console log from the methods to know about which are called when. This is the best way to understand the lifecycle of react components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce36edfbaa86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git and Github. What are they?]]></title>
            <link>https://medium.com/@cabhishek712/git-and-github-what-are-they-5e56dde88dd4?source=rss-9300bed91204------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e56dde88dd4</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[version-control-system]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Abhishek]]></dc:creator>
            <pubDate>Wed, 10 Jun 2020 18:22:57 GMT</pubDate>
            <atom:updated>2023-07-11T18:12:05.639Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi there! Wondering what is git and/or Github? Well, this post aims to help you with that. We’ll see what is git? How git and Github are different? And use them to have a better understanding of the basics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t8Xinl5Um0a_r8vq" /><figcaption>Photo by <a href="https://unsplash.com/@richygreat?utm_source=medium&amp;utm_medium=referral">Richy Great</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>What is git?</strong></h3><p>“git is a version control system”. So what is a version control system? What does it do?</p><p>Let’s use an analogy, the country’s under lockdown due to coronavirus but you still have a group project to submit, let it be an essay. You are a group of two so you write something and she writes something, let these be versions of your essay/project, then she asks you to make some changes, you do them and you have another version of your work, but you don’t like it later so you want to go the previous version of your writing, you can do that. And in the end, you both want to merge your work and create the final project. All the keeping track of versions, git does that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*BoxIGVbunpIvAsp3SpymtQ@2x.png" /></figure><h3>Setting up git on your system.</h3><p>You can download git from <a href="https://git-scm.com/downloads">https://git-scm.com/downloads</a>. And access it using the command line, you have some GUI implementations as well. Just using git you can do all the version control of a project on your system by making repositories, We’ll see how to do that later, it’s a good time to differentiate between git and Github.</p><h3>What is Github?</h3><p>So, you already know what git is and that it can help with version control of projects on your system only, but you want your partner to contribute to the project too or you want your code to be present somewhere else so in the case of data loss on your system you still have the code, for that you need your code to be present online somewhere. For that you have <strong>Github.</strong> Github is a website that provides online hosting for software development version control using git.</p><p>You can create online repositories on Github, they can be either public or private. While we’re at it let’s create one.</p><ul><li>Go to <a href="https://github.com/">https://github.com/</a>.</li><li>Sign up if you already haven&#39;t.</li><li>Go to your repositories and click on New.</li><li>Enter repository name and description and click on “Create Repository”.</li><li>Github opens the repository and gives details about different ways to set up your repository, we’ll do that using git commands in the next section.</li><li>For now, just copy and save the link shown on the repository page that looks like this “<a href="https://github.com/abhishek-031/test.git">https://github.com/&lt;username&gt;/&lt;repository-name&gt;.git</a>”</li></ul><h3>git commands and setting up your project and repository.</h3><p>Let’s start by setting up a project and see how to use git.</p><ul><li>Create a new directory on your system.</li><li>Open this directory in your favorite code editor.</li><li>Also, open a terminal and move to the project directory, ensure that you have installed git.</li></ul><p>Let’s create an index.html file in the project directory.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;title&gt;Index&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Demo for setting up github repository&lt;/h1&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Edit and save the file.</p><p>Now let’s initialize a git repository in this directory.</p><ul><li>On the terminal type the following command and hit enter,</li></ul><pre>git init</pre><p>This will create an empty git repository in the directory, the terminal will also prompt that “Initialized empty Git repository”.</p><ul><li>Now, enter the following command,</li></ul><pre>git status</pre><p>This command shows the status of your git repository. The terminal will return this message,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*3yjF0wJu4MwKOrPErzM2nQ.png" /><figcaption>Result of git status</figcaption></figure><p>So the repository was initialized and it is empty right now but it shows that there is a file in the project directory which is untracked, you need to add this file to the staging area to commit it to the repository.</p><ul><li>To add the file you can enter the following command</li></ul><pre>git add index.html</pre><p>this adds the index.html file. If there are many files to be added there is another option to the command above,</p><pre>git add .</pre><p>remember to add the dot at the end.</p><ul><li>So the file has been added, now check the status of the repository again, you know which command to use. The result of the command is,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*SY8uDqbMpJVdblPFrwFSyQ.png" /></figure><ul><li>Now to save this version of the project there is a command,</li></ul><pre>git commit -m &quot;message of commit&quot;</pre><p>this command commits the changes of staged files and this creates a new version of the project. Go ahead and commit. This will be the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*g2FJys8F4AV0Lu4Aehbc6g.png" /></figure><p>you can check the status of the repository again, It’ll say nothing to commit. Because no changes were made.</p><ul><li>Now edit the index.html file and save it. Now check the status of the repository. You’ll see this,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*9XRXD7MdzxZAWSInj6Tg-Q.png" /></figure><p>Cool! right?</p><ul><li>Now add the index.html again to the staging area commit. You know the command, go ahead.</li><li>Now commit it with a message.</li><li>Let’s see another command, which gives us the history of commits and previous versions,</li></ul><pre>git log --oneline</pre><p>this gives the log details in one line, for more details about commits use.</p><pre>git log</pre><p>You’ll see results similar to this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*t2k1HkhyaCgt4hXbDu7jQw.png" /></figure><p>see we have two versions of our project. Say you don’t like the changes made in the second commit and want to revert back to the initial commit, type in the following command,</p><pre>git checkout &lt;commit-number&gt; //in my case the commit number is afd7b7a</pre><p>Now go to the index.html file, see it reverted back to the first commit.</p><p>That’s the power of version control.</p><ul><li>Let’s get back to the last commit, to do that use the command</li></ul><pre>git switch master //master is branch, some other post about branches</pre><h3>Add the project files to repository on Github.</h3><p>Let’s now use Github to host the repository online for our teammates to contribute, in this post, we’ll just get the code of the repository online on Github. Get hold of the link copied previously, you’ll be needing it. The process of adding code to Github is like this.</p><ul><li>You’ll need to create a remote for the repository, the command for creating a remote is,</li></ul><pre>git remote add origin &lt;the link that you copied&gt;</pre><p>This adds a remote of your project repository on Github named origin,the code is still not online on Github, there is one last step remaining. Pushing the code on to the remote.</p><ul><li>The last step is pushing the code to the online Github repository, the command is,</li></ul><pre>git push -u origin// origin is the name of the remote</pre><p>Go to your repository on Github, refresh and you’ll see the code present on the repository.</p><p>To learn about git branches and merging and collaborating using git head on to part-2 of this article <a href="https://medium.com/@cabhishek712/branching-in-git-and-collaboration-4f5de6f5564">Branching in git and collaboration</a>.</p><p>That’s all for this post. Thank you for your time. Play with it, try things, you’ll learn with time. You’ll <strong>git</strong> it! ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e56dde88dd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>