<?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 Vishvesh on Medium]]></title>
        <description><![CDATA[Stories by Vishvesh on Medium]]></description>
        <link>https://medium.com/@myLordVish?source=rss-13629fbf3388------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*B2xhRPv9Z-fCknypsBbFng.jpeg</url>
            <title>Stories by Vishvesh on Medium</title>
            <link>https://medium.com/@myLordVish?source=rss-13629fbf3388------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 19:51:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@myLordVish/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[Seven instances where ES6 makes your programming life easier]]></title>
            <link>https://medium.com/@myLordVish/seven-instances-where-es6-makes-your-programming-life-easier-1f2b29777217?source=rss-13629fbf3388------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f2b29777217</guid>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Vishvesh]]></dc:creator>
            <pubDate>Mon, 16 Nov 2020 08:24:12 GMT</pubDate>
            <atom:updated>2020-11-16T08:24:12.188Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Seven instances where ES6 makes your programming life easier</strong></p><p>ES6 isn’t new. In fact, since its inception in 2015, at least five other new versions have been released and with those, we have got a whole lot of cool new features at our disposal. But what makes ES6 still stand out among the rest of the versions is it changed the course of scripting language by introducing some of the path breaking features in scripting history.</p><p>The features include let and const, arrow functions, default parameters, rest and spread operators, classes, modules, promises, template literals, destructuring and much more.</p><p>But in this article, we will try to explore just seven instances where ES6 features come in handy and make your programming life easier.</p><p><strong>let vs var:</strong></p><p>In my opinion, developers with a C#/Java background hesitated a lot to pick up JavaScript just because of its outright weirdness. The scoping of <em>var </em>along with its most confusing hoisting problems made new learners to think JavaScript is extremely daunting. ES6 solved these issues in one shot with the introduction of let and const.</p><p>The main difference is <em>var </em>has functional level scope while <em>let</em> has block level scope and cannot be used before declaration, which essentially eliminates the hoisting problem. Let’s see why block scoping is important with the help of an example.</p><pre>for (var i = 1; i &lt; 5; i++) {</pre><pre>  console.log(i);</pre><pre>  setTimeout(function () {</pre><pre>    console.log(i);</pre><pre>  }, 1000)</pre><pre>};</pre><p>If you run the above code, you’ll end up with the most bizarre output with ‘i’ getting printed as ‘5’ four times in the console like how it is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*Xkfh2l7_-VscLstMtkBMEA.png" /></figure><p>Why? Well, the keyword <em>var </em>is the culprit here. Since <em>var </em>is function scoped and ‘i’ gets incremented to 4 even before the setTimeout runs, we get this weird output. Could it get any more confusing?</p><p>Okay, how to solve this then? Well, although defining a separate function for the setTimeout is enough do the job, there is a much better elegant solution which is to simply use block-scoped <em>let</em>. Using <em>let, </em>this is what we get as the output, which is what we intended in the first place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*6DWsNlEdzzmyjTbWKEwOWw.png" /></figure><p>So, when you declare variables, always prefer let over var wherever possible because it only makes the code less confusing and more friendly.</p><p><strong>Template Literals:</strong></p><p>Let’s be honest. Haven’t we ever felt annoyed when we try to handle strings in JavaScript, especially with multiple lines? What about your experience when you try to create HTML elements through JavaScript? Annoying at times, isn’t it? Let’s see why.</p><pre>const name = “Raj”;</pre><pre>const age = 23;</pre><pre>const city = “Chennai”;</pre><pre>// Traditional way</pre><pre>const str = name + “,” + age + “lives in” + city;</pre><p>Now, let’s try the same with template literals. To do this, ES6 provides you an option to enclose strings with backticks (`) and within that, you can gain access to usual JavaScript variables/properties using ${}.</p><pre>// with backticks</pre><pre>const str = `${name},${age} lives in ${city}`;</pre><p>You see how simple is that? That’s how elegant template literal makes your code. Template literal is particularly powerful when you have to use multiple string or create HTML elements like below.</p><pre>const div = document.createElement(‘div’);</pre><pre>const list =</pre><pre>`&lt;ul&gt;</pre><pre>  &lt;li&gt;one&lt;/li&gt;</pre><pre>  &lt;li&gt;two&lt;/li&gt;</pre><pre>  &lt;li&gt;three&lt;/li&gt;</pre><pre>  &lt;li&gt;four&lt;/li&gt;</pre><pre>&lt;/ul&gt;`</pre><pre>div.innerHTML = list;</pre><pre>document.body.append(div);</pre><p>Get it? It’s as if you are using normal English. All you need is your backticks to make this magic work.</p><p><strong>Arrow functions:</strong></p><p>Arrow function is my favorite of the bunch. It is the one of the most important features of ES6 that enables us to create functions without the <em>function </em>keyword. Not just that, it also reduces the keyword <em>return </em>in some cases, making the code more concise and clearer. Let’s look at an example to see the striking difference.</p><pre>let numbers = [1,2,3];</pre><pre>// Traditional way</pre><pre>let squareNum = numbers.map(function(num){</pre><pre>  return num*num;</pre><pre>});</pre><pre>// ES6 way with Arrow function</pre><pre>let squareNum = numbers.map(num =&gt; num*num);</pre><p>In the above snippet, you can clearly see how concise the code is when you use the fat arrow function. The keyword <em>function </em>is gone, the explicit return is gone too, along with the parenthesis for the argument, thus promising a shorter syntax than the traditional way. Cool, isn’t it? But keep in mind, you still need to use the return keyword when you have multiple lines of code in your code block. Also, in case it is multiple argument function, you must use the parenthesis around the arguments.</p><p>Before you get too excited and start using arrow functions, there is one more thing to be aware of. Arrow functions do not bind their own <em>this. </em>Rather, they inherit it from the parent scope, which is what we call <em>lexical scoping. </em>To understand this, we must first need to know what <em>this </em>means in JavaScript.</p><p>The <em>this </em>in JavaScript is a unique keyword whose value changes depending on how it is called. For instance, when <em>this </em>is outside of a function, <em>this </em>refers to the Window object. When the same <em>this </em>is inside an object method, it refers to the Object itself.</p><pre>function simpleFnc () {</pre><pre>  console.log(this);</pre><pre>}</pre><pre>simpleFnc() // Window</pre><pre>  let simpleObj = {</pre><pre>    simpleFnc: function() {</pre><pre>      console.log(this);</pre><pre>    }</pre><pre>  }</pre><pre>simpleObj.simpleFnc() // simpleObj</pre><p>But in arrow function, <em>this </em>will always be the same <em>this </em>value as its surrounding code. Let’s tweak the above example with an arrow function and see what we get.</p><pre>let simpleObj = {</pre><pre>    simpleFnc: function() {</pre><pre>    console.log(this);</pre><pre>  }</pre><pre>}</pre><pre>simpleObj.simpleFnc() // simpleObj</pre><pre>let simpleObj = {</pre><pre>    simpleFnc: () =&gt; {</pre><pre>    console.log(this);</pre><pre>  }</pre><pre>}</pre><pre>simpleObj.simpleFnc() // window</pre><p>The above example clearly tells how arrow functions don’t bind their own scope but inherit from the parent, which in this case is Window object.</p><p>Arrow functions may seem a little hard to use at first, but once you get used to it, you’ll see a massive difference in your coding style.</p><p><strong>Default parameters</strong></p><p>As the name says, default parameters in ES6 allows us to provide default values to the parameters. Let’s straight away dive into an example to understand what exactly it means. Let’s say we have a function to display the project name to which the employee is currently assigned, like the following.</p><pre>function getEmployeeStatus (name, project) {</pre><pre>  console.log(name + “, “ + project );</pre><pre>}</pre><pre>getEmployeeStatus(“Vish”,”KLA”); //Vish, KLA</pre><p>The above code works fine, sure. But what if an employee is not assigned to any project? In that case, the project becomes <em>undefined</em>, and if the argument project is <em>undefined</em>, how can the above code snippet handle the situation? It simply displays <em>undefined</em> in place of project, which is the last thing we want in such situation. To handle this in ES5, we can do the following.</p><pre>function getEmployeeStatus (name, project) {</pre><pre>  if(project == undefined) {</pre><pre>    project = “Unassigned”;</pre><pre>  }</pre><pre>  console.log(name + “, “ + project );</pre><pre>}</pre><pre>getEmployeeStatus(“Vish”); //Vish, Unassigned</pre><p>Although we can pass <em>unassigned </em>as project, the better way to handle the situation is to check if the project is <em>undefined</em>. Problem solved, yes, but this is where ES6 gives an elegant solution. With default parameters, all we need to do is to assign a default value to the parameter and with that, JavaScript automatically assigns the default value whenever the parameter is <em>undefined.</em></p><pre>function getEmployeeStatus (name, project = “Unassigned”) {</pre><pre>  console.log(name + “, “ + project );</pre><pre>}</pre><pre>getEmployeeStatus(“Vish”); //Vish, Unassigned</pre><p><strong>Rest and Spread Operators</strong></p><p>If you happen to see a code with triple dots (…), it’s nothing but ES6 Rest and Spread operators. They look the same, i.e., tripe dots (…), but they differ a bit depending on what you use that for. Let’s take a look at Rest operators first. Consider the below example.</p><pre>let title = “List of messages.”;</pre><pre>let displayMessages = function() {</pre><pre>  console.log(title);</pre><pre>  for(let i in arguments) {</pre><pre>    console.log(arguments[i]);</pre><pre>  }</pre><pre>}</pre><pre>displayMessages(title,”Hi”,”Hello”,”How are you?”);</pre><pre>// List of messages.</pre><pre>// List of messages.</pre><pre>// Hi</pre><pre>// Hello</pre><pre>// How are you?</pre><p>Let’s say we have a function <em>displayMessages </em>that takes <em>title </em>as one argument and then a set of unknown number of arguments. To display the unknown arguments, we have to use <em>arguments </em>object to figure out the actual arguments. But there is a problem with this approach. In the above example, we want to display the title only once and the rest of the messages to be printed below it. But since the title is also a part of the <em>arguments </em>object, the title gets displayed again along with the rest of the arguments. Here’s where <em>rest </em>operator comes in handy. Let’s see how.</p><pre>let title = “List of messages.”;</pre><pre>let displayMessages = function(title, …msgs) {</pre><pre>  console.log(title);</pre><pre>  msgs.forEach(ele=&gt;{console.log(ele)});</pre><pre>}</pre><pre>displayMessages(title,”Hi”,”Hello”,”How are you?”);</pre><pre>// List of messages.</pre><pre>// Hi</pre><pre>// Hello</pre><pre>// How are you?</pre><p>See how the rest operator packs the rest of the arguments into an array and displays it how we expected. That’s exactly the use of rest operator. Now, let’s move on to spread operator.</p><p>Spread operator does the opposite. While the rest operator packs everything into an array, the spread operator takes an array and spreads it into comma separated items. An example could explain it easily.</p><pre>let array = [‘hi’, ‘hello’];</pre><pre>console.log(…array); // hi hello</pre><p>See, that’s it. So simple and yet so useful in certain scenarios like array concatenation. In ES 5, if you have to concatenate arrays, you might have to use Array.concat method like below.</p><pre>let array1 = [“One”,”Two”];</pre><pre>let array2 = [“Three”,”Four”];</pre><pre>let resultArray = array1.concat(array2);</pre><pre>console.log(resultArray); // [“One”,”Two”,”Three”,”Four”]</pre><p>But with spread operator all you have to do is this.</p><pre>let resultArray = […array1, …array2];</pre><pre>console.log(resultArray); // [“One”,”Two”,”Three”,”Four”]</pre><p><strong>Destructuring</strong></p><p>Destructuring is a handy feature that allows us to extract values out of arrays and objects. We’ll see one by one with appropriate examples and dig deep into them.</p><p><em>With Objects:</em></p><pre>let person = {</pre><pre>  fname: “Vish”,</pre><pre>  lname: “S”</pre><pre>}</pre><pre>let fname = person.fname; //Vish</pre><pre>let lname = person.lname //S</pre><p>Let’s say we have an object <em>person. </em>In ES5, to get the value out of it and assign them to different variables, we do something like in the example, which is alright. But with destructuring, we can do the same in a single line, thus making the code much simpler.</p><pre>let person = {</pre><pre>  fname: “Vish”,</pre><pre>  lname: “S”</pre><pre>}</pre><pre>let {fname, lname} = person;</pre><pre>console.log(fname); //Vish</pre><pre>console.log(lname); //S</pre><p>But keep in mind you can’t declare a variable with the name already used. It will throw out an error. To handle this problem, we can always rename variables using a colon, like below.</p><pre>let {fname, lname: surname} = person;</pre><pre>console.log(fname); //Vish</pre><pre>console.log(surname); //S</pre><p>One last thing to address before we move on to destructuring arrays. If you try to destructure a variable that’s not in an object, it will only return <em>undefined. </em>But fortunately, we have a solution to handle this situation as well by leveraging default parameters feature.</p><pre>let person = {</pre><pre>  fname: “Vish”</pre><pre>}</pre><pre>let {fname, lname: surname = “S”} = person;</pre><pre>console.log(fname); //Vish</pre><pre>console.log(surname); //S</pre><p><em>With Array:</em></p><p>Destructuring Arrays is pretty much the same, only that it pulls apart the elements of the Array instead of an Object. Also, here, we use square brackets to destructure the arrays instead of curly brackets. Let’s look at an example.</p><pre>let person = [“Male”,”Vish”,”S”];</pre><pre>let [gender,fname,lname] = person;</pre><pre>console.log(gender); // Male</pre><pre>console.log(fname); // Vish</pre><pre>console.log(lname); // S</pre><p>By using destructuring in the above code, the variables gender, fname and lname get mapped to the 1st, 2nd and 3rd elements of the array respectively with ease, thus saving us from writing considerable lines of code. Also, keep in mind, if an extra variable is present that can’t get mapped to any element in the array, it simply becomes <em>undefined</em>.</p><pre>let person = [“Male”,”Vish”];</pre><pre>let [gender,fname,lname] = person;</pre><pre>console.log(gender); // Male</pre><pre>console.log(fname); // Vish</pre><pre>console.log(lname); // undefined</pre><p>In addition to that, it’s not always necessary to map every element to the array. To skip, however, the commas are necessary.</p><pre>let person = [“Male”,”Vish”,”S”];</pre><pre>let [,,lname] = person;</pre><pre>console.log(lname); // S</pre><p>This is cool, isn’t it? But the best part is, just like in Destructuring objects, we can leverage features like default parameters and rest operator here in destructuring arrays.</p><pre>// using default parameters</pre><pre>let person = [“Male”,”Vish”];</pre><pre>let [gender,fname,lname=”S”] = person;</pre><pre>console.log(gender); // Male</pre><pre>console.log(fname); // Vish</pre><pre>console.log(lname); // S</pre><pre>// using rest operator</pre><pre>let person = [“Male”,”Vish”,”S”];</pre><pre>let [gender,…name] = person;</pre><pre>console.log(gender); // Male</pre><pre>console.log(name); // [“Vish”,”S”]</pre><p><strong>Promise</strong></p><p>Promise is one of the major and important features that came out as part of ES6. Why is it so? And what exactly is it? A promise is an object that may produce a single value in the future. Up until ES5, to handle asynchronous operations in JavaScript, you need to rely only on callback functions which is okay, but when it comes to nested calls, it is a pain to code. That’s where Promise comes in and saves us. Before we get to know why, we need to know how a Promise works. All you need to know is this. When the promise resolves, we consider the call as success and do something with the data that comes back with <em>.then()</em>. And when the promise rejects, we do the error handling with <em>.catch().</em></p><p>Now, to the example. Let’s assume we have three asynchronous tasks in hand to be done in order. With plain callback functions, this is what we’ll end up.</p><pre>doTask1((err, success) =&gt; {</pre><pre>  if (err) throw err</pre><pre>  doTask2((err, document) =&gt; {</pre><pre>    if (err) throw err</pre><pre>    doTask3(customer, (err, result) =&gt; {</pre><pre>      if (err) throw err</pre><pre>      console.log(‘All Tasks Done’);</pre><pre>    })</pre><pre>  })</pre><pre>})</pre><p>Now, with Promises, we can eliminate all these nested code and do something like below.</p><pre>doTask1()</pre><pre>  .then(_ =&gt; doTask2())</pre><pre>  .then(_ =&gt; doTask3())</pre><pre>  .then(console.log(All tasks Done’))</pre><pre>  .catch(err =&gt; console.log(err))</pre><p>See how easy and clean to write asynchronous operations with Promises. It not only reduces the amount of nested code, but it also helps us to visualize the code flow and lets you handle all errors at the end of the chain in one shot.</p><p><strong>Wrapping up</strong></p><p>Okay, focusing just seven features out of a lot is cruel, I know, but my intention is not to introduce the new features that came out as part of ES6. After all, it came out way back in 2015 and you can find online a ton lot of other blog posts and articles which explain every single feature of ES6 in detail. Rather, my intention is to stress — yet again — how important ES6 was to JavaScript world when it came out and how this version stood out and made our lives easier.</p><p>These features are what make ES6 different from the other versions. They not only make the language easier for the developer to work, but also help to create a cleaner and concise codebase. So, if you haven’t used these features yet, consider checking them all out and I am sure you’ll find the difference in your everyday coding life.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f2b29777217" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>