<?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 Aniket Jha on Medium]]></title>
        <description><![CDATA[Stories by Aniket Jha on Medium]]></description>
        <link>https://medium.com/@vtechguys?source=rss-46d6d4053cee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*yvXd9s1KkHXNOcQF7LzspA.jpeg</url>
            <title>Stories by Aniket Jha on Medium</title>
            <link>https://medium.com/@vtechguys?source=rss-46d6d4053cee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 15:08:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vtechguys/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[Should you default to React.memo() or useMemo()?]]></title>
            <link>https://vtechguys.medium.com/should-you-default-to-react-memo-or-usememo-9dd48ad13715?source=rss-46d6d4053cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dd48ad13715</guid>
            <category><![CDATA[react-optimization]]></category>
            <category><![CDATA[render-props]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aniket Jha]]></dc:creator>
            <pubDate>Fri, 22 Oct 2021 20:20:40 GMT</pubDate>
            <atom:updated>2021-10-22T20:20:40.471Z</atom:updated>
            <content:encoded><![CDATA[<p>You might have faced slow renders in react application? When such a situation happens we find ourselves inclined to use React.memo or useMemo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1x3025bgIpU5LvqaPNUlA.png" /><figcaption>Should you default to React.memo() or useMemo()?</figcaption></figure><p>We use React.memo to bail out of re-rendering by wrapping subtree in React.memo. This works pretty well as an optimization patch but with big real-world apps using it mindlessly can make you suffer “death by thousand cuts” and you may end up wrapping everything that you think is slow with React.memo. With this comes using useMemo and useCallback which you may use for <a href="https://en.wikipedia.org/wiki/Memoization">memoized</a> computational values, functions, and handlers. This adds to overall code complexity and you may end up running more code for React to determine changed values, compare them and memoize them. Sometimes this might be the only solution but there are approaches which you can try before you memoize things.</p><p>Consider the following code sample:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cec9b906ed110695e2b25fe3e422f175/href">https://medium.com/media/cec9b906ed110695e2b25fe3e422f175/href</a></iframe><p>In the code example, we have artificially simulated an expensive sub-tree with &lt;SlowSubtree /&gt; component. Which gets re-rendered on a change in input. As we type in input we set the name state thus causing a re-render of App component, which then renders &lt;SlowSubtree /&gt;. The quick fix here is wrapping SlowSubtreecomponent in a React.memo as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a21641d284dcf419ecd83b69e0834b7c/href">https://medium.com/media/a21641d284dcf419ecd83b69e0834b7c/href</a></iframe><p>React.memo() is a quick fix but can we avoid using it? Following are some approaches:</p><h4><strong>Debounce set-state</strong></h4><p>In the example, we are setting the name state with every keystroke and causing re-rendering each time input changes, setting the state on every keystroke is wastage here. What we can do is we can debounce set state calls to prevent rendering with each keystroke. I consider this as a bit of a <em>hacky</em> approach but I’ve put this here to bring this to your notice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f4432bda4f0d5e34904760f3db81f83/href">https://medium.com/media/8f4432bda4f0d5e34904760f3db81f83/href</a></iframe><h4>State relocation</h4><p>Note that the SlowSubtree the component renders because of a state change in the parent component. The changing part here is name state with &lt;input/&gt; while SlowSubtree is not changing. We can split and move state down in its separate component like shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7be395a18fa5a715c955a7832d10d2b8/href">https://medium.com/media/7be395a18fa5a715c955a7832d10d2b8/href</a></iframe><h4><strong>Render as a child</strong></h4><p>It is not required to move the state down in its own NameInput component we can also move the state up and leverage a pattern called <em>render as child. </em><br>This pattern is very similar to the render props approach but instead of passing components to a render prop, we use props.children instead. Here we will lift the state up in its own component and wrap SlowSubtree component with it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ead30bffad5ced369a7b1e9ca7803509/href">https://medium.com/media/ead30bffad5ced369a7b1e9ca7803509/href</a></iframe><p>When name state changed NameComponent re-render but as it still gets the same children prop as last time so React doesn’t need to visit SlowSubtreesubtree. And as a result &lt;SlowSubtree /&gt; doesn’t re-render.</p><p>I have personally used this approach many times to prevent the re-rendering of child subtree. This pattern is used in layout components where the wrapper decided the layout and styles of its children. For example <a href="https://mui.com/components/cards/">Material-UI Card component.</a></p><h4>Conclusion:</h4><p>Before you use a React.memo() or useMemo() again you should stop and think to see if you can split part that changes from the parts that don’t change. So take into account if state relocation can help before you settle with the memo.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dd48ad13715" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS variables vs ThemeContext]]></title>
            <link>https://vtechguys.medium.com/css-variables-vs-themecontext-e7dc880462d8?source=rss-46d6d4053cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7dc880462d8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css-in-js]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[themes]]></category>
            <dc:creator><![CDATA[Aniket Jha]]></dc:creator>
            <pubDate>Tue, 29 Jun 2021 07:38:46 GMT</pubDate>
            <atom:updated>2021-06-29T08:17:24.745Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*WDVO69jvVYmVT69JUswR1A.png" /><figcaption>The image is taken from<a href="https://www.ailonwebs.com/en/blog/web-page-design/dark-mode-and-light-mode/index.php"> ailonwebs.com</a></figcaption></figure><p>The light mode and dark mode are gaining popularity and more apps are offering these theme switching. This theme switching looks cool but is difficult to implement and hard to get right. There are many libraries(<a href="https://emotion.sh/docs/introduction">emotion.js</a>) that let you do this with ease by giving a ThemeProvider which is nothing but a React component that provides theme context. These libraries use CSS-in-JS which is a beautiful way of writing CSS with javascript.</p><p>I have been using CSS-in-JS for most of my projects and I’m in love with it but over time CSS has improved, the browsers have matured and support for CSS is better than before. The cost of implementing theme switching with CSS-in-JS libraries is considerably more than using browser standard CSS variable.</p><p>Let’s take the example of CSS-in-JS theme switching.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20cd301e1cd8acc955c55c0ebcbe5bb2/href">https://medium.com/media/20cd301e1cd8acc955c55c0ebcbe5bb2/href</a></iframe><p>That’s the beauty of CSS-in-js it’s just javascript. The developer experience is pretty amazing with such API. However the user experience takes a hit when there are many components on the page, so switching the theme takes a while sometimes a noticeable delay. This leads to a poor user experience which is bad for our brand and business. Here is <a href="https://y8l81.csb.app/">codesandbox</a> for the CSS-in-JS example.</p><p>Now let’s do it with CSS variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0eba899a21698363aeb4d1a2e96aff5/href">https://medium.com/media/d0eba899a21698363aeb4d1a2e96aff5/href</a></iframe><p>Here the developer experience may suffer because of loss of static typing on theme object but the user experience is considerably better. Also, a developer doesn’t need to learn API styled.button(({<strong>theme</strong>}) =&gt; ({ ...styles })) where we create a function accepting theme and returning styles. Here is a link to <a href="https://codesandbox.io/s/css-var-bfo2z">codesandbox</a>.</p><h4>React profiler matrix⚛️</h4><p><strong>CSS-in-JS way of theme switching</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*zC6DyjqY7tUeJtPXyjDlUQ.png" /><figcaption>CSS-in-JS way of theme switching</figcaption></figure><p><strong>CSS variables of theme switching</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*aN2wRhAs992PHC8P7GJTaA.png" /><figcaption>CSS variable way of theme switching</figcaption></figure><p>By seeing the above two screenshots it is very clear that using CSS variable is better than using CSS-in-JS way. A better developer experience can be achieved by a hybrid of two. Following gives you the ability for static type on theme object as theme.colors.primary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/736e9c7e77174318c8875debbd023b36/href">https://medium.com/media/736e9c7e77174318c8875debbd023b36/href</a></iframe><h4>Conclusion</h4><p>CSS-in-JS is awesome but it comes with the cost of injecting styles with every render and theme switching using ThemeContext is not performant especially if there are a large number of components on a screen. Theme switching is very performant with CSS variables. Let’s use more CSS variables to develop awesome web apps themes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7dc880462d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context Module Pattern in React]]></title>
            <link>https://vtechguys.medium.com/context-module-pattern-in-react-dd3e89d56f2d?source=rss-46d6d4053cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd3e89d56f2d</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-context]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Aniket Jha]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 17:38:58 GMT</pubDate>
            <atom:updated>2021-02-22T18:53:21.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*kUKvoIoqUnvCTbOj6XtI9A.jpeg" /></figure><p>Do you see the beast? context + hooks === 🦁 Using context and hooks together gives birth to Context Module Pattern, the magnificent beast🦁.</p><p>Let’s start by creating the context:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d0dd06cae4339d3090aa2c2d0025713/href">https://medium.com/media/4d0dd06cae4339d3090aa2c2d0025713/href</a></iframe><p>Here I prefer to split my context into state and dispatch, this enables me to consume only what my component needs. To allow our components to consume these contexts we must attach their provider in the ancestral component tree. I prefer to create a wrapper component that provides these context as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/069a5453eaf7449d9b94ad43312e84e8/href">https://medium.com/media/069a5453eaf7449d9b94ad43312e84e8/href</a></iframe><p>Now let&#39;s create custom hooks to consume these context values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/122451f4755d8aaa8a11b130c88db9f9/href">https://medium.com/media/122451f4755d8aaa8a11b130c88db9f9/href</a></iframe><p>Note that we never export context itself as we will consume context by using our custom hooks. Now that is in place we can move to implement state modifier helper functions which in combination with dispatch helps to modify state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbf027978d9f8b153a6d26541ce76f92/href">https://medium.com/media/bbf027978d9f8b153a6d26541ce76f92/href</a></iframe><p>Now all that is in place it is time we conclude our context module. Now let’s see how to use it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dac89608cd146c0abd4a2eb8f48e539e/href">https://medium.com/media/dac89608cd146c0abd4a2eb8f48e539e/href</a></iframe><p>Note that how easy it is to use context in code, we are leveraging hooks and helper functions to abstract complexity and simplify our code.</p><p><strong>Context module pattern — a beautiful magnificent beast 🦁.</strong></p><p>To see a more complex example follow this link <strong>code sandbox</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd3e89d56f2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proxy and Reflect in Javascript | Part 2]]></title>
            <link>https://vtechguys.medium.com/proxy-and-reflect-in-javascript-part-2-14328ae39675?source=rss-46d6d4053cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/14328ae39675</guid>
            <category><![CDATA[reflects]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[proxy]]></category>
            <dc:creator><![CDATA[Aniket Jha]]></dc:creator>
            <pubDate>Sun, 01 Nov 2020 10:44:09 GMT</pubDate>
            <atom:updated>2020-11-01T10:44:09.424Z</atom:updated>
            <content:encoded><![CDATA[<p>In the<em> </em><a href="https://medium.com/@vtechguys/proxy-in-javascript-part-1-ae17703a2d8c"><em>previous</em></a> post, we discussed Proxy in detail. In this post, we will build upon that knowledge and learn some more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIq9hqRQDYeWS30jCIAcZQ.jpeg" /><figcaption>Proxy and Reflect in Javascript</figcaption></figure><p>Reflect helps in the creation of Proxy and somewhat allow us to play with internal methods [[Get]] and [[Set]]. Below are some reflect methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*Ox61jW-IKJ0_x02P9qRDTA.png" /><figcaption>Some Reflect methods</figcaption></figure><p>Let us look at a code example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68d65f90d0f17cd0226aec64f25b0d4e/href">https://medium.com/media/68d65f90d0f17cd0226aec64f25b0d4e/href</a></iframe><p>Reflect allow us to call operators as functions also there is a reflect method for any proxy traps having the same name and arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbaaa1357ca608ec0711795dbfde83c2/href">https://medium.com/media/cbaaa1357ca608ec0711795dbfde83c2/href</a></iframe><p>The Reflect methods work nicely with proxy to ensure that traps output and what we expected is the same. Following is an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91ea13c8745499fba8b18c03d18cac9d/href">https://medium.com/media/91ea13c8745499fba8b18c03d18cac9d/href</a></iframe><p>We saw an example of how Reflect is useful for dealing with this Proxy gotcha. I always writereturn Reflect.get(…arguments);😎. Reflect is awesome to enhance proxy and use it correctly. More on proxy on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">MDN</a>.<br>Stay tuned for more articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14328ae39675" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proxy in JavaScript | Part 1]]></title>
            <link>https://vtechguys.medium.com/proxy-in-javascript-part-1-ae17703a2d8c?source=rss-46d6d4053cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae17703a2d8c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[proxt]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aniket Jha]]></dc:creator>
            <pubDate>Sat, 08 Aug 2020 15:12:04 GMT</pubDate>
            <atom:updated>2020-11-08T08:05:56.365Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you put a proxy for your friend in that one boring lecture and professor couldn’t tell 😂…I have. JavaScript has a similar way of applying a proxy on objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*ZRzi2Nvp3LgKnPiW_gTPsA.jpeg" /><figcaption>Proxy</figcaption></figure><p>A Proxy object wraps another object and intercepts operations on it. While intercepting operations like reading, writing properties on the object, the proxy may choose to handle these operations and modify results.</p><h4>Proxy</h4><p>Syntax: let proxy = new Proxy(target, handler);</p><p>target : the object that has to be proxied. <br>handler : the proxy configuration object, it may register traps. A trap is a handler for a particular kind of operation. By registering a trap handler it can intercept the operation and do its own thing.</p><p>If there is a trap for the operation onhandler only then the operation will be trapped and handled by proxy else operation directly occurs on the object itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ced5ecd3dc0894f9340ae2df805c6ae/href">https://medium.com/media/6ced5ecd3dc0894f9340ae2df805c6ae/href</a></iframe><p>For most of the operations on objects, there are “Internal Methods” in JavaScript that describe how operation work at a low level, what proxy trap does is that it can intercept these methods and do its own thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*PD-6SDSWaAax6EBgVeEHwA.png" /><figcaption>Proxy visualisation</figcaption></figure><p>Below we show some of the “Internal Methods” and their corresponding proxy traps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*kqnbCeffkpaP6oXpcF5-gQ.png" /><figcaption>Proxy trap and corresponding Internal method</figcaption></figure><p>Internal Methods have some rules that our traps must follow, for eg: set the trap must return true if property setting was success else false.[[GetPrototypeOf]] must always return the target’s prototype when applied on proxy as well.</p><h4>The problem statement</h4><blockquote>It is common practice to use <em>_</em> is in the beginning of property name to denote a private property. You cannot get/set/loop this property. Write a proxy to achive this.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/606d24c798360d61234c105fd0f993de/href">https://medium.com/media/606d24c798360d61234c105fd0f993de/href</a></iframe><p><strong>A “set” trap<br></strong>We will register a set trap on the handler to intercept write operation on the object.</p><p>Syntax: set(target, prop, value, receiver).</p><p>target : target object. <br>prop : property name that is being set. <br>value : the value of the property to be set. <br>receiver : the object that is utilised as in getters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0d3e75f78ef946b07485c3226cb3a2e/href">https://medium.com/media/d0d3e75f78ef946b07485c3226cb3a2e/href</a></iframe><h4>A “get” trap</h4><p>We will register a get trap to prevent direct access user._password to private property. Also, we have to ensure that isCorrectpassword works correctly as it does indirect access this._password.</p><p>Syntax: get(target, property, receiver). <br>The arguments mean the same as above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61ed3df058c26d7d3f78afc1ff73e483/href">https://medium.com/media/61ed3df058c26d7d3f78afc1ff73e483/href</a></iframe><h4>A “deleteProperty” trap</h4><p>We will register deleteProperty so that we can&#39;t delete a private property.<br>Syntax: deleteProperty(target, property)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfaefca6eeb46d023d3fc0fb3e8d73c7/href">https://medium.com/media/dfaefca6eeb46d023d3fc0fb3e8d73c7/href</a></iframe><h4>A “ownKeys” trap</h4><p>for..in, Object.keys, Object.values and other methods utilise an “Internal Method” called [[OwnPropertyKeys]] to get a list of keys. For eg:<br>Object.getOwnPropertyNames() to get a list of non-symbol keys,<br>Object.getOwnPropertySymbols() to get a list of symbol keys, <br>Object.keys() to get a list of non-symbol enumerable keys, etc.</p><p>They all call [[OwnPropertyKeys]] but tweak it a bit to return keys according to their use case. So we will register ownKeys(target) trap to return only public keys.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/528128bfb0794f55b4055a99bdc79e6d/href">https://medium.com/media/528128bfb0794f55b4055a99bdc79e6d/href</a></iframe><p><strong>Note:</strong> Our traps must follow the rules defined for “Internal Method”. The rule defined for ownKeys with Object.keys() is that it must return non-symbol enumerable keys. Look at the example below to understand this gotcha.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a73536c72b933914c7b05f9bf812a2bd/href">https://medium.com/media/a73536c72b933914c7b05f9bf812a2bd/href</a></iframe><h4>A “has” trap</h4><p>This trap work with the in operator that intercept [[hasProperty]] Internal Method. Let’s register a has(target, property) trap.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48b9233bcfaa13e4ad8b8981d90b918e/href">https://medium.com/media/48b9233bcfaa13e4ad8b8981d90b918e/href</a></iframe><h4>A “apply” trap</h4><p>Until now all examples we have seen were on objects and now we will see an example of function as target.</p><p>Syntax: apply(target, thisArgs, args). <br>thisArgs : it is the value of this <br>args : it is a list of arguments for function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/287ba345dd3f4df2d8421559756e4bb5/href">https://medium.com/media/287ba345dd3f4df2d8421559756e4bb5/href</a></iframe><h4>The End</h4><p>Now teach the Proxy you learnt here to your friend for whom you have put proxy 😂. Here is the next part of the post <a href="https://vtechguys.medium.com/proxy-and-reflect-in-javascript-part-2-14328ae39675">Part 2</a>. Stay tuned for more content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae17703a2d8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Method of primitive]]></title>
            <link>https://vtechguys.medium.com/method-of-primitive-206fbee0c5f?source=rss-46d6d4053cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/206fbee0c5f</guid>
            <category><![CDATA[primitive]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[methods]]></category>
            <dc:creator><![CDATA[Aniket Jha]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 09:16:09 GMT</pubDate>
            <atom:updated>2020-07-05T09:16:40.286Z</atom:updated>
            <content:encoded><![CDATA[<h3>Methods of primitive</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOTmBgy4HqDuNBwJZxhChw.jpeg" /></figure><p>Let’s start with a piece of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e72fcbcb095aefc3f4778f4431a2097c/href">https://medium.com/media/e72fcbcb095aefc3f4778f4431a2097c/href</a></iframe><p>The name is a primitive but we are able to access a method on it as if it were some sort of object. But we know that primitive isn’t an object. <br>What is the story here?🧐</p><p>Primitive are simple values stored in memory, those are lightweight and extremely fast. Whereas an object is a collection of the key, value pairs, it is heavy but it allows to access some utility properties associated with the object that is very useful. The javascript people faced the dilemma where they wanted to put primitive for being lightweight and fast but also wanted to allow access useful methods on primitives.</p><p>The solution the came up with was:<br><em>As soon as the engine reaches line 2 it sees that you are trying to do property access on primitive, but as primitive itself doesn’t have methods on them. It momentarily wraps the primitive value into a corresponding type wrapper object that has these methods on them and that object exposes us the properties which we can use, as soon as the method is done executing it returns the result of the operation in a new memory space and deletes this wrapper object.</em></p><h4>Constructors function</h4><p>The constructor function String, Number, Boolean is for internal use only. Languages like Java allows us to explicitly creates a wrapper object that is also possible with JavaScript but those are not recommended and are for internal use only. A lot of things can go crazy if we use those.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fec7cfdb10f4793e2da353ea3abe33ea/href">https://medium.com/media/fec7cfdb10f4793e2da353ea3abe33ea/href</a></iframe><h4>Recap with a question</h4><p>Explain the console output in strict and non-strict mode?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5923c4d9846f5018d91fe44a9f7e29d/href">https://medium.com/media/c5923c4d9846f5018d91fe44a9f7e29d/href</a></iframe><p>In strict mode on line 2, the engine sees that we are trying to create a property on internal momentarily created internal wrapper object so there occurs an error. For a non-strict mode the engine on line 2, allows you to create a property on momentarily created wrapper object but this object is thrown out of memory as soon as line 2 is done executing. On line 3 a new wrapper object is created momentarily but as this is different from previous it doesn&#39;t have thelastproperty and thus undefined is the output.</p><h4>Conclusions</h4><p>The primitive is indeed a simple value but the engine treats primitive especially if it sees there is property access on it by wrapping it in wrapper object and exposing us with useful methods and properties.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=206fbee0c5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript: Array Methods | Mutating vs Non-Mutating]]></title>
            <link>https://vtechguys.medium.com/javascript-array-methods-mutating-vs-non-mutating-8606d9b78c77?source=rss-46d6d4053cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/8606d9b78c77</guid>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[array-methods]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mutation]]></category>
            <dc:creator><![CDATA[Aniket Jha]]></dc:creator>
            <pubDate>Sun, 24 May 2020 14:08:07 GMT</pubDate>
            <atom:updated>2020-05-24T14:08:07.309Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we are going to look at a few common array operations in their mutable and non-mutable version. Add, Delete, Replace are most common operations and we will take a look at those operations. In this article, we will exploit methods like `array.map()` to produce non-mutating versions. This is not an exhaustive listing, we will keep ourselves limited to basic manipulations.</p><p><em>I will assign array to </em><em>const to show non-mutating aspect and </em><em>let as mutating. Though you can always mutate array assign to </em><em>const but I like to it that way keep for developer indication.</em></p><h3>Add: Mutating</h3><p>The easiest way to add an item to array is array.push() and array.unshift().</p><pre>// Note: using `let` here to indicate that this array will be mutated. <br>let array = [1, 2, 3, 4, 5];<br>array.push(6); // [1, 2, 3, 4, 5, 6];<br>array.unshift(10);// [10, 1, 2, 3, 4, 5, 6];</pre><p>array.push() adds an item to the end and array.unshift() adds an item to the front of the array.</p><h3>Add: Non-Mutating</h3><p>There are two ways to do so array.concat() and …array spread operator.</p><pre>// Note use `const` to indicate that this will not be mutated<br>const array1 = [1, 2, 3, 4, 5];<br>const array2 = array.concat(6); // [1, 2, 3, 4, 5, 6];</pre><pre>const array3 = [...array1, 6]; // [1, 2, 3, 4, 5, 6];<br>const array4 = [10, ...array1]; // [10, 1, 2, 3, 4, 5];</pre><p>array1.concat(item1, item2, …) the concat method will merge all items from array1 and items passed as params and create a new array with them. While the … spread operator will essentially take all items out from array and place them in a new context.</p><h3>Remove: Mutating</h3><p>There are two methods array.pop() and array.shift()</p><pre>let array = [1, 2, 3, 4, 5];<br>array.pop(); // [1, 2, 3, 4] &gt; delete from end and return deleted item<br>array.shift(); // [2, 3, 4]  &gt; delete from front and return deleted item</pre><p>array.pop() delete an item from the end and return deleted item. array.shift() delete an item from the front and return deleted item.</p><p>There is one important method to manipulate array i.e array.splice(). It mutates the array. splice() takes 2 important params, first being the starting index and second being the number of items to be removed. splice will remove items from array directly. for eg. splice(0, 2) will remove two items starting from index 0.</p><pre>let array = [1, 2, 3, 4, 5];<br>array.splice(0, 2);// [3, 4, 5];</pre><h3>Remove: Non-Mutating</h3><p>The removing or any type of filtering is done by array.filter(), the filter() is among the coolest non-mutating method on the array. It takes a function that is called over each item in the array during that it has to do some filtering where if it returns true then the item will be included in new array and return false if items has to be thrown away.</p><pre>const array1 = [1, 2, 3, 4, 5];<br>const array2 = array1.filter((item) =&gt; item !== 5); <br>// will filter any item i.e not equal to 5</pre><p>Another very important method is array.slice(). Remember this is not array.splice(), they are different array.slice() will return new array i.e its is not mutating. It is very similar to slice for how its is used. It takes 2 important params, the first is starting index where copying should begin and second is end index where copy should end, it is not inclusive. It copy items between those index and returned them in a new array.</p><pre>const array1 = [1, 2, 3, 4, 5];<br>const array2 = array1.slice(0, 2); // [1,2];<br>// if no args provided ti  will copy the whole array</pre><h3>Replace: Mutating</h3><p>Array splice method is very interesting method because not only it can remove items but also add items to the array directly. The third parameters and onwards basically mean items that need to be inserted to array.</p><pre>let array = [1, 2, 3, 4, 5];<br>array.splice(2, 1, 10, 12); // [1, 2, 10, 12, 4, 5];</pre><p>splice will remove 1 item starting index 2 and then insert 10 and 12 from the same position.</p><h3>Replace | Transform: Non-mutating</h3><p>The mighty method array.map() is very useful as it can transform array. Map method takes a function that is called on each item of the array and it must return an item that has to be put into the new array.</p><pre>const array1 = [1, 2, 3, 4, 5];<br>const array2 = array1.map((item) =&gt; {<br>  if (item === 3) {<br>    return 10;  <br>  }<br>  return item;<br>}); // [1, 2, 10, 4, 5];</pre><pre>// Map as transformation<br>const mutilpliedByTwo = array1.map((item) =&gt; item * 2); <br>// [2, 4, 6, 8, 10];</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8606d9b78c77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript | DOM — Allow to enter particular characters only]]></title>
            <link>https://vtechguys.medium.com/javascript-dom-allow-to-enter-particular-characters-only-ab9812dbe7cd?source=rss-46d6d4053cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab9812dbe7cd</guid>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[invalid-input]]></category>
            <category><![CDATA[dom]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aniket Jha]]></dc:creator>
            <pubDate>Sat, 09 May 2020 14:07:45 GMT</pubDate>
            <atom:updated>2020-05-09T14:07:45.109Z</atom:updated>
            <content:encoded><![CDATA[<h3>Javascript | DOM — Allow to enter particular characters only</h3><p>Many times we want to make validations on an input box for characters that user can type. And other characters will not be entertained in the input box.</p><blockquote><em>Question: Make a input box that accepts </em><strong><em>digits</em></strong><em> and </em><strong><em>spaces</em></strong><em> only. Also, care for copy-paste (Ctrl +V ) of invalid characters.</em></blockquote><p>The first step is to register an event on the input tag. But what event type? 🤔 We are typing characters into it so keypress the event looks fine.</p><pre>&lt;input type=&quot;text&quot; id=&quot;input&quot;/&gt;</pre><pre>const input = document.getElementById(&#39;input&#39;);<br>var currentInputValue = &#39;&#39;;<br>input.addEventListener(&#39;keypress&#39;, function inputKeypressHandler(e) {<br>    // keypress event on input box is listened here and this function is triggered<br>    // which key is pressed, keyPressed = e.which || e.keyCode; <br>    const key = e.which || e.keyCode;<br>    // key code corresponds to digits 0-9 or space then okay👍🏼<br>    // 0-9 key code is 48-57<br>    // space keycode is 32<br>    const SPACE = 32; // May be just stored somewhere<br>    const ZERO = 48;<br>    const NINE = 57;<br>    // valid digit is b/w 0-9 thus invalid will be lt 0 or gt 9<br>    const isNotValidDigit = key &lt; ZERO || key &gt; NINE;<br>    // if key is not a space or not a digit prevent this event<br>    if (key != SPACE || ( isNotValidDigit ) ) {<br>        e.preventDefault();<br>    }<br>});</pre><p>This is a pretty good solution but this doesn’t prevent paste cheats. And that is because the keypress event only records key pressed inside the input box. A better event type is required. input it runs on all input ways including copy paste and drag.</p><pre>var currentInputValue = &#39;&#39;;<br>input.addEventListener(&#39;input&#39;, function inputInputEventHandler(e) {<br>    // use target of event to get value of input<br>    const target = e.target;<br>    // we can use regex to check if current input value<br>    // is valid input<br>    const DIGITS_SPACE_REGEX = /^[0-9\s]*$/;<br>    // test if target.value or value of input box now is valid.<br>    // if value is valid then update currentInputValue <br>    // target.value else its is not value and we will<br>    // ignore this target.value and replace it with <br>    // previously valid value currentInputValue<br>    DIGITS_SPACE_REGEX.test(target.value) <br>        ? ( currentInputValue = target.value ) <br>        : ( target.value = currentInputValue );<br>});</pre><p>This solves our problem of paste but there is one problem here. Say you paste something Ctrl/Cmd + V your current cursor position will be lost and moved to starting. This must not happen and you must be able to retain cursor position.</p><pre>// Track cursor position<br>// cursor position is changed when you type something<br>const cursorState = {};<br>input.addEventListener(&#39;keydown&#39;, function inputKeydownHandler(e) {<br>    const target = e.target;<br>    // record the start and end<br>    cursorState.selectionStart = target.selectionStart;<br>    cursorState.selectionEnd = target.selectionEnd;<br>});</pre><p>now in input handler</p><pre>// modify<br>DIGITS_SPACE_REGEX.test(target.value) <br>        ? ( currentInputValue = target.value ) <br>        : ( target.value = currentInputValue );<br> // to<br> if (DIGITS_SPACE_REGEX.test(target.value)) {<br>     currentValue = target.value;<br> }<br> else {<br>    target.value = current.value;<br>    // restore cursor state<br>    target.setSelectionRange(<br>        cursorState.selectionStart,<br>        cursorState.selectionEnd<br>    );<br> }</pre><p><a href="https://codepen.io/vtechguys/pen/JjYLmQd">Demo 👨‍💻</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab9812dbe7cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Objects | “this”​]]></title>
            <link>https://vtechguys.medium.com/javascript-objects-this-b5c78516ca3b?source=rss-46d6d4053cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5c78516ca3b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[javascript-method]]></category>
            <category><![CDATA[javascript-this]]></category>
            <dc:creator><![CDATA[Aniket Jha]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 17:37:23 GMT</pubDate>
            <atom:updated>2020-09-04T15:43:52.476Z</atom:updated>
            <content:encoded><![CDATA[<p>Objects in the real world have some behaviour attached to them. For example, a user on messenger can chat, view profile etc. These behaviour are the function linked to the user object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*63m2wJocSBUv5IcJR6r35w.jpeg" /><figcaption>“this” happened</figcaption></figure><pre>const userObject = {<br>    name: &#39;Aniket&#39;,<br>    age: 22,<br>};<br>userObject.myName = function (){ // (1) way<br>    alert(&#39;myName method&#39;);<br>};<br>function myAge(){<br>    alert(&#39;myAge method&#39;);<br>}<br>userObject.myAge = myAge;<br>userObject.myName(); // alert: myName method</pre><p>Here we have created a Function expression and assigned it to `userObject.myName` property, this function as a property is called a method.</p><h3>Method shorthand</h3><p>Method shorthand exists which are declared directly on object literal itself like so:</p><pre>userObject = {<br>    myName: function (){<br>        // implemetation<br>    },<br>    myAge() {<br>        // implementation<br>    },<br>};</pre><p>`myAge` and `myName` functions are method shorthand that is directly declared on object literal. They are slightly different during inheritance. But that’s a topic for another article.</p><h3>“this” in method</h3><p>In Javascript, `this` is `dynamically scoped`. 🤔</p><h3>Dynamic Scoped</h3><p>💡A function’s `this` keyword references the `execution context` for that call and determined entirely by how the function was called.</p><p>💡`this` aware function thus can have different context each time it is called which makes it flexible and reusable. This is called Dynamic Scoping and `this` behaviour is different from other languages like Java.</p><h3>Need for “this”</h3><p>In Javascript, `this` is used to refer a object inside `function/ method` call. Like so:</p><pre>var userObject = {<br>    name: &#39;Aniket&#39;,<br>    myName(){<br>        console.log(&#39;this&#39;, this.name); // (1)<br>        console.log(&#39;object&#39;, userObject.name); // (2)<br>    }<br>};<br>userObject.myName(); // (3)<br>// used to access object ref inside method / function<br>// this Aniket <br>// object Aniket</pre><pre>var userObject2 = userObject; // (4) Assigning userObject ref<br>userObject2.name = &#39;Jane&#39;; // (5) changes name property at ref<br>userObject = null; // (6) Removed refernce to user object</pre><pre>userObject2.myName(); // (7) TypeError: Cannot read property of null</pre><p>In the above illustration, the `<em>userObject`</em> was declared and the method was created on it. The method/ function is `this` awareness and thus when called like `userObject.myName()` the function is called on `<em>userObject`</em> object and refer `this` as `userObject` object.</p><p>💡 In the above case for (3), `userObject.myName()` where myName property is called from `userObject` thus context,` this` will refer to `userObject`.</p><p>🏷️ (1) this.name gives ‘Aniket’. Here this refers to `userObject. `(2) `userObject.name` directly access name property stored on `userObject.`</p><p>🏷️ (1) `this` is used and it dynamically refers to the context from where it was called, here it is `userObject. `(2) `userObject` is directly referring to the object itself so reads directly from there.</p><p>🏷️ (1) `this.name` referred the `context(userObject)` dynamically and context were determined at point method was called. (2) userObject.name statically refer to `userObject.` It doesn’t change no matter how it is called.</p><p>💡 In the above case for (4) we assigned the `userObject reference to userObject2.` Note Objects are reference type and thus both `userObject and userObject2 refer to the same section in memory. Reference assigning for objects types is not the same as value assigning for primitive types.`</p><p>💡 In the above case for (5) we are modifying the value of property name at memory referred by userObject2. As both user object and userObject2 refer the same section of memory the value is changed for both. Confirm this by putting a console.log(userObject.name, userObject2.name) immediately after (5);</p><p>💡 In the above case for (6) we put `null` into userObject which means userObject no longer refer to object in memory. Rather refers to a null value.</p><p>💡 In above case for (7) we call `userObject2.myName()` which call `myName(`) method with context userObject2.</p><p>🏷️ (1) `this` will refer to userObject2 and thus access property name on it.(2) userObject currently holds null and thus `.myName() method/ property doesn’t exist on null`</p><p>🏷️ (1) We saw use case how `this behaves dynamically and help us to refer context.`(2) This way was unreliable and thus should not be used.</p><h3>Ways to call a function and “this” variance</h3><p>Ther are four ways a function can be called.</p><h3>Implicit way</h3><p>The way we have seen in the above illustration is called Implicit way.</p><pre>const userObject = {<br>    name: &#39;Aniket&#39;,<br>    myName() {<br>        console.log(this.name);<br>    }<br>};<br>userObject.myName(); // implict way</pre><p>myName() function is called from userObject thus the context is userObject and this points to userObject</p><h3>Bound way</h3><p>ABC of function is one way to call some function in a different context.</p><pre>function myName() { // (1)<br>    console.log(this.name);<br>}; <br>const userObject = {<br>    name: &#39;Aniket&#39;,<br>};<br>const userObject2 = {<br>    name: &#39;Jane&#39;,<br>};<br>// userObject.myName(); Error<br>// call myName function with context as userObject<br>myName.call(userObject2); // (2) Aniket<br> // call myName function with context as userObject2<br>myName.call(userObject2); // (3) Jane</pre><p>In the above illustration, we demonstrate how C (call) in ABC of functions work. (1) function myName is free and is not declared on userObject thus userObject.myName will be undefined and userObject.myName() is error as undefined is not a function. Now we want to call myName() with context as userObject and userObject2 this is done using ABC of function. ABC of functions calls our function with the context of the specified object.</p><p>A common 🤷‍♂️ problem we face with this is loosing the this binding in callbacks. Illustrated as:</p><pre>const userObject = {<br>    name: &#39;Aniket&#39;,<br>    myName(){<br>        console.log(this.name);<br>    },<br>};<br>userObject.myName(); // &#39;Aniket&#39;<br>setTimeout(userObject.myName, 1000); // undefined or Error -- depends if strict mode or not</pre><p>Here we pass our function/ method as a callback which and depending on the mode of operation output could be undefined or Error.</p><p>Consider following to understand how method call works:</p><pre>const userObject = {<br>    name: &#39;Aniket&#39;,<br>    myName(){<br>        console.log(this.name);<br>    },<br>};<br>userObject.myName(); // &#39;Aniket&#39;<br>const myName = userObject.myName; (1)<br>myName(); // undefined or Error -- depends if strict mode or not</pre><p>Steps:</p><ol><li>The dot operator retrieves the object.method property.</li><li>Then () call that function</li></ol><p>🤔 But how does this information is passed to method?</p><p>To make object.method() calls work, the dot ’.’ returns not a function ref, but a value of the special internal type called “Reference Type.”</p><p>The “Reference Type” is a “Specification Type” internally used by language itself and we cannot use it explicitly. The “Reference Type” has a triplet combination give as (base, name, strict) where</p><ul><li>base denotes the object on which function is called.</li><li>name is property name/method name.</li><li>strict is true if use strict is used.</li></ul><p>base is utilized as this inside method call.</p><p>The property userObject.myName is not a function but Reference type value.</p><pre>// Refernce type if strict mode is in effect<br>(userObject, &quot;myName&quot;, true)</pre><p>💡When () are called on Reference type, they receive full information about object userObject and set base = this = userObject.</p><p>💡Reference type is an internal type that has the purpose to pass information from . to calling ().</p><p>💡Operation like const myName = userObject.myName; ignore Reference type and takes the value of the function and pass it on to myName variable. Thus this binding is lost.</p><p>💡 The value of this is only passed correctly if the function is called directly using dot object.method().</p><p>To solve the problem faced during callback we use B(bind) of ABC of function. It creates a hardbound function and gives us reference of that function ensuring it will be called with this pointing to a specified object. const myName = userObject.myName.bind(userObject) will return a hardbound function. And setTimeout(myName, 1000); will work correctly.</p><h3>Constructor call</h3><pre>function Person(name){<br>    this.name = name;<br>};<br>// new Person(); putting &quot;new&quot; in front of function call hijack function<br>var aniket = new Person(&#39;Aniket&#39;); <br>aniket.name; // Aniket</pre><p>Steps:</p><ul><li>Create a brand new object</li><li>Link that object to another object</li><li>Call function with “this” set to the new object</li><li>If the function doesn’t return anything “this” is implicitly returned.</li></ul><p>The function gets hijacked with the new keyword in front while calling. In case 4 steps are always followed. A brand new object is created out of thin air and “this” points to that object inside the function call</p><h3>Global/ Default</h3><pre>function myName(){<br>    console.log(this.name);<br>}<br>myName(); // (1)</pre><p>myName is this aware function and called but in (1) call it without specifying context and thus js try to rescue you by referring global object as the this value for the function. The default behaviour of referring global object doesn’t work in strict mode instead this is equal to undefined and thus Error as undefined.name is not a property.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5c78516ca3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Objects]]></title>
            <link>https://vtechguys.medium.com/javascript-objects-3f5c14e0521c?source=rss-46d6d4053cee------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f5c14e0521c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[spread-operator]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[newbie]]></category>
            <category><![CDATA[js-object]]></category>
            <dc:creator><![CDATA[Aniket Jha]]></dc:creator>
            <pubDate>Fri, 03 Apr 2020 07:58:44 GMT</pubDate>
            <atom:updated>2020-04-03T07:58:44.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*RZKFXpLm3pYTptIhI1BJ5Q.png" /></figure><p>There are a total of eight data types in Javascript. Seven of them are ‘primitive’ and other is ‘object’. Primitive is something that contains a single thing (string or number or others). Objects are collection of key value pair.</p><h3>Creating an object</h3><pre>// Contructor syntax</pre><pre>const objConstructor = new Object();</pre><pre>// Literal syntax</pre><pre>const objLiteral = {};</pre><p>There are two ways of creating an object in javascript. One is object constructor syntax and other is object literal syntax. The common way of creating an object is through literal syntax.</p><h3>Properties</h3><h4>Adding properties</h4><pre>// Immedaitely adding properties</pre><pre>const userObject = { // creating an object</pre><pre>name: &#39;Aniket&#39;, // added property &#39;name&#39; with value &#39;aniket&#39;</pre><pre>age: 20, // property &#39;age&#39; with value 20</pre><pre>&quot;like orange&quot;: true // multiword as property</pre><pre>};</pre><pre>// Adding property later</pre><pre>userObject.like = &#39;Apple&#39;;</pre><pre>// Another multiword as key</pre><pre>// Multiword keys needs to be set/accessed using square bracket syntax</pre><pre>userObject[&#39;like apple&#39;] = true;</pre><h4>Deleting property</h4><pre>delete userObject.like;</pre><pre>delete userObject[&#39;like apple&#39;];</pre><h4>Accessing Properties</h4><pre>userObject.name; // Aniket</pre><pre>userObject.age; // 20</pre><pre>userObject.like orange // error occured</pre><pre>// multiword key can be accessed using square bracket syntax</pre><pre>userObject[&#39;like orange&#39;]; // true</pre><h3>Computed properties</h3><p>The properties can be some computed values and can be used inside literal like so:</p><pre>const language = prompt(&#39;which language you like ?&#39;, &#39;javascript&#39;);</pre><pre>const likesObject = {</pre><pre>[language]: &#39;you are the best&#39;</pre><pre>// language is computed from value of variable langauge</pre><pre>};</pre><pre>alert(likesObject.javascript);</pre><pre>// if langauge == &#39;javascript&#39;  then alert &#39;you are the best&#39; :p</pre><h3>Properties shorthand</h3><pre>const id = 1234;</pre><pre>const userObject = {</pre><pre>id, // same as id: id</pre><pre>// it saved us of writing extra ;)</pre><pre>};</pre><h3>Property limitations</h3><p>The property name can be a string or symbol. Other types are converted to a string. For example, we try to make the property as 2 (number) it gets converted to “2”.</p><pre>const object = {</pre><pre>2: &#39;two&#39;,</pre><pre>};</pre><pre>alert(object[&#39;2&#39;]); // two</pre><pre>alert(object[2]); // two (excat same property)</pre><p>Reserved keyword of language can be used as properties, for example, let, for, the return can be used as property names. Objects have a special property __proto__ which can is reserved and should not be directly modified.</p><pre>// Reserved words can be used</pre><pre>const object = {</pre><pre>let: &#39;let&#39;,</pre><pre>for: &#39;for&#39;,</pre><pre>return: &#39;return&#39;,</pre><pre>};</pre><pre>alert(object.let);</pre><pre>alert(object.for);</pre><pre>alert(object.return);</pre><pre>// __proto__ is special reserved property on a object</pre><pre>// it is a object datatype, should not be modified directly</pre><h3>Property existence</h3><p>Accessing a non-existing property on object results in undefined but it is to note that the value of some property can be undefined also.</p><pre>const userObject = {</pre><pre>propertyExist: undefined,</pre><pre>};</pre><pre>userObject.nonExistingProperty; // undefined</pre><pre>userObject.propertyExist; // undefined</pre><p>So is there a way to know if property physically exists on the object? Yes, in the keyword is used in such scenarios.</p><pre>const userObject = {</pre><pre>propertyExist: undefined, // intentionaly put as undefined</pre><pre>};</pre><pre>userObject.nonExistingProperty; // undefined</pre><pre>&#39;nonExistingProperty&#39; in userObject; // false</pre><pre>userObject.propertyExist; // undefined</pre><pre>&#39;propertyExist&#39; in userObject; // true</pre><p>Good practice: the value of the property should never be undefined instead, use null.</p><h3>Ordered keys</h3><p>Keys on the object are sorted in a special fashion. Integer keys are sorted and others appear in order of creation.</p><pre>// integer keys</pre><pre>const rollName = {</pre><pre>&#39;40&#39;: &#39;john&#39;</pre><pre>&#39;20&#39;: &#39;aniket&#39;,</pre><pre>&#39;21&#39;: &#39;albert&#39;,</pre><pre>};</pre><pre>for(let key in rollName){</pre><pre>console.log(key, rollName[key]); // 20 aniket 21 albert 40 john</pre><pre>}</pre><pre>// string key</pre><pre>const nameRoll = {</pre><pre>john: 40,</pre><pre>aniket: 20,</pre><pre>albert: 21</pre><pre>};</pre><pre>for(let key in nameRoll){</pre><pre>console.log(key, nameRoll[key]); // john 40 aniket 20 albert 21</pre><pre>}</pre><h3>By Reference</h3><p>Objects are reference type. In the following example imagine userObject as a bucket that refernces/points to a store/section in memorary which holds the object itself.;</p><pre>const userObject = {};</pre><pre>// variable userObject ----&gt; store/section of memorary which holds // {}</pre><h4>Copying an object</h4><p>An object is copied by reference, not value or duplicated. This can be seen in the following example where user reference is copied to the admin variable bucket. And when name property of admin is modified the property value of name on user also changes, this indicates that both refer to the same location in memory.</p><pre>const user = {</pre><pre>name: &#39;Aniket&#39;</pre><pre>};</pre><pre>const admin = user;</pre><pre>admin.name = &#39;John&#39;;</pre><pre>user.name; // &#39;John&#39; ? refer to same object thus got modified</pre><pre>admin.name; // &#39;John&#39;</pre><pre>// also</pre><pre>alert(admin === user); // true : same reference</pre><p>🤔 so reassigning doesn’t copy object value but its reference. But what if I need to duplicate or clone the object into a new variable.</p><pre>const user = {</pre><pre>name: &#39;Aniket&#39;,</pre><pre>age: 20,</pre><pre>};</pre><pre>/// solution 1</pre><pre>// adding keys one by one in a for...in loop</pre><pre>const admin = {};</pre><pre>for(let key in user){</pre><pre>admin.key = user.key;</pre><pre>}</pre><pre>// solution 2</pre><pre>const admin = Object.assign({}, user);</pre><pre>// solution 3</pre><pre>const admin = { ...user };</pre><p>Solution 1: It is adding property one by one in a loop.</p><p>Solution 2: This is something important Object.assign(destObject, [srcObj1, srcObj2, ...]). The Object.assign takes a destObject object onto which properties of srcObj1, srcObj2 and many others are copied.</p><p>Solution 3: { ...obj } the ...obj is spread syntax to spread properties of obj, it is spread on { } object.</p><h3>The End</h3><p>The Object are very important in javascript, it penetrates every aspect of language. In future, we will look some more javascript stuff stay tuned. 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f5c14e0521c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>