Common JavaScript syntax
Variable declarations
Use const
for values that cannot change. Use let
otherwise.
Rule of thumb: Always use const
unless absolutely necessary.
const PI = 3.14159;
let willChange = 2;
Classes
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea();
}
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log(square.area); // 100
Similarly, in ECMAScript 5:
function Rectangle (height, width) {
this.height = height;
this.width = width;
this.area = height * width;
}
var square = new Rectangle(10, 10);
console.log(square.area); // 100
Arrow Functions
These functions are commonly used in other functions. For example:
const arr = [1, 2, 3, 4, 5];
const squared = arr.map(elem => elem**2); // [2, 4, 9, 16, 25]
Please note:
- If no brackets are used to surround the body, only one expression can be written and that expression will be returned.
- A single parameter does not need to be wrapped in parentheses (though it can be). Zero or multiple parameters must be wrapped in parentheses.
Similarly, in ECMAScript 5:
var arr = [1, 2, 3, 4, 5];
var squared = arr.map(function (elem) {
return elem ** 2;
});
Template Literals
This allows developers to finally use string interpolation.
const pokemonName = 'bulbasaur',
url = `http://pokeapi.co/api/v2/pokemon/${pokemonName}`;
Similarly, in ECMAScript 5:
var pokemonName = 'bulbasaur',
url = 'http://pokeapi.co/api/v2/pokemon/' + pokemonName;
For more about the changes made from ES5 to ES6, visit es6features.
Classwork
- Write a function that logs the numbers from 1 to n. For multiples of three, log "Fizz" instead of that number. For the multiples of five, log "Buzz" instead of that number. For multiples of both three and five, log "FizzBuzz" instead.
- Action
- Temperature Converter
- Cat and Mouse
Homework
- Complete the JavaScript section of Codecademy.
- Get as far as possible in the JavaScript section of Free Code Camp.