Javascript fundamentals in 2019

This will change no doubt. Here's where we might be right now.

Use document.querySelector and document.querySelectorAll instead of jquery.

// always returns an array
function $(selector) {
    return document.querySelectorAll(selector);
}

Don't need type='text/javascript' in a script tag.

var is deprecated. Use const and/or let

For a value that should never be changed use const , e.g.

const numWheels = 4;

For a value that can be changed, use let

let age = 0;

Destructuring

Instead of this:

const width = dims.width;
const height = dims.height;

You can write:

const {width, height} = dims;

Object declaration made easy

instead of

const width = 300;
const height = 150;
const obj = {
    width: width,
    height: height,
    area: function() {
        return this.width * this.height
    },
};

you can simplify slightly....

const width = 300;
const height = 150;
const obj = {
    width,
    height,
    area() {
        return this.width * this.height
    },
};

The spread operator

var middle = [3, 4];
var arr = [1, 2, ...middle, 5, 6];
console.log(arr);
// [1, 2, 3, 4, 5, 6]



var arr = [2, 4, 8, 6, 0];
var max = Math.max(...arr);
console.log(max);
// 8

Use class

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

more about class

Arrow functions

Instead of

thing.calc(function(value){
  return value + 2;
});

Use:

loader.load(value => {
  return value + 2;
});

Or even...

loader.load(value => value + 2);

In classic function expressions, the this keyword is bound based on the context in which it is called. With arrow functions however...it uses this from the code that contains the arrow function.

Cynthia Lee: When (and why) you should use ES6 arrow functions — and when you shouldn’t

Promises

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

Async/Await

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

Source

results matching ""

    No results matching ""