Next Gen JS

From Logic Wiki
Jump to: navigation, search

let & const

let and const basically replace var. You use let instead of var and

const instead of var if you plan on never re-assigning this "variable" (effectively turning it into a constant therefore).

ES6 Arrow Functions

const callMe = function(name) {
 console.log(name);
}

can also be written

const callMe = (name) => {
 console.log(name);
}

No Arguement

const callMe = () => {
 console.log('Max!');
}

One Argument

const callMe = name => {
  console.log(name);
}

Just Returning a Value

const returnMe = name => name

That's equal to:

const returnMe = name => {
 return name;
}

Exports & Imports

You got two different types of exports: default (unnamed) and namedexports

default

import someNameOfYourChoice from './path/to/file.js';

named

import { someData } from './path/to/file.js';

When importing named exports, you can also import all named exports at once with the following syntax:

import * as upToYou from './path/to/file.js'; 

Classes

class Person {
 constructor () {
    this.name = 'Max';
  }
}
const person = new Person();
console.log(person.name);

You can define methods like this:

class Person {
  name = 'Max';
  printMyName () {
     console.log(this.name); // this is required to refer to the class!
   }
}

Or like this:

class Person {
   name = 'Max';
   printMyName = () => {
      console.log(this.name);
   }
}

Inheritance

class Human {
   species = 'human';
 }

 class Person extends Human {
   name = 'Max';
   printMyName = () => {
     console.log(this.name);
    }
 }

Spread & Rest Operator

Spread

used to split up array elements or object properties

const oldArray = [1, 2, 3];
const newArray = [...oldArray, 4, 5]; // This now is [1, 2,3, 4, 5];

Using it in object

const newObject = {...oldObject, newProp:5}
const person = {
   name:'Max'
 };

 const newPerson = { 
  ...person,
  age : 28
 }
console.log(newPerson);
age:28
person : Max 

Rest

used to merge a list of function arguments into an array

function sortArgs(...args){
   return args.sort()
 }

Destructuring

Allows you to easily access the values of arrays or objects and assign them to variables. Here's an example for an array:

const array = [1, 2, 3];
const [a, b] = array;
console.log(a); // prints 1
console.log(b); // prints 2
console.log(array); // prints [1, 2, 3]

And here for an object:

const myObj = {
name: 'Max',
age: 28
}
const {name} = myObj;
console.log(name); // prints 'Max'
console.log(age); // prints undefined
console.log(myObj); // prints {name: 'Max', age: 28}

Destructuring is very useful when working with function arguments. Consider this example:

const printName = (personObj) => {
console.log(personObj.name);
}
printName({name: 'Max', age: 28});