// Function scoped var
function order(x, y) {
if (x > y) {
var tmp = x;
x = y;
y = tmp;
}
console.log(tmp === x);
// true
return [x, y];
}
// Block scoped let
function order(x, y) {
if (x > y) {
let tmp = x;
x = y;
y = tmp;
}
console.log(tmp === x);
// ReferenceError:
// tmp is not defined
return [x, y];
}
const PI = 3.14;
PI = 10;
console.log(PI); // 3.14
let obj = { first: "Jane", last: "Doe" };
let { first: f, last: l } = obj;
console.log(f + " " + l); // Jane Doe
Brukes til:
{x, y} er det samme som {x: x, y: y}.
let obj = { first: "Jane", last: "Doe" };
let { first, last} = obj;
console.log(first + " " + last); // Jane Doe
function returnMultipleValues() {
return {
foo: 1,
bar: 2
};
}
var { foo, bar } = returnMultipleValues();
let [ x, y ] = [ "a", "b" ];
// x="a", y="b"
[ x, y ] = [ y, x ] // Swap values
var [,,third] = [1, 2, 3];
console.log(third);
// 3
var [head, ...tail] = [1, 2, 3, 4];
console.log(tail);
// [2, 3, 4]
Refutable (default):
{ a: x, b: y } = { a: 3 } // fails
Default Value:
{ a: x, b: y=5 } = { a: 3 } // x=3, y=5
{ a: x, b: y=5 } = { a: 3, b: undefined } // x=3, y=5
Kan sette standardverdi for parametre som mangler
function func1(x, y=3) {
return [x, y];
}
Console:
# func1(1, 2);
[1, 2]
# func1(1);
[1, 3]
# func1();
[undefined, 3]
Legge etterfølgende parametre i en array:
function func2(arg0, ...others) {
return others;
}
Console:
# func2(0, 1, 2, 3);
[1, 2, 3]
#func2(0);
[]
#func2();
[]
Omgjøre en array til funksjon-/metodeparametre:
# Math.max(7, 4, 11);
11
# Math.max(...[ 7, 4, 11 ]);
11
var parts = ['shoulder', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];
Bruk av destructing for navngitte parametre opt1 og opt2:
function func3(arg0, { opt1, opt2 }) {
return [opt1, opt2];
}
func3(0, {opt1: "a", opt2: "b"});
// ["a", "b"]
Kortere syntaktisk form (function () {} vs () => {})
let squares = [1, 2, 3].map(function(x) { return x * x });
vslet squares = [1, 2, 3].map(x => x * x);
`=>` har leksikalsk `this` istedenfor dynamisk`this`
var that = this,
button = document.getElementById("myButton");
button.addEventListener("click", function() {
that.handleClick();
});
let button = document.getElementById("myButton");
button.addEventListener("click", () => {
this.handleClick();
});
Generell form:
(arg1, arg2, ...) => expr
(arg1, arg2, ...) => { statment1; statment2; ...}
Kortversjon - kun en parameter
arg => expr
arg => { statment1; statment2; ...}
__proto__ gjør det mulig å definere prototypisk arv:
// ECMAScript 6
let obj = {
__proto__: someObject, // special property
myMethod(arg1, arg2) { // method definition
...
}
};
// ECMAScript 5
var obj = Object.create(someObject);
obj.myMethod = function (arg1, arg2) {
...
};
ECMAScript 6
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return "(" + this.x + ", " + this.y + ")";
}
}
ECMAScript 5
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function() {
return "(" + this.x + ", " + this.y + ")";
};
ECMAScript 6
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y);
this.color = color;
}
toString() {
return this.color + " " + super();
}
}
ECMAScript 5
function ColorPoint(x, y, color) {
Point.call(this, x, y);
this.color = color;
}
ColorPoint.prototype = Object.create(Point.prototype);
ColorPoint.prototype.constructor = ColorPoint;
ColorPoint.prototype.toString = function() {
return this.color + " " + Point.prototype.toString.call(this);
};
class Point {
static zero() {
return new Point(0, 0);
}
constructor(x, y) {
this.x = x;
this.y = y;
}
}
let p = Point.zero();
// lib/math.js
export function sum(x, y) {
return x + y;
}
export var pi = 3.141593;
// app.js
import {sum, pi} from 'lib/math';
alert("2π = " + sum(pi, pi));
// app.js
module Math from 'lib/math';
alert("2π = " + Math.sum(Math.pi, Math.pi));
module 'lib/math' {
export function sum(x, y) {
return x + y;
}
export var pi = 3.141593;
}
module 'lib/string' {
export function capitalize(string) {
return string.charAt(0).toUpperCase() + string.substr(1);
}
}
import {sum, pi} from 'lib/math';
import {capitalize} from 'lib/string';
alert("2π = " + sum(pi, pi));
alert(capitalize("evry"));
System.import([
'module1',
'module2'
], function (module1, module2) { // success
...
}, function (err) { // failure
...
});
APIet har forksjellige "hooks" man kan bruke til f.eks.:
Loader : function(options = {}) -> Loader
options: {
global: Object = Object.create(null),
intrinsics: Loader | null = null,
strict: boolean = false,
normalize: function,
resolve: function,
fetch: function,
translate: function,
link: function
}
`literal${substitution}literal`
var name = "Evry",
msg = `Hello, ${name}!`;
console.log(msg); // "Hello, Evry!"
var total = 30,
msg = `The total is ${total} (${total*1.25} with tax)`;
console.log(msg); // "The total is 30 (37.5 with tax)"
tag`literal${substitution}literal`
someFunc`literal${substitution}literal`
> let sym = Symbol();
> typeof sym
'symbol'
let red = Symbol();
let green = Symbol();
let blue = Symbol();
function handleColor(color) {
switch(color) {
case red:
...
case green:
...
case blue:
...
}
}
let specialMethod = Symbol();
let obj = {
// computed property key
[specialMethod]: function (arg) {
...
}
};
obj[specialMethod](123);
let map = new Map();
let obj = {};
map.set(obj, 123);
console.log(map.get(obj)); // 123
console.log(map.has(obj)); // true
map.delete(obj);
console.log(map.has(obj)); // false
let set1 = new Set();
set1.add('hello');
console.log(set1.has('hello')); // true
console.log(set1.has('world')); // false
let set2 = new Set([3,2,1,3,2,3]);
console.log(set2.values()); // 1,2,3
class Point {
constructor(x, y) {
Object.assign(this, { x, y });
}
}
# 'abc'.repeat(3)
'abcabcabc'
# 'abc'.startsWith('ab')
true
# 'abc'.endsWith('bc')
true
# 'foobar'.contains('oo')
true
# [13, 7, 8].find(x => x % 2 === 0)
8
# [1, 3, 5].find(x => x % 2 === 0)
undefined
# [13, 7, 8].findIndex(x => x % 2 === 0)
2
# [1, 3, 5].findIndex(x => x % 2 === 0)
-1
let arr = [ 'hello', 'world' ];
for (let elem of arr) {
console.log(elem);
}
hello
world
import items from "@iter";
let obj = { first: "Jane", last: "Doe" };
for (let [k,v] of items(obj)) {
console.log(k + " = " + v);
}
var s = Set([1, 3, 4, 2, 3, 2, 17, 17, 1, 17]);
for (var v of s) {
console.log(v);
}
let m = new Map;
m.set("one", 1);
m.set("two", 2);
for (let [name, value] of m) {
console.log(`the value of ${name} is ${value}`);
}
let numbers = [1,2,3];
let squares = [for (x of numbers) x * x];
[for (i of document.querySelectorAll('.item'))
i.textContent]
[for (x of a) for (y of b) if (x > y) [x,y]]
function arrayComprehension() {
let result = [];
for (let x of a) {
for (let y of b) {
if (x > y) {
result.push([x,y]);
}
}
}
return result;
}