let
and const
let
let
defines a block level variable. It can help prevent confusion in going through source code.
See the Pen UA-Let-Scoping by Jon (@Middaugh) on CodePen.
const
const
is used to generate variables that do not change.
const
We have several new feature inside of strings that are very helpful.
String concatenation is much easier with the new ES6 features. Variables can be injected into strings by using the `
(grave accent) instead of single/double quotes and using the ${x}
symbols.
^ interpolation only works within the `` ticks.
See the Pen ES6 - Interpolation by Jon (@Middaugh) on CodePen.
You can also use the `
symbol for multi line strings.
See the Pen ES6 - strings by Jon (@Middaugh) on CodePen.
Arrow functions are yet another feature introduced into ES6 that other languages leverage. Arrow functions help remove some confusion of the `this` keyword. It is very helpful, but it isn't always the best fit.
.on('click', function(){
});
.on('click', () => {
});
function(y){
var x = 3;
return x * y;
}
(y) => {
var x = 3;
return x * y;
}
var rn = function(y){
return Math.random() * y;
}
rn();
//No curly braces signifies
//it is returning the calculation.
var rn = (y) => Math.random() * y;
n(4);
Arrow functions are awesome when used with Arrays.
[].filter((element) => element.isSomething == true);
[].filter((element) => {
return element.isActive && element.isInDate
});
Module patterns have been built into JavaScript libraries for some time, but they are now available native in the language.
Module are single instances of code designed to be reused throughout an application.
Modules are heavily used in NodeJS and Angular Applications.
// /lib/math.js
export function multiply(x,u){
return x * u;
}
export const pi = 3.14
import {multiply, pi} from 'lib/math';
console.log(multiply(pi, 4));
import {multiply, pi} from 'lib/math';
import
- All imports occur before any other code{multiply, pi}
- Imported objects must be properly exported.from
'lib/math'
- Relative path to the file. .js file extension is not required. Unfortunately, modules don't natively work in browser, but we can use a tool called Babel to compile our modules into browser compatible JavaScript.
npm install --save-dev gulp-babel babel-preset-es2015
const gulp = require('gulp');
const babel = require('gulp-babel');
gulp.task('default', () => {
return gulp.src('src/app.js')
.pipe(babel({
presets: ['es2015']
}))
.pipe(gulp.dest('dist'));
});
Classes provide JavaScript a better opportunity to behave like an Object Oriented Programming Language.
You could make it behave like OOP by enforcing strict patterns.
this
starts getting complicated.You must declare a class before you use it.
class Square{
}
var sq = new Square();
A constructor is a specific method used in the initialization of a class.
There can only be one constructor per class.
class Rectangle{
constructor(height, width){
this.height = height;
this.width = width;
}
}
var rc = new Rectangle(10, 15);
The class is like a blueprint, an object is an actual instance
of the class.
No code is allowed outside of method. The
function
keyword is not required.
class Rectangle{
constructor(height, width){
this.height = height;
this.width = width;
}
calcArea(){
return this.height * this.width;
}
}
var rc = new Rectangle(10, 10);
console.log(rc.calcArea());
Get methods allow you to create dynamic read only properties without requiring the user to call a method.
class Rectangle{
constructor(height, width){
this.height = height;
this.width = width;
}
get area(){
return this.calcArea();
}
calcArea(){
return this.height * this.width;
}
}
var rc = new Rectangle(10, 10);
console.log(rc.area);
class Log{
constructor(){
this.log = [];
}
get logHistory(){
return this.log;
}
set currentLog(value){
this.log.push(value);
}
}
var lg = new Log();
lg.currentLog = 'new message';
console.log(lg.logHistory);
class Person {
constructor(){}
get fullName() {
return this.firstName + ' ' + this.lastName;
}
set fullName (name) {
var words = name.toString().split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
}
Static Methods are methods associated with a class, but are not a part of the instance of the class.
class Number{
constructor(n){
this.num = n;
}
increment(){
this.num++;
}
static square(num){
return num * num;
}
}
var x = new Number(1);
x.increment();
x.square() //error
Number.square(2); //return 4
Subclasses extend an existing class. It shares the same methods and properties of it's parent class.
class Rectangle {
constructor(height, width){
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
get area(){
return this.height * this.width;
}
}
class Square extends Rectangle{
constructor(length){
super(length, length);
this.name = 'Square';
}
}
var rect = new Rectangle(10, 5);
console.log(rect.name); //Rectangle
console.log(rect.area); //50
var sq = new Square(5);
console.log(sq.name); //Square
console.log(sq.height); //5
console.log(sq.area); //25
Person
get
method that returns the user's full name.users
search phrase
filter
and return any users that match the search phrase.A promise is the eventual result of an async operation.
let getAccountInfo = new Promise(function(resolve, reject){
let gotData = true;
if(gotData){
resolve('User is Jon');
} else {
reject('No user info');
}
});
getAccountInfo.then(function(result){
console.log(result);
}).catch(function(result){
console.log(result);
});
Pretend we have three promises we've created. How do we call them sequentially?
getAccountInfo.then(function(result){
return getUserSecurity(result);
}).then(function(result){
return getAccessLevels(result);
}).then(function(result){
console.log(result + " is the result of three calls");
});
Promise.all is used when three calls can be made concurrently instead of sequentially
Promise.all([getAccountInfo(), getUserSecurity(), getAccessLevels()]).then(function(){
console.log('All done');
});
Promise.raise fires as soon as one child finishes
Promise.raise([getAccountInfo(), getUserSecurity(), getAccessLevels()]).then(function(){
console.log('One is done');
});