Using Modern JavaScript — ES6

Ernesto Cobos
Modern JavaScript

The most popular language in the world in 2018 was JavaScript, so it was the most commonly used for almost six years. -These data are from StackOverflow.

So, this makes JavaScript one of the most important languages in the world.

What is Javascript?

JavaScript, is one of the most powerful and important programming languages nowadays, for three clear approaches: it is useful, practical and is available in any web browser and servers running Node.js.

Objective

In this post, I am going to show you the main features of ES6 and how to use it.

Background: Standardization


1995 Nicolas Cage won an Oscar for the movie Leaving Las Vegas as Best Actor

1995 Nicolas Cage won an Oscar, and Netscape Navigator had 80% of the Browsers market. Netscape was looking for a way to take the web to the next level, so they went with Sun (now Oracle) to find a way to use their Java Language on the Web. Also, this year Brendan Eich was hired by Netscape to create a more straightforward programming language that anyone could use, the name of this programming language was Mocca (the first name of javascript). -In less than 30 days Brendan Eich creates the first version of the language.

At this point, Javascript was a scripting language for amateurs and designers, so Java was the professional tool for rich web components.

Now, it’s important to understand the context before Nicolas Cage won an Oscar. Microsoft was also working on Internet Explorer because JavaScript changed the user experience of the web, Microsoft created their own Javascript implementation, and they called it JScript. JScript filled the same used cases of javascript but their implementation was different, so you couldn’t build websites and expect to work on Internet Explorer and Netscape, and at this point, ECMA came to the rescue. ECMAInternational is an industry association founded in 1961 dedicated to the standardization of information and communication systems.

In 1996 Netscape submitted Javascript to ECMA for standardization and kept the other implementation consistent across browsers. ECMA works in this way, every single implementation has both a Standard and a Committee, for Javascript the Standard is ECMAScript-262, and the Committee which works in that standard is the TC39.

If you look inside the ECMAScript-262 standard you can see that the term Javascript is never used, the reason behind this is that Oracle owns the trademark Javascript; instead, they use the term ECMAScript to avoid legal issues. In the real world, ECMAScript is used to the official standard and Javascript for the language in practice.

Scopes

If you’re coming to JavaScript from another programming language, a “feature” of JavaScript that will probably throw you off is that JavaScript is function scoped. What that means is that only functions introduce new scopes. However, let allows you to have a code which is block scoped, meaning anywhere we have an opening and closing curly brace we are creating a new scope.

  • Global Scope: This makes your functions and variables globally available.
  • Function Scope: You can only use your variables inside your function.
  • Block scope: we are creating a new scope anywhere we have an opening and closing curly brace.
// Global Scope
var firstFunction = function () {
// firstFunction’s Scope
var secondFunction = function () {
// secondFunction’s Scope
for(…){
// firstBlockScope
}
};
};

Note: It’s generally agreed upon that block scope is a better paradigm than function scope, that’s why organizations like Mozilla have been using let internally for years.

Variables

In Javascript we have three different variable types:

  • var: That is function scope.
  • let: That is block scope.
  • const: Everything let has, const also has. The only difference when you create a variable with const, that variable can’t be re-assigned a new reference. Notice I didn’t say that variable is unalterable. You can change the properties inside an object.

So you can do this with const

const user = {
name: ‘Tyler’,
age: 25
}
user.name = ‘Joey’

However, you can’t do this

const user = {
name: ‘Tyler’,
age: 25
}
user = {
name: ‘Joey’,
age: 25
}

This will throw a “user is already defined” error since we’re trying to re-assign the actual reference.

I prefer default with const, if I’m mutating the variable, I’ll use let.

Note: By default in JavaScript variables are initialized with “undefined” when they are created.

Hoisting

When JavaScript read your code, it moves all your variables at the top of the scope; this is referred to as Hoisting.

You write your code like this

// Global Scopeconsole.log(mazapan)
console.log(deneb)
var firstFunction = function () {
money++
let money = 10
};
var mazapan = ‘beauty’
var deneb = ‘amazing’

But JavaScript interpretes your code like this

// Hoistingvar mazapan = ‘beauty’
var deneb = ‘amazing’
console.log(mazapan)
console.log(deneb)
var firstFunction = function () {
let money = 10
money++

};

Note: this is why variables without the “var” word are global.

Array Destructuring

Destructuring allows us to extract the elements of an array and assign them to variables.

var arrayVar = [‘Ernesto’,‘Kovacs’]
var [name,lastname] = arrayVar

Object Destructuring

Destructuring allows us to extract multiple properties from an object. When you use deconstructing you make a new variable for every single prop.

function register (props) {
var { onChangeEmail, email, onChangePassword, password} = props;
}

and in a dirty way

function register (props) {
var onChangeEmail = props.onChangeEmail;
var email = props.email;
var onChangePassword = props.onChangePassword;
var password = props.password;

}

Object Destructuring with a different name

function register (props) {
var { email:e, password:p} = props;
}

Object Destructuring on function param

function register ({ email, password}) {a 

}

Shorthand property and method names

Property: If the value is the same as the property name you can omit the prop name.

function getUser (username) {
const email = getEmail(username)
return {
username,
email
}
}

Methods: If your object has inside functions you can omit the word “function.”

const actions = {
sayName () {
alert(this.name)
},
takeStep () {
this.step++
}
}

Computed properties

in ES6 computed properties allow us to have an expression to be computed as a property name on an object.

function objectify(key,value) {
return {
[key]: value
}
}

moreover, when we use this function, the result is going to be

objectify(name,Ernesto)// result
{
name: ‘Ernesto’
}

Template Strings

Template literals also know as template strings are good for string interpretation or multi-line strings.

Ordinary way

function makeGreeting (name, email, id) {
return ‘Hello, ‘ + name + ‘. We\’ve emailed you at ‘ + email
‘.Your user id is ‘ + id + ‘.’
}

Using Template Strings.

function makeGreeting (name, email, id) {
return `Hello, ${name}. We’ve emailed you at ${email}.
Your user id is ${id}.`

}

Arrow Functions

What is that? Well, they serve two main purposes:

  • More concise syntax.
  • Share lexical “this” with the parent scope.
let user;$.post( “ajax/getUser”, (data) => {
this.user = data;
});

Default Parameters

it’s a fairly common pattern to want to set initial or default values to specific parameters if those arguments aren’t specified when the function is invoked, for example, like the wait parameter below.

function hyperloop(name,value = 0, wait = 1000){

}

Compiling and Pollify

When you use some tools like Webpack is common to hear the terms compile or pollify but, what do they mean?

When Babel compiles, your code takes your syntax and run many syntaxes transforms to get compatibility with web browsers. What is not doing is adding new methods that you need for the global object.

  • Compiling: transform your syntax to a web browser compatible syntax.
  • Pollify: when you do a Pollify you are adding new functionalities to your browser code.

Imports and exports

Now with ES6 we have a standardized way of dealing with modules — as in, importing and exporting them from different files.

In this case code speaks much louder than writing, so let’s look at a bunch of examples.

You can export more than one item (called named exports) from a function and when you import those items, you can specify which of those items being exported you would like to import (called named imports). You’re not restricted to importing everything if you only care about a few properties.

// math.js
export function add (x,y) {
return x + y
}
export function multiply (x,y) {
return x * y
}
export function divide (x,y) {
return x / y
}
// main.js
import { add, multiply } from './math'
add(1,2) // 3
multiply(3,4) // 12

Fetch

Fetch is a replacement of axios, one of the main differences of fetch from axios is that axios put your data inside an object prop called data and is included in most web browsers.

async function getRepos(username) {
return fetch(`https://api.github.com/users/${username}/repos${params}&per_page=100`);
}

End

Javascript is one of the most worthy languages to master since the trend of being the most used does not seem to change. I hope that this data will serve you and any questions do not hesitate to leave it in the comments.

Ernesto Cobos

Written by

I’m a web developer with some full-stack chops, too. Currently working at Tyson Foods

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade