by rajaraodv

5 JavaScript “Bad” Parts That Are Fixed In ES6

iS5beNL2qeunl19lw1J5qOqO3T3unGlJ4MSm

ECMAScript 6 (ES6) features can be divided into features that are pure syntactic sugar (like: class), features that enhance JavaScript (like import) and features that fix some of JavaScript’s “bad” parts (like the let keyword). Most blogs and articles combine all three types, and can overwhelm newcomers. So I’m writing this post that focuses on just the key ES6 features that fix “bad” parts.

I hope that by the end of this blog you’ll realize that by using just a couple ES6 features like let and the fat-arrow, you’ll get massive returns.

OK, Let’s get started.

1. Block Scope

ES5 only had “function-level scope” (i.e. you wrap code in functions to create scope) and caused a lot of issues. ES6 provides “block”-level scoping(i.e curly-braces to scope) when we use “let” or “const” instead of “var”.

Prevent Variable Hoisting Outside of Scope

Below picture shows that the variable “bonus” is not hoisted outside of the “if” block making work as most programming languages.

Note: You can click on the pictures to zoom and read
9FJydx6UlmUycsw0InaURd9mceYbaBOoplVc

Prevent Duplicate Variable Declaration

ES6 doesn’t allow duplicate declaration of variables when we declare them using “let” or “const” in the same scope. This is very helpful in avoiding duplicate function expressions coming from different libraries (like the “add” function expression below).

LYXvvQvqzpsq4lIZDi9np-I371PgBWjk1M28

Eliminates The Need For IIFE

In ES5, in cases like below, we had to use Immediately Invoked Function Expression (IIFE) to ensure we don’t not pollute or overwrite the global scope. In ES6, we can just use curly braces ({}) and use const or let to get the same effect.

p9vja10g1seIjyLnc3QYucY4VCZ11xg1dJaN

babel — A Tool to convert ES6 to ES5

We need to ultimately run ES6 in a regular browser. Babel is the most popular tool used to convert ES6 to ES5. It has various interfaces like a CLI, Node-module and also an online converter. I use the node module for my apps and use the online version to quickly see the differences.
Below picture shows how Babel renames the variables to simulate “let” and “const”!
7dFctBbozGKRW2ivDmX3zpc5od6PEiQwAxXJ
BabelJS.io renaming variables to simulate let and const

Makes It Trivial To Use Functions In Loops

In ES5, if you had a function inside a loop (like for(var i = 0; i < 3; i++) {…}), and if that function tried to access the looping variable “i”, we’d be in trouble because of hoisting. In ES6, if you use “let”, you can use functions without any issue.

SoAkDH4c6Z9CYxs8X7dTM52a3JefjhLGYTbB
Note: You can’t use const because it is constant unless you are using the new for..of loop.

2. Lexical “this” (via Arrow Functions)

In ES5, “this” can vary based on “where” it is called and even “how” it is called and has caused all sorts of pains for JS developers. ES6 eliminates this major issue by “lexical” this.

Lexical “this” a feature that forces the variable “this” to always point to the object where it is physically located within.

The problem and two workarounds in ES5:

In the below picture, we are trying to print a user’s firstName and salary. But we are getting the salary from the server (simulated). Notice that when the response comes back, “this” is “window” instead of the “person” object.

l7TGRBGNkWr-gXZhGl24gIuXuGvg6-F59NSt
ES5 — the problem and two workarounds

The Solution in ES6

Simply use the fat-arrow function => and you get the lexical “this” automatically.

fwFpXGvPX0o4fjxH3ar5Q0KoPysTif17sp5U
Line 16 shows how to use => function in ES6
The below picture shows how Babel converts fat-arrow function into regular ES5 function w/ workaround so that it works in current browsers.
LJfIVFoY6SUill6l32oESh1zLtPthI6nVDCr
babel is converting fat-arrow to regular ES5 function w/ workaround #2

3. Dealing With “arguments”

In ES5, “arguments” acts like an Array (i.e. we can loop over it), but is not an Array. So, all the Array functions like sort, slice and so on are not available.

In ES6, we can use a new feature called “Rest” parameters. It’s represented with 3 dots and a name like …args. Rest parameters is an Array and so we can use all the Array functions.

Hlk7i7KXhBGbyBPt2R0YVlfbxqj0DwNmzf9B
Picture shows ES6 “Rest” parameters

4. Classes

Conceptually, there is no such thing as a “Class”(i.e. blueprint) in JS like it is in other OO languages like Java. But people for a long time have treated the “function” (aka “function constructors”) that creates Objects when we use the “new” keyword as Classes.

And since JS doesn’t support the “Classes” and just simulates it via “prototypes”, it’s syntax has been very confusing for both existing JS developers and new comers who wants to use it in a traditional OO fashion. This is especially true for things like: creating subclasses, calling functions in parent class and so on.

ES6 brings a new syntax that’s common in various programming languages and makes the whole thing simple. Below picture shows a side-by-side comparison of ES5 and ES6 classes.

Note: You can click on the picture to zoom and read
b4odOVjDfpH6zTop1QLUFswTJCPudtFOY2Gw
ES5 Vs ES6 (es6-features.org)
UPDATE: Be sure to read: Is “Class” In ES6 The New “Bad” Part? (after this)

5. Strict Mode

Strict Mode(“use strict”) helps identify common issues (or “bad” parts) and also helps with “securing” JavaScript. In ES5, the Strict Mode is optional but in ES6, it’s needed for many ES6 features. So most people and tools like babel automatically add “use strict” at the top of the file putting the whole JS code in strict mode and forcing us to write better JavaScript.

That’s it! ?

If this was useful, please click the clap ? button down below a few times to show your support! ⬇⬇⬇ ??

https://medium.com/@rajaraodv/latest

ECMAScript 2015+

  1. Check out these useful ECMAScript 2015 (ES6) tips and tricks
  2. 5 JavaScript “Bad” Parts That Are Fixed In ES6
  3. Is “Class” In ES6 The New “Bad” Part?

Terminal Improvements

  1. How to Jazz Up Your Terminal — A Step By Step Guide With Pictures
  2. Jazz Up Your “ZSH” Terminal In Seven Steps — A Visual Guide

WWW

  1. A Fascinating And Messy History Of The Web And JavaScript

Virtual DOM

  1. Inner Workings Of The Virtual DOM

React Performance

  1. Two Quick Ways To Reduce React App’s Size In Production
  2. Using Preact Instead Of React

Functional Programming

  1. JavaScript Is Turing Complete — Explained
  2. Functional Programming In JS — With Practical Examples (Part 1)
  3. Functional Programming In JS — With Practical Examples (Part 2)
  4. Why Redux Need Reducers To Be “Pure Functions”

WebPack

  1. Webpack — The Confusing Parts
  2. Webpack & Hot Module Replacement [HMR] (under-the-hood)
  3. Webpack’s HMR And React-Hot-Loader — The Missing Manual

Draft.js

  1. Why Draft.js And Why You Should Contribute
  2. How Draft.js Represents Rich Text Data

React And Redux :

  1. Step by Step Guide To Building React Redux Apps
  2. A Guide For Building A React Redux CRUD App (3-page app)
  3. Using Middlewares In React Redux Apps
  4. Adding A Robust Form Validation To React Redux Apps
  5. Securing React Redux Apps With JWT Tokens
  6. Handling Transactional Emails In React Redux Apps
  7. The Anatomy Of A React Redux App
  8. Why Redux Need Reducers To Be “Pure Functions”
  9. Two Quick Ways To Reduce React App’s Size In Production

If this was useful, please click the clap ? button below a few times to show your support! ⬇⬇⬇ ??