<?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 Eduard Hayrapetyan on Medium]]></title>
        <description><![CDATA[Stories by Eduard Hayrapetyan on Medium]]></description>
        <link>https://medium.com/@edhayrapetyan?source=rss-daf5761afa02------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Nddk2GD9LCjwJLS3TO3l0A.png</url>
            <title>Stories by Eduard Hayrapetyan on Medium</title>
            <link>https://medium.com/@edhayrapetyan?source=rss-daf5761afa02------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 23:11:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edhayrapetyan/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[JavaScript ES2021 (ES12) New Features]]></title>
            <link>https://edhayrapetyan.medium.com/javascript-es2021-es12-new-features-12650df37dc0?source=rss-daf5761afa02------2</link>
            <guid isPermaLink="false">https://medium.com/p/12650df37dc0</guid>
            <category><![CDATA[ecmascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Eduard Hayrapetyan]]></dc:creator>
            <pubDate>Sat, 09 Jan 2021 19:06:52 GMT</pubDate>
            <atom:updated>2021-01-09T19:06:52.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*no_ccpi6pVSODp_fcn4-5A.jpeg" /></figure><p>The new version of ECMAScript, ES2021 is expected to be released in June 2021. What new features can we expect from the new release? This article covers some of the features in the upcoming release, and how we can put them to use.</p><h3>List of the new features discussed in this article</h3><ul><li>String.prototype.replaceAll</li><li>Promise.any</li><li>Logical Operators and Assignment Expressions</li><li>Numeric Separators</li><li>Intl.ListFormat</li><li>dateStyle and timeStyle options for Intl.DateTimeFormat</li></ul><h3>String.prototype.replaceAll</h3><p>In JavaScript, <strong>replace()</strong> method only replaces the first instance of a pattern in a string. If we want to replace all the matches of a pattern in a string, the only way to achieve that is by using global regexp.</p><p>The suggested method <strong>replaceAll()</strong> returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a regular expression, and the replacement can be a string or a function that gets executed for each match.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2615ab0788a815862875ac795aad6c0e/href">https://medium.com/media/2615ab0788a815862875ac795aad6c0e/href</a></iframe><p>This method also comes with a performance improvement as it uses string comparisons instead of regular expression matching.</p><h3><strong>Promise.any()</strong></h3><p>The next cool feature called promise.any().It returns a value, as soon as it hits the first resolved promise from the list/array of promises. If all the promises are rejected then it will throw an aggregated error message.</p><p>It is different from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race"><strong>Promise.race()</strong></a><strong> </strong>as that method ,once one of the given promises either resolves or rejects.</p><p>Even though a promise is rejected earlier than a resolved promise, <strong>Promise.any() </strong>will return the first resolved promise</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f132c283078fe3d57fe6bccb76ded752/href">https://medium.com/media/f132c283078fe3d57fe6bccb76ded752/href</a></iframe><p>When all the promises are rejected, AggregateError is thrown.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3aa47ae81112bab6279e2691356eed96/href">https://medium.com/media/3aa47ae81112bab6279e2691356eed96/href</a></iframe><h3>Logical Operators and Assignment Expressions</h3><p>With ES2021 we will be able to combine Logical Operators (&amp;&amp;, || and ??) with Assignment Expression (=) similarly to how it&#39;s already possible to do in Ruby.</p><p>If you skipped on ES2020 you may not be aware of ?? which is the <strong>nullish coalescing</strong> operator. Let&#39;s look at an example:</p><pre>const a = null ?? &#39;test&#39;;<br>// &#39;test&#39;<br>const b = 0 ?? &#39;test&#39;;<br>// 0</pre><p>The <strong>nullish coalescing</strong> operator returns the <em>right</em> hand-side when the left-hand-side is null or undefined, otherwise it returns the <em>left</em> hand-side. In the first example the left-hand-side was null thus it returned the right-hand-side while on the second example it returned the left-hand-side because it was neither null nor undefined.</p><p>Moving back to ES2021 stuff, in JavaScript we already have many <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#Assignment_operators">assignment opeartors</a> like the following example:</p><pre>let a = 0;<br>a +=2;<br>// 2</pre><p>But with this new proposal we will be able to do the following:</p><pre>a ||= b;<br>// equivalent to a = a || b<br><br>c &amp;&amp;= d;<br>// equivalent to c = c &amp;&amp; d<br><br>e ??= f;<br>// equivalent to e = e ?? f</pre><p>Let’s go over each one by one:</p><ul><li>a ||= b will return a if a is a truthy value, or b if a is falsy</li><li>c &amp;&amp;= d will return d if both c and d are truthy, or c otherwise</li><li>e ??= f will return f if e is null or undefined otherwise it will return e</li></ul><h3>Numeric Separators</h3><p>The introduction of Numeric Separators will make it easier to read numeric values by using the _ (underscore) character to provide a separation between groups of digits.</p><p>Let’s look at more examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/389f911481e12f11d15a8a44fe6a7fae/href">https://medium.com/media/389f911481e12f11d15a8a44fe6a7fae/href</a></iframe><h3>Intl.ListFormat</h3><p>The Intl.ListFormat object is a constructor for objects that enable language-sensitive list formatting.</p><p>Looking at an example is easier than explaining it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f930de3eafd2d78071c8169d3ffd7973/href">https://medium.com/media/f930de3eafd2d78071c8169d3ffd7973/href</a></iframe><p>You are not limited to English, let’s try with a few different languages:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/586213d433c15134ea837f2e989d749e/href">https://medium.com/media/586213d433c15134ea837f2e989d749e/href</a></iframe><h3>dateStyle and timeStyle options for Intl.DateTimeFormat</h3><p>We can use dateStyle and timeStyle to request a locale-specific date and time of a given length.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80d30c8f7031850e5f94f548194fa6c9/href">https://medium.com/media/80d30c8f7031850e5f94f548194fa6c9/href</a></iframe><p>You can pass whatever locale you want and you can also pass both dateStyle and timeStyle options at the same time, choosing between the three options of &#39;short&#39;, &#39;medium&#39;, and &#39;long&#39; that best suit your needs.Also you can achieve this with fantastic JS library called <a href="https://momentjs.com/"><strong>moment.js</strong></a></p><h3>Conclusion</h3><p>Every year since 2015, JavaScript has been receiving constant yearly updates to its specification with new interesting features added.For those of you who don’t know, there are 4 stages in the proposal process, with the 4th one being the last one which marks the proposal as finished. Thanks for reading , as a developer, it’s important to stay updated with the new specs of a language:)</p><h3>References</h3><p><a href="https://tc39.es/ecma262/">ECMAScript® 2026 Language Specification</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6VYpMxA4Q1k%3Fstart%3D19%26feature%3Doembed%26start%3D19&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6VYpMxA4Q1k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6VYpMxA4Q1k%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a2b2a03ac06d620b71a7dd067743541/href">https://medium.com/media/9a2b2a03ac06d620b71a7dd067743541/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12650df37dc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Clean Coding Best Practices]]></title>
            <link>https://medium.com/preezma/javascript-clean-coding-best-practices-c6adb8e3e4c8?source=rss-daf5761afa02------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6adb8e3e4c8</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[maintainability]]></category>
            <dc:creator><![CDATA[Eduard Hayrapetyan]]></dc:creator>
            <pubDate>Thu, 20 Aug 2020 18:12:32 GMT</pubDate>
            <atom:updated>2020-09-10T06:57:26.820Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“Even bad code can function. But if the code isn’t clean, it can bring a development organization to its knees.” — Robert C. Martin (Uncle Bob)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*goIqmk0iANVP3USYCIo5sA.jpeg" /></figure><h3>Overview</h3><p><em>First of all, what does clean coding mean</em>? Clean coding means that in the first place you write code for your later self and for your co-workers and not for the machine.</p><p>Good code is easy to understand and maintain. It achieves the three Rs of Software Architecture: Refactorability Reusability and Readability. All this makes sharing and reusing components between projects, an absolute must. So lets dive deeper and look through useful tips for writing better code.😊</p><h3>Variables</h3><h4>Use intention-revealing names and don’t worry if you have long variable names instead of saving a few keyboard strokes.</h4><p>Make your variable names easy to pronounce, because for the human mind it takes less effort to process.</p><pre>//Bad<br>cosnt ddmmyyyy = new Date();</pre><pre>//Good<br>const date = new Date();</pre><h3>Searchable Variable Names</h3><p>It’s important that the code we do write is readable and searchable, by not naming variables that end up being meaningful for understanding our program.Variable names should help explain and give context to what is happening in the code. Someone new to this code should be able to have a loose understanding of what is happening. Use verbs. An example of a Boolean variable could start with is…, and examples of functions could be action verbs.</p><h3>Don’t add unneeded context</h3><p>If your class/object name tells you something, don’t repeat that in your variable name.</p><pre><strong>// BAD</strong><br>const car = {<br>  carMake: &quot;BMW&quot;,<br>  carModel: 5,<br>  carColor: &quot;Black&quot;<br>};<br><br>function paintCar(car) {<br>  car.carColor = &quot;Red&quot;;<br>}</pre><pre>}<strong>// GOOD<br></strong>const car = {<br>  make: &quot;BMW&quot;,<br>  model: 5,<br>  color: &quot;Blue&quot;<br>};<br><br>function paintCar(car) {<br>  car.color = &quot;Red&quot;;<br>}</pre><h3>Use Strong Type Checks</h3><p>Use === instead of == . This would help you avoid all sorts of unnecessary problems later on. If not handled properly, it can dramatically affect the program logic.</p><pre>0 == false // true<br>0 === false // false<br>2 == &quot;2&quot; // true<br>2 === &quot;2&quot; // false</pre><h3>Functions</h3><p><em>Functions should do one thing. They should do it well. They should do it only. — Robert C. Martin (Uncle Bob)</em></p><h3>Function arguments (2 or fewer ideally)</h3><p>Limiting the amount of function parameters is incredibly important because it makes testing your function easier. Having more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument.</p><p>One or two arguments is the ideal case, and three should be avoided if possible. Anything more than that should be consolidated. Usually, if you have more than two arguments then your function is trying to do too much. In cases where it’s not, most of the time a higher-level object will suffice as an argument.</p><p>To make it obvious what properties the function expects, you can use the ES2015/ES6 destructuring syntax. This has a few advantages:</p><ol><li>When someone looks at the function signature, it’s immediately clear what properties are being used.</li><li>It can be used to simulate named parameters.</li><li>Destructuring also clones the specified primitive values of the argument object passed into the function. This can help prevent side effects. Note: objects and arrays that are destructured from the argument object are NOT cloned.</li><li>Linters can warn you about unused properties, which would be impossible without destructuring.</li></ol><p>Bad:</p><pre>function createMenu(title, body, buttonText, cancellable) {<br>  // ...<br>}</pre><pre>createMenu(&quot;Foo&quot;, &quot;Bar&quot;, &quot;Baz&quot;, true);</pre><p>Good:</p><pre>function createMenu({ title, body, buttonText, cancellable }) {<br>  // ...<br>}</pre><pre>createMenu({<br>  title: &quot;Foo&quot;,<br>  body: &quot;Bar&quot;,<br>  buttonText: &quot;Baz&quot;,<br>  cancellable: true<br>});</pre><h3>Functions should do one thing</h3><p>This is by far the most important rule in software engineering. When functions do more than one thing, they are harder to compose, test, and reason about. When you can isolate a function to just one action, it can be refactored easily and your code will read much cleaner. If you take nothing else away from this guide other than this, you’ll be ahead of many developers.</p><p>Bad:</p><pre>function emailClients(clients) {<br>  clients.forEach(client =&gt; {<br>    const clientRecord = database.lookup(client);<br>    if (clientRecord.isActive()) {<br>      email(client);<br>    }<br>  });<br>}</pre><p>Good:</p><pre>function emailActiveClients(clients) {<br>  clients.filter(isActiveClient).forEach(email);<br>}</pre><pre>function isActiveClient(client) {<br>  const clientRecord = database.lookup(client);<br>  return clientRecord.isActive();<br>}</pre><h3>Function names should say what they do</h3><p>A function name should be a verb or a verb phrase, and it needs to communicate its intent, as well as the order and intent of the arguments.</p><p>Bad:</p><pre>function addToDate(date, month) {<br>  // ...<br>}</pre><pre>const date = new Date();</pre><pre>// It&#39;s hard to tell from the function name what is added<br>addToDate(date, 1);</pre><p>Good:</p><pre>function addMonthToDate(month, date) {<br>  // ...<br>}</pre><pre>const date = new Date();<br>addMonthToDate(1, date);</pre><h3>Don’t write to global functions</h3><p>Globals is a bad practice in JavaScript because you could clash with another library, let’s think about an example: what if you wanted to extend JavaScript’s native Array method to have a diff method that could show the difference between two arrays? You could write your new function to the Array.prototype, but it could clash with another library that tried to do the same thing. What if that other library was just using diff to find the difference between the first and last elements of an array? This is why it would be much better to just use ES2015/ES6 classes and simply extend the Array global.</p><p>Bad:</p><pre>Array.prototype.diff = function diff(comparisonArray) {<br>  const hash = new Set(comparisonArray);<br>  return this.filter(elem =&gt; !hash.has(elem));<br>};</pre><p>Good:</p><pre>class SuperArray extends Array {<br>  diff(comparisonArray) {<br>    const hash = new Set(comparisonArray);<br>    return this.filter(elem =&gt; !hash.has(elem));<br>  }<br>}</pre><h3>Encapsulate conditionals</h3><p>Bad:</p><pre>if (fsm.state === &quot;fetching&quot; &amp;&amp; isEmpty(listNode)) {<br>  // ...<br>}</pre><p>Good:</p><pre>function shouldShowSpinner(fsm, listNode) {<br>  return fsm.state === &quot;fetching&quot; &amp;&amp; isEmpty(listNode);<br>}</pre><pre>if (shouldShowSpinner(fsmInstance, listNodeInstance)) {<br>  // ...<br>}</pre><h3>Avoid negative conditionals</h3><p>Bad:</p><pre>function isDOMNodeNotPresent(node) {<br>  // ...<br>}</pre><pre>if (!isDOMNodeNotPresent(node)) {<br>  // ...<br>}</pre><p>Good:</p><pre>function isDOMNodePresent(node) {<br>  // ...<br>}</pre><pre>if (isDOMNodePresent(node)) {<br>  // ...<br>}</pre><h3>Avoid conditionals</h3><p>This seems like an impossible task. Upon first hearing this, most people say, “how am I supposed to do anything without an if statement?&quot; The answer is that you can use polymorphism to achieve the same task in many cases. The second question is usually, &quot;well that&#39;s great but why would I want to do that?&quot; The answer is a previous clean code concept we learned: a function should only do one thing. When you have classes and functions that have if statements, you are telling your user that your function does more than one thing. Remember, just do one thing.</p><p>Bad:</p><pre>class Airplane {<br>  // ...<br>  getCruisingAltitude() {<br>    switch (this.type) {<br>      case &quot;777&quot;:<br>        return this.getMaxAltitude() - this.getPassengerCount();<br>      case &quot;Air Force One&quot;:<br>        return this.getMaxAltitude();<br>      case &quot;Cessna&quot;:<br>        return this.getMaxAltitude() - this.getFuelExpenditure();<br>    }<br>  }<br>}</pre><p>Good:</p><pre>class Airplane {<br>  // ...<br>}</pre><pre>class Boeing777 extends Airplane {<br>  // ...<br>  getCruisingAltitude() {<br>    return this.getMaxAltitude() - this.getPassengerCount();<br>  }<br>}</pre><pre>class AirForceOne extends Airplane {<br>  // ...<br>  getCruisingAltitude() {<br>    return this.getMaxAltitude();<br>  }<br>}</pre><pre>class Cessna extends Airplane {<br>  // ...<br>  getCruisingAltitude() {<br>    return this.getMaxAltitude() - this.getFuelExpenditure();<br>  }<br>}</pre><h3>Avoid type-checking</h3><p>JavaScript is untyped, which means your functions can take any type of argument. Sometimes you are bitten by this freedom and it becomes tempting to do type-checking in your functions. There are many ways to avoid having to do this. The first thing to consider is consistent APIs.</p><p>Bad:</p><pre>function travelToTexas(vehicle) {<br>  if (vehicle instanceof Bicycle) {<br>    vehicle.pedal(this.currentLocation, new Location(&quot;texas&quot;));<br>  } else if (vehicle instanceof Car) {<br>    vehicle.drive(this.currentLocation, new Location(&quot;texas&quot;));<br>  }<br>}</pre><p>Good:</p><pre>function travelToTexas(vehicle) {<br>  vehicle.move(this.currentLocation, new Location(&quot;texas&quot;));<br>}</pre><p>If you are working with basic primitive values like strings and integers, and you can’t use polymorphism but you still feel the need to type-check, you should consider using TypeScript. The problem with manually type-checking normal JavaScript is that doing it well requires so much extra verbiage that the faux “type-safety” you get doesn’t make up for the lost readability. Keep your JavaScript clean, write good tests, and have good code reviews.</p><p>Bad:</p><pre>function combine(val1, val2) {<br>  if (<br>    (typeof val1 === &quot;number&quot; &amp;&amp; typeof val2 === &quot;number&quot;) ||<br>    (typeof val1 === &quot;string&quot; &amp;&amp; typeof val2 === &quot;string&quot;)<br>  ) {<br>    return val1 + val2;<br>  }</pre><pre>  throw new Error(&quot;Must be of type String or Number&quot;);<br>}</pre><p>Good:</p><pre>function combine(val1, val2) {<br>  return val1 + val2;<br>}</pre><h3>Remove dead code</h3><p>Dead code is just as bad as duplicate code. There’s no reason to keep it in your codebase. If it’s not being called, get rid of it! It will still be safe in your version history if you still need it.</p><p>Bad:</p><pre>function oldRequestModule(url) {<br>  // ...<br>}</pre><pre>function newRequestModule(url) {<br>  // ...<br>}</pre><pre>const req = newRequestModule;<br>inventoryTracker(&quot;apples&quot;, req, &quot;www.inventory-awesome.io&quot;);</pre><p>Good:</p><pre>function newRequestModule(url) {<br>  // ...<br>}</pre><pre>const req = newRequestModule;<br>inventoryTracker(&quot;apples&quot;, req, &quot;www.inventory-awesome.io&quot;);</pre><h3>Classes</h3><h3>Prefer ES2015/ES6 classes over ES5 plain functions</h3><p>It’s very difficult to get readable class inheritance, construction, and method definitions for classical ES5 classes. If you need inheritance (and be aware that you might not), then prefer ES2015/ES6 classes. However, prefer small functions over classes until you find yourself needing larger and more complex objects.</p><p>Bad:</p><pre>const Animal = function(age) {<br>  if (!(this instanceof Animal)) {<br>    throw new Error(&quot;Instantiate Animal with `new`&quot;);<br>  }</pre><pre>  this.age = age;<br>};</pre><pre>Animal.prototype.move = function move() {};</pre><pre>const Mammal = function(age, furColor) {<br>  if (!(this instanceof Mammal)) {<br>    throw new Error(&quot;Instantiate Mammal with `new`&quot;);<br>  }</pre><pre>  Animal.call(this, age);<br>  this.furColor = furColor;<br>};</pre><pre>Mammal.prototype = Object.create(Animal.prototype);<br>Mammal.prototype.constructor = Mammal;<br>Mammal.prototype.liveBirth = function liveBirth() {};</pre><pre>const Human = function(age, furColor, languageSpoken) {<br>  if (!(this instanceof Human)) {<br>    throw new Error(&quot;Instantiate Human with `new`&quot;);<br>  }</pre><pre>  Mammal.call(this, age, furColor);<br>  this.languageSpoken = languageSpoken;<br>};</pre><pre>Human.prototype = Object.create(Mammal.prototype);<br>Human.prototype.constructor = Human;<br>Human.prototype.speak = function speak() {};</pre><p>Good:</p><pre>class Animal {<br>  constructor(age) {<br>    this.age = age;<br>  }</pre><pre>  move() {<br>    /* ... */<br>  }<br>}</pre><pre>class Mammal extends Animal {<br>  constructor(age, furColor) {<br>    super(age);<br>    this.furColor = furColor;<br>  }</pre><pre>  liveBirth() {<br>    /* ... */<br>  }<br>}</pre><pre>class Human extends Mammal {<br>  constructor(age, furColor, languageSpoken) {<br>    super(age, furColor);<br>    this.languageSpoken = languageSpoken;<br>  }</pre><pre>  speak() {<br>    /* ... */<br>  }<br>}</pre><h3>Prefer composition over inheritance</h3><p>As stated famously in <a href="https://en.wikipedia.org/wiki/Design_Patterns"><em>Design Patterns</em></a> by the Gang of Four, you should prefer composition over inheritance where you can. There are lots of good reasons to use inheritance and lots of good reasons to use composition. The main point for this maxim is that if your mind instinctively goes for inheritance, try to think if composition could model your problem better. In some cases it can.</p><p>You might be wondering then, “when should I use inheritance?” It depends on your problem at hand, but this is a decent list of when inheritance makes more sense than composition:</p><ol><li>Your inheritance represents an “is-a” relationship and not a “has-a” relationship (Human-&gt;Animal vs. User-&gt;UserDetails).</li><li>You can reuse code from the base classes (Humans can move like all animals).</li><li>You want to make global changes to derived classes by changing a base class. (Change the caloric expenditure of all animals when they move).</li></ol><p>Bad:</p><pre>class Employee {<br>  constructor(name, email) {<br>    this.name = name;<br>    this.email = email;<br>  }</pre><pre>  // ...<br>}</pre><pre>// Bad because Employees &quot;have&quot; tax data. EmployeeTaxData is not a type of Employee<br>class EmployeeTaxData extends Employee {<br>  constructor(ssn, salary) {<br>    super();<br>    this.ssn = ssn;<br>    this.salary = salary;<br>  }</pre><pre>  // ...<br>}</pre><p>Good:</p><pre>class EmployeeTaxData {<br>  constructor(ssn, salary) {<br>    this.ssn = ssn;<br>    this.salary = salary;<br>  }</pre><pre>  // ...<br>}</pre><pre>class Employee {<br>  constructor(name, email) {<br>    this.name = name;<br>    this.email = email;<br>  }</pre><pre>  setTaxData(ssn, salary) {<br>    this.taxData = new EmployeeTaxData(ssn, salary);<br>  }<br>  // ...<br>}</pre><h3>Concurrency</h3><h3>Use Promises, not callbacks</h3><p>Callbacks aren’t clean, and they cause excessive amounts of nesting. With ES2015/ES6, Promises are a built-in global type. Use them!</p><p>Bad:</p><pre>import { get } from &quot;request&quot;;<br>import { writeFile } from &quot;fs&quot;;</pre><pre>get(<br>  &quot;https://en.wikipedia.org/wiki/Robert_Cecil_Martin&quot;,<br>  (requestErr, response, body) =&gt; {<br>    if (requestErr) {<br>      console.error(requestErr);<br>    } else {<br>      writeFile(&quot;article.html&quot;, body, writeErr =&gt; {<br>        if (writeErr) {<br>          console.error(writeErr);<br>        } else {<br>          console.log(&quot;File written&quot;);<br>        }<br>      });<br>    }<br>  }<br>);</pre><p>Good:</p><pre>import { get } from &quot;request-promise&quot;;<br>import { writeFile } from &quot;fs-extra&quot;;</pre><pre>get(&quot;https://en.wikipedia.org/wiki/Robert_Cecil_Martin&quot;)<br>  .then(body =&gt; {<br>    return writeFile(&quot;article.html&quot;, body);<br>  })<br>  .then(() =&gt; {<br>    console.log(&quot;File written&quot;);<br>  })<br>  .catch(err =&gt; {<br>    console.error(err);<br>  });</pre><h3>Async/Await are even cleaner than Promises</h3><p>Promises are a very clean alternative to callbacks, but ES2017/ES8 brings async and await which offer an even cleaner solution. All you need is a function that is prefixed in an async keyword, and then you can write your logic imperatively without a then chain of functions. Use this if you can take advantage of ES2017/ES8 features today!</p><p>Bad:</p><pre>import { get } from &quot;request-promise&quot;;<br>import { writeFile } from &quot;fs-extra&quot;;</pre><pre>get(&quot;https://en.wikipedia.org/wiki/Robert_Cecil_Martin&quot;)<br>  .then(body =&gt; {<br>    return writeFile(&quot;article.html&quot;, body);<br>  })<br>  .then(() =&gt; {<br>    console.log(&quot;File written&quot;);<br>  })<br>  .catch(err =&gt; {<br>    console.error(err);<br>  });</pre><p>Good:</p><pre>import { get } from &quot;request-promise&quot;;<br>import { writeFile } from &quot;fs-extra&quot;;</pre><pre>async function getCleanCodeArticle() {<br>  try {<br>    const body = await get(<br>      &quot;https://en.wikipedia.org/wiki/Robert_Cecil_Martin&quot;<br>    );<br>    await writeFile(&quot;article.html&quot;, body);<br>    console.log(&quot;File written&quot;);<br>  } catch (err) {<br>    console.error(err);<br>  }<br>}</pre><pre>getCleanCodeArticle()</pre><h3>Error Handling</h3><p>Thrown errors are a good thing! They mean the runtime has successfully identified when something in your program has gone wrong and it’s letting you know by stopping function execution on the current stack.</p><h3>Don’t ignore caught errors</h3><p>Doing nothing with a caught error doesn’t give you the ability to ever fix or react to said error. Logging the error to the console (console.log) isn&#39;t much better as often it can get lost in a sea of things printed to the console. If you wrap any bit of code in a try/catch it means you think an error may occur there and therefore you should have a plan, or create a code path, for when it occurs.</p><p>Bad:</p><pre>try {<br>  functionThatMightThrow();<br>} catch (error) {<br>  console.log(error);<br>}</pre><p>Good:</p><pre>try {<br>  functionThatMightThrow();<br>} catch (error) {<br>  // One option (more noisy than console.log):<br>  console.error(error);<br>  // Another option:<br>  notifyUserOfError(error);<br>  // Another option:<br>  reportErrorToService(error);<br>  // OR do all three!<br>}</pre><h3>Formatting</h3><p>Formatting is subjective. Like many rules herein, there is no hard and fast rule that you must follow. The main point is DO NOT ARGUE over formatting. There are <a href="https://standardjs.com/rules.html">tons of tools</a> to automate this.</p><p>For things that don’t fall under the purview of automatic formatting (indentation, tabs vs. spaces, double vs. single quotes, etc.) look here for some guidance.</p><h3>Conclusion</h3><p>If you ❤️ this article, click the clap 👏 see you in the next article.</p><p>In general, you should do your best not to repeat yourself, meaning you shouldn’t write duplicate code.I know that there are many other tips, tricks and best practices, so if you have anything to add or if you have any feedback or corrections to the ones that I have shared, please add a comment.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7EmboKQH8lM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7EmboKQH8lM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7EmboKQH8lM%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e944856974efd49b22206a88166e108e/href">https://medium.com/media/e944856974efd49b22206a88166e108e/href</a></iframe><ul><li><a href="https://code.google.com/archive/p/jslibs/wikis/JavascriptTips.wiki">Code</a></li><li><a href="https://medium.com/javascript-in-plain-english/5-best-practices-for-writing-clean-javascript-be366adb2859">5 Best Practices for writing clean JavaScript</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6adb8e3e4c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preezma/javascript-clean-coding-best-practices-c6adb8e3e4c8">JavaScript Clean Coding Best Practices</a> was originally published in <a href="https://medium.com/preezma">Preezma Software Development Company</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Leaks in JavaScript and how to avoid them.]]></title>
            <link>https://medium.com/preezma/memory-leaks-in-javascript-and-how-to-avoid-them-63916a02f68?source=rss-daf5761afa02------2</link>
            <guid isPermaLink="false">https://medium.com/p/63916a02f68</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[memory-leak]]></category>
            <dc:creator><![CDATA[Eduard Hayrapetyan]]></dc:creator>
            <pubDate>Sun, 26 Jul 2020 18:32:17 GMT</pubDate>
            <atom:updated>2020-07-26T18:34:10.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RP7ANL1qDMP5CEdFZoZYXw.jpeg" /></figure><h3>Overview</h3><p>We just need to remember that memory is limited , so when it comes to call stack and memory heap ,those are two places that JavaScript remembers or stores memory. And we have limited use of them. So we will do our best to write efficient code to avoid the stack overflow or a memory leak and to manage memory well.</p><h3>What are memory leaks?</h3><p>A Memory leak can be defined as a piece of memory that is no longer being used or required by an application but for some reason is not returned back to the OS.In simple terms it is<em> </em><strong><em>forgotten data forever waiting to be used</em></strong><em>.</em>Leaks are the cause of whole class of problems: slowdowns, crashes, high latency, and even problems with other applications.</p><p>So lets create our own memory leak 🥴 the easiest way to do this is the following example</p><pre>let arr = [];<br>for(let i = 5; i &gt; 1; i++){<br>    arr.push(i-1)           // Warning! do not try this at home )<br>}</pre><p>So we are going to run an infinite loop that keeps pushing to the array i -1 over and over until we will fill up our memory and there’s nothing left for us to use. In this case <strong>garbage collection </strong>wasn’t really working because we had this array and we are using this array over and over until we crashed the program. So most likely you are not going to do this in your programs, so lets dive and see what common memory leaks can happen in our application.</p><h3>The four types of common JavaScript leaks</h3><p><strong>1.Undeclared/ Global Variables</strong></p><p>One of the ways in which JavaScript is permissive is in the way <strong>it handles undeclared variables</strong>: a reference to an undeclared variable creates a new variable inside the global object.</p><p>In the case of browsers, the global object is a “<strong>window</strong>”. For instance:</p><pre>function foo(arg){<br>   bar = &quot;this is a hidden global variable&quot;;<br>}</pre><p>But, is in fact</p><pre>function foo(arg){<br>   window.bar = &quot;this is an explicit global variable&quot;;<br>}</pre><p>Always avoid using global variables or prevent these mistakes from happening, add &#39;<strong>use strict</strong>&#39;; at the beginning of your JavaScript files. This enables a stricter mode of parsing JavaScript that prevents accidental globals.</p><p><strong>2.Forgotten timers or callbacks</strong></p><p>Having a setTimeout or a setInterval referencing some object in the callback is the most common way of preventing the object from being garbage collected. If we set the recurring timer in our code the reference to the object from the timer&#39;s callback will stay active for as long as the callback is invocable.</p><p>In the example below the data object can be garbage collected only after the timer is cleared. Since we have no reference to setInterval, it can never be cleared and data.hugeString is kept in memory until the app stops, although never used.</p><pre>function setCallback() {    <br> const data = {   <br>    counter: 0,    <br>    hugeString: new Array(100000).join(&#39;x&#39;)   <br>  };  <br> return function cb() {  <br>  data.counter++; // data object is now part of the callback&#39;s scope                        console.log(data.counter);   <br>   }<br>} <br>setInterval(setCallback(), 1000); // how do we stop it?</pre><p><strong>How to prevent it:</strong> Especially if the callback’s lifespan is undefined or indefinite:</p><ul><li>being aware of the objects referenced from the timer’s callback,</li><li>using the handle returned from the timer to cancel it when necessary.</li><li>returned from the timer to cancel it when necessary.</li></ul><pre>function setCallback() {<br>    // &#39;unpacking&#39; the data object<br>    let counter = 0;<br>    const hugeString = new Array(100000).join(&#39;x&#39;); // gets removed   when the setCallback returns<br>    return function cb() {<br>        counter++; // only counter is part of the callback&#39;s scope<br>        console.log(counter);<br>    }<br>}</pre><pre>const timerId = setInterval(setCallback(), 1000); // saving the interval ID</pre><pre>// doing something ...</pre><pre>clearInterval(timerId); // stopping the timer i.e. if button pressed</pre><p><strong>3.Out of DOM references </strong>(Event listeners)</p><p>Active event listener will prevent all variables captured in its scope from being garbage collected. Once added, the event listener will remain in effect until:</p><ul><li>explicitly removed with removeEventListener()</li><li>the associated DOM element is removed.</li></ul><p>A DOM element belongs to the DOM, but it also exists in the Object Graph Memory. Therefore, if you delete the former, you should else delete the latter.</p><pre>var trigger = document.getElementById(&quot;trigger&quot;);<br>var elem = document.getElementById(&quot;elementToDelete&quot;);</pre><pre>trigger.addEventListener(&quot;click&quot;, function(){<br>   elem.remove();<br>});</pre><p>In this example, after you click <em>trigger</em>, e<em>lementToDelete </em>is removed from the DOM. But since it’s still referenced within the listener, the allocated memory for the object is still used.</p><p><strong>How to prevent it:</strong> We should always unregister the event listener once no longer needed, by creating a reference pointing to it and passing it to removeEventListener() or addEventListener() can take a third parameter, which is an object providing additional options. Given that {once: true} is passed as a third parameter to addEventListener(), the listener function will be automatically removed after handling the event once.</p><pre>trigger.addEventListener(&quot;click&quot;, function(){<br>   elem.remove();<br>},{once: true}));  // listener will be removed after running once</pre><p><strong>4.Closures</strong></p><p>Function-scoped variables will be cleaned up after the function has exited the call stack and if there aren’t any references left outside of the function pointing at them. The closure will keep the variables referenced and alive although the function has finished executing and its execution context and variable environment are long gone.</p><pre>function outer() { <br>    const potentiallyHugeArray = []; <br>    return function inner() {  <br>       potentiallyHugeArray.push(&#39;Hello&#39;); <br>       console.log(&#39;Hello&#39;);    <br>  }; <br>};<br> const sayHello = outer(); // contains definition of the function inner <br> function repeat(fn, num) { <br>    for (let i = 0; i &lt; num; i++){ <br>        fn();     <br>   }<br> } <br>repeat(sayHello, 10); // each sayHello call pushes another &#39;Hello&#39; to the potentiallyHugeArray   <br> // now imagine repeat(sayHello, 100000)</pre><p>In this example, potentiallyHugeArray is never returned from any of the functions and cannot be reached, but its size can grow infinitely depending on how many times we call the function inner().</p><p><strong>How to prevent it:</strong> Closures are an unavoidable and an integral part of JavaScript, so it is important to:</p><ul><li>understand when the closure has been created and what objects are retained by it,</li><li>understand closure’s expected lifespan and usage (especially if used as a callback).</li></ul><h3>Conclusion</h3><p>Integral part of the memory management process is understanding the typical memory leaks sources to prevent them from happening in the first place. In the end, when it comes to memory and performance, it is the user experience that is at stake and that’s what matters most.<br>If you ❤️ this article, click the clap 👏 , I hope this article was helpful for you.</p><h3>References</h3><ul><li><a href="https://auth0.com/blog/four-types-of-leaks-in-your-javascript-code-and-how-to-get-rid-of-them/">4 Types of Memory Leaks in JavaScript and How to Get Rid Of Them</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec">How JavaScript works: memory management + how to handle 4 common memory leaks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63916a02f68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preezma/memory-leaks-in-javascript-and-how-to-avoid-them-63916a02f68">Memory Leaks in JavaScript and how to avoid them.</a> was originally published in <a href="https://medium.com/preezma">Preezma Software Development Company</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory management in JavaScript]]></title>
            <link>https://medium.com/preezma/memory-management-in-javascript-e6b2ab793b5a?source=rss-daf5761afa02------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6b2ab793b5a</guid>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Eduard Hayrapetyan]]></dc:creator>
            <pubDate>Sun, 19 Jul 2020 17:27:11 GMT</pubDate>
            <atom:updated>2020-07-19T17:27:11.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hb87UnRVgjlSEFVxnGrY6g.jpeg" /></figure><h3>Overview</h3><p>When something gets displayed on your webpage, where is it stored? The process of memory allocation is automatic in modern browsers, since in JavaScript we are not performing any manual memory operation however it is good to know how it works.This helps analyze and debug things, forces us to be more inventive developers also understand the work behind the scenes.Languages, like C have low-level memory management ,and the developer had to allocate memory by using malloc() and free().</p><h3>Memory life cycle</h3><p>No matter what programming language you’re using, memory life cycle is pretty much always the same:</p><ol><li><strong>Allocate memory</strong></li><li><strong>Use memory</strong></li><li><strong>Release memory</strong></li></ol><p>Here is an overview of what happens at each step of the cycle:</p><ul><li><strong>Allocate memory </strong>— memory is allocated by the operating system which allows your program to use it.</li><li><strong>Use memory — </strong>this is the time when your program actually makes use of the previously allocated memory. <strong>Read</strong> and <strong>write</strong> operations are taking place as you’re using the allocated variables in your code.</li><li><strong>Release memory</strong> — now is the time to release the entire memory that you don’t need so that it can become free and available again. As with the <strong>Allocate memory </strong>operation, this one is explicit in low-level languages.</li></ul><h3>V8 memory structure 🧠</h3><p>First, let us see what the memory structure of the V8 engine is. Since JavaScript is single-threaded V8 also uses a single process via JavaScript context. V8 allocates objects in memory into 6 chunks or spaces.The divided chunks also called <strong>Resident Set</strong>.</p><ol><li>New space</li><li>Old pointer space</li><li>Old data space</li><li>Large object space</li><li>Code space</li><li>Map Space</li></ol><ul><li><strong>New Space</strong>: New space or <strong>Young generation</strong> is where new allocated objects live and most of these objects are short-lived. This space is small and has two <strong>semi-space(</strong>1–8 MB). So when you create an object which size fits in 1–8 megabytes, it will go to the new space.</li><li><strong>Old pointer space</strong>: Contains survived objects that have pointers to other objects. Default size is 1.4GB , but you can make it bigger by max-old-space-size <a href="https://gist.github.com/cevek/ef1c9761a67d80d642f98cc75885bf31">v8 Flag</a>.</li><li><strong>Old data space</strong>: Contains objects that just contain data without pointer to other objects. Ascii characters, Strings, numbers, and arrays of unboxed doubles are moved here after surviving in “New space” for two minor GC cycles.</li><li><strong>Large object space</strong>: This is where objects which are larger than the size limits of other spaces live. If objects didn’t fits on the <strong>new space,</strong> they automatically allocated on this space. Each object gets its own [mmap] region of memory. <strong>Large objects are never moved by the garbage collector.</strong></li><li><strong>Code-space</strong>: This is where the <a href="https://en.wikipedia.org/wiki/Just-in-time_compilation"><strong>Just In Time(JIT)</strong></a> compiler stores compiled code blocks. This is the only space with executable memory (although Codes may be allocated in “Large object space”, and those are executable, too).</li><li><strong>Map space</strong>: These spaces contain Maps, Cells, and PropertyCell respectively. Each of these spaces contains objects which are all the same size and has some constraints on what kind of objects they point to, which simplifies collection.</li></ul><p>So this point we allocated objects on memory, they’re in our heap, and now a question?:) How we should know what to clean and how to clean it?🗑️🤔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*iMD5sadkhA9o6N3OcBk6uA.gif" /></figure><p>And the answer is <strong>Reachability</strong>! Memory is considered garbage when it’s no longer reachable or accessible in your code, and here comes the garbage Collector.</p><h3><em>V8 Memory management with Garbage collection</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*ueLTwrmc_ssq7RQj7wT3Zw.gif" /></figure><p>V8 manages the heap memory by garbage collection. In simple terms, it frees the memory used by dead objects, objects that are no longer referenced from the Stack directly or indirectly(via a reference in another object) to make space for new object creation.</p><p>There are two stages and three different algorithms used for garbage collection by V8: <strong>Minor GC (Scavenger) &amp; Major GC.</strong></p><h3>Minor GC (Scavenger)</h3><p>This type of GC keeps the young or new generation space compact and clean. Objects are allocated in new-space, which is fairly small (between 1 and 8 MB, depending on behavior). Allocation in “new space” is very cheap: there is an allocation pointer which we increment whenever we want to reserve space for a new object. When the allocation pointer reaches the end of the new space, minor GC is triggered. This process is called <strong>Scavenger</strong> and it implements <a href="http://en.wikipedia.org/wiki/Cheney&#39;s_algorithm">Cheney’s algorithm</a>. It occurs frequently and uses parallel helper threads and is very fast.</p><p>Let us look at the minor GC process:</p><p>The new space is divided into two equal-sized semi-spaces: <strong>to-space</strong> and <strong>from-space</strong>. Most allocations are made in from-space .When from-space fills up the minor GC is triggered.</p><ol><li>Let us assume that there are already objects on the “from-space” when we start(Blocks 01 to 06 marked as used memory)</li><li>The process creates a new object(07)</li><li>V8 tries to get required memory from from-space, but there is no free space in there to accommodate our object and hence V8 triggers minor GC</li><li>Minor GC recursively traverses the object graph in “from-space” starting from stack pointers(GC roots) to find objects that are used or alive(Used memory). These objects are moved to a page in the “to-space”. Any objects reference by these objects are also moved to this page in “to-space” and their pointers are updated. This is repeated until all the objects in “from-space” are scanned. By end of this, the “to-space” is automatically compacted reducing fragmentation</li><li>Minor GC now empties the “from-space” as any remaining object here is garbage</li><li>Minor GC swaps the “to-space” and “from-space”, all the objects are now in “from-space” and the “to-space” is empty</li><li>The new object is allocated memory in the “from-space”</li><li>Let us assume that some time has passed and there are more objects on the “from-space” now(Blocks 07 to 09 marked as used memory)</li><li>The application creates a new object(10)</li><li>V8 tries to get required memory from “from-space”, but there is no free space in there to accommodate our object and hence V8 triggers second minor GC</li><li>The above process is repeated and any alive objects that survived second minor GC is moved to the “Old space”. First-time survivors are moved to the “to-space” and remaining garbage is cleared from “from-space”</li><li>Minor GC swaps the “to-space” and “from-space”, all the objects are now in “from-space” and the “to-space” is empty</li><li>The new object is allocated memory in the “from-space”</li></ol><p>So we saw how minor GC reclaims space from the young generation and keeps it compact. It is a stop-the-world process but it’s so fast and efficient that it is negligible most of the time. Since this process doesn’t scan objects in the “old space” for any reference in the “new space” it uses a register of all pointers from old space to new space.</p><h3>Major GC</h3><p>This type of GC keeps the old generation space compact and clean. This is triggered when V8 decides there is not enough old space, based on a dynamically computed limit, as it gets filled up from minor GC cycles.</p><p>The Scavenger algorithm is perfect for small data size but is impractical for large heap, as the old space, as it has memory overhead and hence major GC is done using the <strong>Mark-Sweep-Compact</strong> algorithm.The following image visualizes the mark and sweep process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*L4WGutRBomHr2cl20vWi6g.gif" /></figure><ul><li>The Mark-and-sweep algorithm goes through these 3 steps:</li></ul><ol><li>Roots: In general, roots are global variables which get referenced in the code. In JavaScript for example, a global variable that can act as a root is the “window” object. The identical object in Node.js is called “global”. A complete list of all roots gets built by the garbage collector.</li><li>The algorithm then inspects all roots and their children and marks them as active (meaning, they are not garbage). Anything that a root cannot reach will be marked as garbage.</li><li>Finally, the garbage collector frees all memory pieces that are not marked as active and returns that memory to the OS.</li></ol><ul><li><strong>Incremental GC</strong>: GC is done in multiple incremental steps instead of one.</li><li><strong>Concurrent marking</strong>: Marking is done concurrently using multiple helper threads without affecting the main JavaScript thread. Write barriers are used to keep track of new references between objects that JavaScript creates while the helpers are marking concurrently.</li><li><strong>Sweeping/compacting</strong>: Sweeping and compacting are done in helper threads concurrently without affecting the main JavaScript thread.</li><li><strong>Lazy sweeping</strong>. Lazy sweeping involves delaying the deletion of garbage in pages until the memory is required.</li></ul><p>Let us look at the major GC process:</p><ol><li>Let us assume that many minor GC cycles have passed and the old space is almost full and V8 decides to trigger a “Major GC”</li><li>Major GC recursively traverses the object graph starting from stack pointers to mark objects that are used as alive(Used memory) and remaining objects as garbage(Orphans) in the old space. This is done using multiple concurrent helper threads and each helper follows a pointer. This does not affect the main JS thread.</li><li>When concurrent marking is done or if memory limit is reached the GC does a mark finalization step using the main thread. This introduces a small pause-time.</li><li>Major GC now marks all dead object’s memory as free using concurrent sweep threads. Parallel compaction tasks are also triggered to move related blocks of memory to the same page to avoid fragmentation. Pointers are updated during these steps.</li></ol><p><em>How much memory is your application using &amp; how often do GC cycles occur in your application?</em></p><p>1.You can investigate heap by making a snapshot in Chrome Dev Tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*rcvmyYB16JkRFYI0Z72clw.png" /><figcaption>Devtools ➡️ Memory ⬇️ Take snapshot</figcaption></figure><p>2. <a href="https://www.npmjs.com/package/heapdump">npm i heapdump</a></p><p>Heapdump is a javaScript library for node ,and it allows you to take a snapshot of your heap.</p><h3>Conclusion</h3><p>Thanks for reading! I hope this helped you to understand how the browser allocates and clears out memory as it runs applications.</p><h3>References</h3><p><a href="https://www.youtube.com/watch?v=AeUCN2lPqL8&amp;t=1054s">Safia Abdalla: The Hitchhiker’s Guide to All Things Memory in Javascript</a></p><p><a href="https://www.youtube.com/watch?v=-NpUG8OJSf8">Memory Management and Garbage Collection in V8</a></p><ul><li><a href="https://v8.dev/blog/trash-talk">Trash talk: the Orinoco garbage collector</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management">Memory management - JavaScript | MDN</a></li><li><a href="http://jayconrod.com/posts/55/a-tour-of-v8-garbage-collection">A tour of V8: Garbage Collection</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6b2ab793b5a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preezma/memory-management-in-javascript-e6b2ab793b5a">Memory management in JavaScript</a> was originally published in <a href="https://medium.com/preezma">Preezma Software Development Company</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Understanding Under The Hood Of a Browser]]></title>
            <link>https://medium.com/preezma/javascript-understanding-under-the-hood-of-a-browser-c227177c875b?source=rss-daf5761afa02------2</link>
            <guid isPermaLink="false">https://medium.com/p/c227177c875b</guid>
            <category><![CDATA[event-queue]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[call-stack]]></category>
            <dc:creator><![CDATA[Eduard Hayrapetyan]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 15:36:39 GMT</pubDate>
            <atom:updated>2020-07-12T15:46:20.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vlWsUBXGIrldVK0wKM4gXQ.jpeg" /></figure><h3>Overview</h3><p>This article is about deepening our knowledge of JS by understanding how our code gets executed. If you are new to JavaScript 👶, then this article will help to learn how JavaScript works. If you are an experienced 👴, JavaScript developer hopefully, this will be a good refresher for you.</p><p>Understanding the browser environment, what it is composed of and how it works will make you more confident in writing JavaScript and well-prepared for potential issues that might happen.</p><h3>The JavaScript Engine</h3><p>Basically, the engine is a program that translates your JavaScript into machine code and executes the result on a computer’s central processing unit (CPU). A popular example of a JavaScript engine is Google’s V8 engine.The V8 engine is used inside Google Chrome, Node.js ,electron and among others.And there are various JavaScript Engines that are available for use. You can refer this <a href="https://en.wikipedia.org/wiki/JavaScript_engine">Wikipedia</a> page for the list of available JS engines.</p><p><strong>V8 Does:</strong></p><ol><li>Compiles and executes JS code</li><li>Handling call stack — running your JS functions in some order</li><li>Managing memory allocation for objects — the memory heap</li><li>Garbage collection — of objects which are no longer in use</li><li>Provide all the data types, operators, objects and functions</li></ol><p><strong>V8 Can:</strong></p><ol><li>Provide the event loop, but this is sometimes implemented by the browser as well.</li></ol><p><strong>V8 Doesn’t:</strong></p><p>Know anything about the Web APIs like DOM elements and events, XMLHttpRequest, fetch, setTimeout, setInterval and so on, which are accessible via JavaScript<strong>.</strong></p><p>This is a very simplified view of what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*oZNNs0TCxqhRkOjv34Aoxg.png" /></figure><p>The mechanism consists of two main components:</p><ul><li>Memory Heap — is an unstructured memory that is used for memory allocation of the variables and the objects.</li><li>Call Stack — is a <a href="https://en.wikipedia.org/wiki/Stack_(abstract_data_type)">LIFO</a> data structure that is used for function calls that record where we are in the program.</li></ul><h3>🥞 Call Stack</h3><p>JavaScript is a single-threaded programming language with a single call stack. It means that your code is executed synchronously, we only have a single call stack, in other words, we can only execute one thing at a time.</p><p>If we execute a function, V8 pushes frame on top of the stack. When we return from a function, V8 pops off the frame. Let’s take an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*YeU-tsCwiojzgtiol_Z7yA.gif" /></figure><p>Following is the sequence of steps when JavaScript executes the code:</p><ol><li>Start execution using the main thread referred to as main() here.</li><li>Identify the function which needs to executed and add it in the call stack.</li><li>Identify other function which the current function executes and add it in the call stack.</li><li>Upon completion of the function remove its reference from the call stack.</li><li>Repeat steps #2 to #4 till the code finishes execution.</li><li>After all the code has finished execution, remove main() from the call stack.</li></ol><p>Hence, if any other program want to execute something, it has to wait until previous program is completely executed. This means that while a function is being executed, the engine cannot run another context at the same time. It also means that every time a function is pushed onto the call-stack, it then becomes the active executing context and takes control flow away from whatever function called it, until it <em>returns </em>either explicitly (with a return statement) or implicitly (when all instructions have been executed).</p><p>So let’s think of one scenario. What if a browser sends a HTTP request to load some data over network or to load an image to display on web page. Will browser freeze until that request is resolved? So how then do we achieve asynchronous JavaScript with it’s illusion of multiple things happening all at once?</p><p>Browser comes with a JavaScript engine which provides JavaScript runtime environment and uses more than just a JavaScript engine. This is what browser under the hood looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*5gNXv17lERnjb12v9Xfqdg.png" /><figcaption>The big picture 🧐</figcaption></figure><p>JavaScript runtime actually consist of 2 more components <strong>event loop</strong> and <strong>callback queue</strong>. Callback queue is also called as <strong>message queue</strong> or <strong>task queue</strong>.</p><p>Apart from JavaScript engine, browser contains different applications which can do variety of things like send HTTP requests, listen to DOM events, delay execution using setTimeout or setInterval, caching, database storage and much more. These features of browser help us create rich web applications.</p><p>But think about this, if browser had to use same JavaScript thread for execution of these feature, then user experience would have been horrible. Because even when user is just scrolling the web page, there are many things going on, in the background. Hence, browser uses low level language like C++ to perform these operations and provide clean JavaScript API to work with. These APIs are known as <strong>Web APIs</strong>.</p><p>These Web APIs are <strong>asynchronous</strong>. That means, you can instruct these APIs to do something in background and return data once done, meanwhile we can continue further execution of JavaScript code. While instructing these APIs to do something in background, we have to provide a <strong>callback function</strong>. Responsibility of callback function is to execute some JavaScript once Web API is done with it’s work. Let’s understand how all pieces work together.</p><p>So when you call a function, it gets pushed to the stack. If that function contains Web API call, JavaScript will delegate control of it to the Web API with a callback function and move to the next lines until function returns something. Once function hits return statement, that function is popped from the stack and move to the next stack entry. Meanwhile, Web API is doing it’s job in the background and remembers what callback function is associated with that job. Once job is done, Web API binds result of that job to callback function and publishes a message to <strong>callback queue</strong> with that callback. The only job of <strong>event loop</strong> is to look at callback queue and once there is something pending in callback queue, push that callback to the stack. Event loop pushes one callback function at a time, to the stack, <strong>once the stack is empty</strong>. Later, stack will execute callback function.</p><p>Let’s see how everything works step by step using setTimeout Web API. setTimeout Web API is mainly used to execute something after few seconds. This execution happens once all code in the program is done executing (<em>when stack is empty</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*csQAm_62BgeLr8eXwnLUpg.gif" /><figcaption>Here’s a visualization of how it all works from <a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ">Philip Roberts’ speech from JSConf EU 2014</a></figcaption></figure><p>What I think should be noted is the way setTimeout actually works. Calling setTimeout(function cb(){...}, 5000) doesn&#39;t mean foo will be executed in precisely 5 seconds; it means that in 5 seconds cb will be put into the callback queue, where it will wait until the stack is empty. This is why sometimes setTimeout(..., 0) is used: instead of just executing its callback immediately, it waits until all the other stuff is done.</p><p>There’s a resource called <a href="http://latentflip.com/loupe/?code=JC5vbignYnV0dG9uJywgJ2NsaWNrJywgZnVuY3Rpb24gb25DbGljaygpIHsKICAgIHNldFRpbWVvdXQoZnVuY3Rpb24gdGltZXIoKSB7CiAgICAgICAgY29uc29sZS5sb2coJ1lvdSBjbGlja2VkIHRoZSBidXR0b24hJyk7ICAgIAogICAgfSwgMjAwMCk7Cn0pOwoKY29uc29sZS5sb2coIkhpISIpOwoKc2V0VGltZW91dChmdW5jdGlvbiB0aW1lb3V0KCkgewogICAgY29uc29sZS5sb2coIkNsaWNrIHRoZSBidXR0b24hIik7Cn0sIDUwMDApOwoKY29uc29sZS5sb2coIldlbGNvbWUgdG8gbG91cGUuIik7!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D">Loupe</a> (also created by Philip Roberts) that visualizes JavaScript code and shows how the stack, the WebAPIs, the callback queue and the event loop interact with each other.</p><h3>Heap</h3><p>Sometimes V8 doesn’t know at compile time how much memory an object variable will need. All the memory allocation for such data happens in the heap — unstructured region of memory. Objects on the heap live on after we exit the function that allocated the memory.</p><p>V8 has a built-in Garbage Collector (GC). Garbage collection is a form of memory management. It’s like a collector which attempts to release the memory occupied by objects that are no longer being used.</p><p>You can investigate heap by making a snapshot in Chrome Dev Tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*yugi1MFjqu7DyI_OHAK2og.png" /><figcaption>Devtools ➡️ Memory ⬇️ Take snapshot</figcaption></figure><p>Since we don’t have access to infinite amount of memory, there is comes V8 built-in Garbage Collector (GC). Garbage collector’s job is to go through objects that are allocated in memory and determine whether they are <em>dead</em> or <em>alive</em>. Those that are alive get to stay in memory, those that are dead get removed, and memory gets allocated back to the heap.</p><h3>Conclusion</h3><p>Thanks for reading! I hope that after reading this article you have a better understanding of the mechanics behind JavaScript. These concepts also act as a building block for a greater understanding of other concepts such as scopes and closures. Please, click the clap 👏, if the article above was helpful for you.</p><h3>References</h3><p><a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ&amp;t=967s">What the heck is the event loop anyway? | Philip Roberts | JSConf EU</a></p><p><a href="https://www.youtube.com/watch?v=cCOL7MC4Pl0">Jake Archibald: In The Loop — JSConf.Asia</a></p><ul><li><a href="https://medium.com/@allansendagi/javascript-fundamentals-call-stack-and-memory-heap-401eb8713204">Javascript Fundamentals — Call Stack and Memory Heap</a></li><li><a href="https://blog.bitsrc.io/understanding-execution-context-and-execution-stack-in-javascript-1c9ea8642dd0">Understanding Execution Context and Execution Stack in Javascript</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c227177c875b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preezma/javascript-understanding-under-the-hood-of-a-browser-c227177c875b">JavaScript: Understanding Under The Hood Of a Browser</a> was originally published in <a href="https://medium.com/preezma">Preezma Software Development Company</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>