Exploring ES6 – From jQuery to ES6 #1

Recently I started to migrate all my code from ES5+jQuery to ES6 for different projects. I discovered a lot of cool things. Of course, I also faced some issues and I thought would be great to share all the stuff I’m learning and fixing with the rest of the people planning to migrate to ES6 as well.

I’m gonna write a serie of small articles covering all the new ES6 features and how to migrate your code from previous ECMAScript versions or from jQuery code.

ecmascript-6

Today we’ll start with something basic but fundamental the new way of declaring variables using let and const.

This new way of declaring variables will allow you to better understand the new ECMAScript and the context.

Declaring variables in ES6 using let and const

Variables declared with let or const are block-scoped. This is great because we can avoid all the side effects and weird behaviours you can have using var.

See example:

let 
  x = 1, 
  y = 2; 

if ( x > y ) { 
  let tmp = x; 
} 

console.log( tmp ); // Error: tmp is not defined

const variables works exactly like variables declared with let but their content can’t be changed. They’re used when its content is not gonna change.

See example:

const pi = 3.14159265359;

console.log(pi); // 3.14159265359

pi = 3.14; // TypeError: Assignment to constant variable. "pi" is read-only
const 
  fs = require('fs');

fs.unlink('/tmp/hello', (err) => {
  if (err) throw err;
  console.log('successfully deleted /tmp/hello');
});

const and let will act in a more strict way and will throw more exceptions than variables declared with var. This way we’ll get alerts before deploy our code if we’re doing something ilegal or trying to access a variable that was not defined.

See example:

let
  x = 1,
  y = 2;

if ( x > y ) {
  let tmp = x;
}

console.log( tmp ); // Error: tmp is not defined

See the same example using var:

var
  x = 1,
  y = 2;

if ( x > y ) {
  var tmp = x;
}

console.log( tmp ); // undefined

The rule to follow is really simple:

  1. When possible use const. Variables declared with const won’t change its content.
  2. Otherwise use let, if the content of the variable will change.
  3. Avoid variables with var to avoid side effects.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: