Skip to content

ES6

let

var camper = 'James';
var camper = 'David';
console.log(camper);
// logs 'David'

let camper = 'James';
let camper = 'David'; // throws an error
var printNumTwo;
for (var i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());
// returns 3
'use strict';
let printNumTwo;
for (let i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());
// returns 2
console.log(i);
// returns "i is not defined"

const

const has all the awesome features that let has, with the added bonus that variables declared using const are read-only. They are a constant value, which means that once a variable is assigned with const, it cannot be reassigned.

"use strict";
const FAV_PET = "Cats";
FAV_PET = "Dogs"; // returns error

function

const myFunc = function(param1,param2) {
  const myVar = "value";
  return myVar;
}

const myFunc = (param1,param2) => {
  const myVar = "value";
  return myVar;
}

const myFunc = (param1,param2) => "value";

Spreading

//ES5
var arr = [:fontawesome-solid-link: 6, 89, 3, 45];
var maximus = Math.max.apply(null, arr); // returns 89

//ES6
const arr = [:fontawesome-solid-link: 6, 89, 3, 45];
const maximus = Math.max(...arr); // returns 89
const arr1 = [:fontawesome-solid-link: 'JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;

arr2 = [:fontawesome-solid-link: ...arr1]; 

arr1[:fontawesome-solid-link: 0] = "newJAN";
console.log(arr1);  //[:fontawesome-solid-link:  'newJAN', 'FEB', 'MAR', 'APR', 'MAY' ]
console.log(arr2); // [:fontawesome-solid-link:  'JAN', 'FEB', 'MAR', 'APR', 'MAY' ]

Destructuring

const user = { name: 'John Doe', age: 34 };

const name = user.name; // name = 'John Doe'
const age = user.age; // age = 34
//         |
//         V
const { name, age } = user;
// name = 'John Doe', age = 34
const { name: userName, age: userAge } = user;
// userName = 'John Doe', userAge = 34
//nested
const user = {
  johnDoe: { 
    age: 34,
    email: 'johnDoe@freeCodeCamp.com'
  }
};

const { johnDoe: { age: userAge, email: userEmail }} = user;
//destructuring arrays
const [:fontawesome-solid-link: a, b] = [:fontawesome-solid-link: 1, 2, 3, 4, 5, 6];
console.log(a, b); // 1, 2

const [:fontawesome-solid-link: a, b,,, c] = [:fontawesome-solid-link: 1, 2, 3, 4, 5, 6];
console.log(a, b, c); // 1, 2, 5
//with rest parameter
const [:fontawesome-solid-link: a, b, ...arr] = [:fontawesome-solid-link: 1, 2, 3, 4, 5, 7];
console.log(a, b); // 1, 2
console.log(arr); // [:fontawesome-solid-link: 3, 4, 5, 7]
// destructuring in function
const profileUpdate = (profileData) => {
  const { name, age, nationality, location } = profileData;
  // do something with these variables
}

//or
const profileUpdate = ({ name, age, nationality, location }) => {
  /* do something with these fields */
}
//This has the added benefit of not having to manipulate an entire object in a function — only the fields that are needed are copied inside the function.

Template Literals

const person = {
  name: "Zodiac Hasbro",
  age: 56
};

// Template literal with multi-line and string interpolation
const greeting = `Hello, my name is ${person.name}!
I am ${person.age} years old.`;

console.log(greeting); // prints
// Hello, my name is Zodiac Hasbro!
// I am 56 years old.

Concise Object Literal Declarations Using Object Property Shorthand

const getMousePosition = (x, y) => ({
  x: x,
  y: y
});

//         |
//         V

const getMousePosition = (x, y) => ({ x, y });

Declarative Functions

const person = {
  name: "Taylor",
  sayHello: function() {
    return `Hello! My name is ${this.name}.`;
  }
};

//         |
//         V

const person = {
  name: "Taylor",
  sayHello() {
    return `Hello! My name is ${this.name}.`;
  }
};

Class

class Book {
  constructor(author) {
    this._author = author;
  }
  // getter
  get writer() {
    return this._author;
  }
  // setter
  set writer(updatedAuthor) {
    this._author = updatedAuthor;
  }
}
const lol = new Book('anonymous');
console.log(lol.writer);  // anonymous
lol.writer = 'wut';
console.log(lol.writer);  // wut

/*
Notice the syntax we are using to invoke the getter and setter - as if they are not even functions. Getters and setters are important, because they hide internal implementation details. Note: It is a convention to precede the name of a private variable with an underscore (_).
*/

Export/Import

//named export
const add = (x, y) => {
  return x + y;
}

export { add };
//named import
import { add, subtract } from './math_functions.js';
import * as myMathModule from "./math_functions.js";

myMathModule.add(2,3);
//default export

// named function
export default function add(x, y) {
  return x + y;
}

// anonymous function
export default function(x, y) {
  return x + y;
}

/*
Usually you will use this syntax if only one value is being exported from a file. It is also used to create a fallback value for a file or module.

Since export default is used to declare a fallback value for a module or file, you can only have one value be a default export in each module or file. Additionally, you cannot use export default with var, let, or const
*/
//default import
import add from "./math_functions.js";

Promise

/*
A promise in JavaScript is exactly what it sounds like - you use it to make a promise to do something, usually asynchronously.

When the task completes, you either fulfill your promise or fail to do so. Promise is a constructor function, so you need to use the new keyword to create one. 
It takes a function, as its argument, with two parameters - resolve and reject. These are methods used to determine the outcome of the promise.
*/

const myPromise = new Promise((resolve, reject) => {

});

/*
A promise has three states: pending, fulfilled, and rejected. The promise above will be stuck in pending state.

The resolve and reject parameters given to the promise argument are used to do this. resolve is used when you want your promise to succeed, and reject is used when you want it to fail.
*/
const makeServerRequest = new Promise((resolve, reject) => {

    //do some processing
  let responseFromServer = true;

  if(responseFromServer) {
    resolve("We got the data");
  } else {  
    reject("Data not received");
  }
});

makeServerRequest.then(result => {
  console.log(result);  // We got the data
});
const makeServerRequest = new Promise((resolve, reject) => {

  let responseFromServer = false;

  if(responseFromServer) {
    resolve("We got the data");
  } else {  
    reject("Data not received");
  }
});

makeServerRequest.then(result => {
  console.log(result);
});

makeServerRequest.catch(error => {
  console.log(error); // Data not received
});