[1, 5, 3, 10, 12].forEach(v => {
if (v % 5 === 0)
fives.push(v);
});
Statement bodies
let numbers = [1, 3, 5, 3, 6, 8];
var added = numbers.map(v => v + 1);
Expression bodies
function f() {
{
let x;
{
x = "foo";
}
// error, already
//declared in block
let x = "inner";
}
}
Let is the new var (block scope)
Const is #stfu
const a = 'forevernever';
//Boom!
a = 'notsomuch';
function f(x, y=12) {
// y is 12 if not passed
return x + y;
}
Default
function f(x, ...y) {
// y is an Array
return x * y.length;
}
Rest (Splat)
class Animal extends Creature {
constructor() {
super();
}
eat(camera) {
super.update();
}
get legs() {
return this.bones;
}
set moveing(moving) {
this.moving = moving;
}
}
Prototypes become classes
function f(x, y, z) {
return x + y + z;
}
// Pass each elem of
// array as argument
f(...[1,2,3]) == 6
Spread
class Array {
constructor(...args) { /* ... */ }
static [Symbol.create]() {
}
}
Subclassing
// lib/math.js
export function sum(x, y) {
return x + y;
}
export var pi = 3.141593;
Export
import * as math from "lib/math";
console.table({
'2π': math.sum(math.pi, math.pi)
});
Import
function timeout(duration = 0) {
return new Promise((resolve, reject) => {
setTimeout(resolve, duration);
})
}
Promises
var height: number = 6;
var name: string = "bob";
var isDone: boolean = false;
var list:number[] = [1, 2, 3];
var list:Array<number> = [1, 2, 3];
enum Color {Red, Green, Blue};
var notSure: any = 4;
function warnUser(): void {
alert("This is my warning message");
}
Types
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
Interfaces
interface SquareConfig {
color?: string;
width?: number;
}
Optionals
interface SearchFunc {
(
source: string,
subString: string
): boolean;
}
Function Types
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
Single line (interpolated)
`In JavaScript
this is
not legal.`
Multi line #wow
class Flies {
fly() {
alert('Flies!');
}
}
class Climbs {
climb() {
alert('Climbs!');
}
}
class Bulletproof {
deflect() {
alert('Cant kill it');
}
}
class BeetleGuy implements Climbs, Bulletproof {
climb: () => void;
deflect: () => void;
}
//This is no magic :(
applyMixins (BeetleGuy, [Climbs, Bulletproof]);
Mixins
module Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
var lettersRegexp = /^[A-Za-z]+$/;
var numberRegexp = /^[0-9]+$/;
export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
}
import validation = require('./Validation');
Modules