11. Design goals
Compact syntax
Support cyclic dependencies
Asynchronous loading
Configurable
// lib/math.js
export function sum(x, y) {
return x + y;
}
export var pi = 3.141593;
// app.js
import * as math from "lib/math";
math.sum(22, 20); // 42
12. // Default exports and named exports
import myLib from 'src/mylib';
import { function1, function2 } from 'src/mylib';
Importing
13. // Default exports and named exports
import myLib from 'src/mylib';
import { function1, function2 } from 'src/mylib';
Importing
// Renaming: import named1 as myNamed1
import { function1 as fn, function2 } from 'src/mylib';
14. // Default exports and named exports
import myLib from 'src/mylib';
import { function1, function2 } from 'src/mylib';
Importing
// Renaming: import named1 as myNamed1
import { function1 as fn, function2 } from 'src/mylib';
// Importing the module as an object
// (with one property per named export)
import * as mylib from 'src/mylib';
15. // Default exports and named exports
import myLib from 'src/mylib';
import { function1, function2 } from 'src/mylib';
Importing
// Renaming: import named1 as myNamed1
import { function1 as fn, function2 } from 'src/mylib';
// Importing the module as an object
// (with one property per named export)
import * as mylib from 'src/mylib';
// Only load the module, don’t import anything
import 'src/mylib';
22. Spread operator
Math.max(...[1, 2, 3]);
// the same as
Math.max(1, 2, 3);
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);
23. Spread operator
Math.max(...[1, 2, 3]);
// the same as
Math.max(1, 2, 3);
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);
[head, ...tail] = [1, 2, 3, 4, 5];
24. Scope - let & const
function foo() {
a = 1;
if (a) {
var a;
let b = a + 2;
25. Scope - let & const
function foo() {
a = 1;
if (a) {
var a;
let b = a + 2;
console.log( b );
}
console.log( a );
console.log( b );
}
26. Scope - let & const
function foo() {
a = 1;
if (a) {
var a;
let b = a + 2;
console.log( b );
}
console.log( a );
console.log( b );
}
console.log( b ); // 3
}
console.log( a ); // 1
console.log( b ); // ReferenceError: `b` is not defined
}
function foo() {
a = 1; // careful, `a` has been hoisted!
if (a) {
var a; // hoisted to function scope!
let b = a + 2; // `b` block-scoped to `if` block!
27. Scope - let & const
function foo() {
a = 1;
if (a) {
var a;
let b = a + 2;
console.log( b );
}
console.log( a );
console.log( b );
}
console.log( b ); // 3
}
console.log( a ); // 1
console.log( b ); // ReferenceError: `b` is not defined
}
function foo() {
a = 1; // careful, `a` has been hoisted!
if (a) {
var a; // hoisted to function scope!
let b = a + 2; // `b` block-scoped to `if` block!
if (true) {
const foo = "foo";
// error
foo = "bar";
}