[go: up one dir, main page]

0% found this document useful (0 votes)
15K views47 pages

JS Es15

Template literals provide a cleaner syntax for string interpolation in JavaScript. Default parameter values allow defining default values for function parameters if no argument is passed for that parameter. Arrow function expressions provide a concise syntax as an alternative to regular function expressions. Spread syntax allows spreading/expanding array elements or property values into a function's parameters, an array, or an object literal.

Uploaded by

Bryan Blanchot
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15K views47 pages

JS Es15

Template literals provide a cleaner syntax for string interpolation in JavaScript. Default parameter values allow defining default values for function parameters if no argument is passed for that parameter. Arrow function expressions provide a concise syntax as an alternative to regular function expressions. Spread syntax allows spreading/expanding array elements or property values into a function's parameters, an array, or an object literal.

Uploaded by

Bryan Blanchot
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

ES2015 JavaScript

ES2015 or ES6?
What should we call it?
● You will see both ES2015 and ES6 used to describe the current widely-released
version of JavaScript
● The official specification is called ECMAScript 2015 Language, but that is for
the language specification and NOT the implemented coding language
● There is not an officially preferred name; you may use either ES2015 or ES6 to
refer to the current JS release
ES2015 JavaScript
Template Literals
Life Before Template Literals
function sayHello(name) { ● Traditionally, when you want to use a
console.log('Hello ' + name + '!'); variable's value as part of a string, you have
} to use string concatenation to combine the
pieces of the string together
sayHello('John'); ● You have to be careful with spacing and
punctuation, otherwise you might get
something like: HelloJohn!
Template Literals to the Rescue
function sayHello(name) { ● A template literal is a special type of string
console.log(`Hello ${name}!`); that is denoted by backticks (`) instead of
} single or double quotes
● Inside a template literal, everything is
sayHello('John'); assumed to be a character unless you
interpolate it
● Interpolation is the process of evaluating a
JavaScript expression or variable and
outputting its value
● To interpolate, surround the variable or
expression with the interpolation syntax:
${someVar}

● When using template literals, our statements flow more naturally and we aren't
prone to spacing or punctuation errors
ES2015 JavaScript
Default Parameter Values
Life Before Default Parameter Values
function greet(name) { ● If an argument is not passed into a function
alert(`Hello ${name}!`); when it is called, the parameter will be
} undefined

greet('James'); // Hello James!


greet(); // Hello undefined!
Life Before Default Parameter Values
function greet(name) { ● To prevent this, you could check and see
if (name === undefined) { whether the parameter is undefined, and if
name = 'World'; so, assign a default value to it
}
alert(`Hello ${name}!`);
}

greet('James'); // Hello James!


greet(); // Hello World!
Using Default Parameter Values
function greet(name = 'World') { ● A default parameter value looks like an
alert(`Hello ${name}!`); assignment statement in the parameter list
} ● The assignment only occurs if an argument
is not passed into the function to fill that
greet('James'); // Hello James! parameter
greet(); // Hello World!
Mixing Defaults and Non-Defaults
function product(a = 1, b) { ● You can have some parameters with
console.log(a * b); default values and some without
} ● Although having your default parameters
first is not technically an error, it is a poor
product(2, 3); // 6 practice
product(2); // NaN ● In this example, the function works as
expected when sent two arguments
● When a single argument is sent, that value
is set into the a parameter, and b is
undefined
○ 2 * undefined = NaN (Not a Number)
Mixing Defaults and Non-Defaults
function product(a, b = 1) { ● By making sure your default parameter
console.log(a * b); values are at the end of the parameter list,
} you will have the option of leaving
arguments out when you call the function
product(2, 3); // 6 ● In this example, this function behaves as an
product(2); // 2 identity function if you pass just a single
value in
ES2015 JavaScript
Arrow Function Expressions
Arrow Function Expression
let btn = document.getElementById('my-btn'); ● An arrow function, or arrow function
expression, is a more concise
// Using standard function expression representation of a function expression
btn.addEventListener('click', function() {
● This example compares using a standard
alert('Hello!');
function expression in a click listener to
});
using an arrow function
// Using arrow function ● The primary difference in syntax is that you
btn.addEventListener('click', () => { DO NOT use the function keyword when
alert('Hello!'); writing an arrow function
}); ● You also need to add an arrow ( => )
between the parameter parenthesis and
the function body curly braces
Another Example
let add = (a, b) => { ● Here is another example of an arrow
alert(a + b); function
}; ● Once you get used to the missing function
keyword and the extra arrow, you can see
add(5,4); they are very similar syntactically
● However, there are many popular
shorthands that you will see on the web
○ Many of these make it hard to read and
understand the arrow expression
Shorthand: Single Parameter
// shorthand ● When an arrow function has a single
let greet = name => { parameter, you may discard the
alert(name); parenthesis around the parameter list
}; ● Note that when you have no parameters, or
more than one parameter, you must have
// equivalent to: parenthesis
let greet = (name) => {
alert(name);
};

greet('Jane');
Shorthand: Concise Body
// shorthand ● If an arrow function simply needs to return
let add = (a, b) => a + b; a value that can be easily accessed or
computed, you can use the concise body
// equivalent to: shorthand
let add = (a, b) => { ● With a concise body, you DO NOT use curly
return a + b; braces to specify the body of the arrow
}; function
● You simply place a variable or expression
let sum = add(5,4); right after the arrow, and that value will be
console.log(sum); returned by the arrow function
Shorthand: Concise Body
let getStats = (a, b) => ({ ● When using the concise body shorthand,
sum: a + b, you must surround a returned object literal
difference : a - b, with parenthesis
product: a * b,
quotient: a / b
});

let result = getStats(4, 2);


console.log(result);
How obscure can you go?
let p1 = {
firstName: 'Jane',
lastName: 'Doe',
age: 29
};

// Most verbose
let getFullName = (person) => {
return `${person.firstName} ${person.lastName}`;
};

let result = getFullName (p1);


console.log(result);
How obscure can you go?
let p1 = {
firstName: 'Jane',
lastName: 'Doe',
age: 29
};

// single parameter shorthand


let getFullName = person => {
return `${person.firstName} ${person.lastName}`;
}

let result = getFullName (p1);


console.log(result);
How obscure can you go?
let p1 = {
firstName: 'Jane',
lastName: 'Doe',
age: 29
};

// single param shorthand, concise body


let getFullName = person => `${person.firstName} ${person.lastName}`;

let result = getFullName (p1);


console.log(result);
ES2015 JavaScript
Spread Syntax
Spreading Values in a Function Call
function add(a, b, c) { ● If you have an array of values, you can use
console.log(a + b + c); the spread operator (...) to send the
} values into a function as arguments
● Basically, the spread operator is taking a
let enteredValues = [5, 2, 7]; list of values and breaking them out into a
comma separated list
add(...enteredValues );

// same as:
add.apply(null, enteredValues );

// same as:
add(5, 2, 7);
Spreading Values in an Array
let low = [0, 1, 2]; ● You can use the spread operator to unfurl
let high = [7, 8, 9]; the values of an array into another array

let n = [...low, 3, 4, 5, 6, ...high];

console.log(n);
// [0,1,2,3,4,5,6,7,8,9]
Spreading a String
let str = 'Code'; ● You can use the spread operator to spread
the characters of a string into an array
let chars = [...str];

console.log(chars);
// [ 'C', 'o', 'd', 'e' ]
ES2015 JavaScript
Object Literal Property Shorthand
Property Names in Object Literals
function getStats(a, b) { ● This function has local variables
let resultAdd = a + b; resultAdd and resultSub, and it
let resultSub = a - b; packages those values up in an object literal
before returning it
return { ● We picked the names of the local variables,
sum: resultAdd, as well as the names of the properties in the
difference : resultSub object (sum, difference )
}; ● When we log stats to the console, we will
} see an object with properties sum and
difference
let stats = getStats(4,2);
console.log(stats);
Property Names in Object Literals
function getStats(a, b) { ● There is nothing that says our property
let sum = a + b; names cannot be the same as the variable
let difference = a - b; names we are accessing
● This example functions the exact same as
return { before
sum: sum, ● When you are defining an object literal, the
difference : difference word to the left of the : is the name of the
}; property you are choosing to put on the
} object
● The value after the : is going to be the
let stats = getStats(4,2);
value for that property
console.log(stats);

● So in this example, starting on the right, we are accessing the sum variable,
getting its value, and setting that as the value of the sum property for the object
literal we are creating
Property Name Shorthand
function getStats(a, b) { ● When a property name is the same as the
let sum = a + b; variable that will fill its value, you can
let difference = a - b; simply use the property/variable name
once and omit the :
return { ● This shorthand is often written on one line
sum,
difference
};

// or:
return { sum, difference };
}

let stats = getStats(4,2);


console.log(stats);
ES2015 JavaScript
Destructuring Assignment
Destructuring Assignment
● Destructuring assignment syntax allows us to unpack values from an array or
object and assign them into their own, separate variables
● In basic terms, destructuring is an opportunity to take a larger piece of
structured data, and pick out just the pieces you need into conveniently named
variables
● Destructuring can be performed on arrays and objects
Destructuring Assignment with Arrays
let [a, b, c] = ['Apple', 'Banana', ● This is not a technique you will frequently
'Pear']; use, but you may stumble across it online so
it is important to see how it works
console.log(a); // 'Apple' ● The values are unpacked from the array
console.log(b); // 'Banana' and placed into variables in the
console.log(c); // 'Pear' corresponding order: 'Apple' gets placed
into created variable a, 'Banana' gets
placed into created variable b, and 'Pear'
gets placed into created variable c
Destructuring Assignment with Objects
let p1 = { ● This technique is used often
firstName: 'Jane', ● The right-hand-side of the equal sign is an
lastName: 'Doe', object (object literal, variable containing an
age: 29 object, function that returns an object, etc)
}; ● The left-hand-side is where you specify the
property names you want to pull out as
let { firstName } = p1; separate variables
● You don't have to grab all the properties
// can do multiple
let { lastName, age } = p1;

console.log(firstName); // 'Jane'
console.log(lastName); // 'Doe'
console.log(age); // 29
Object Destructuring: Default Values
let p1 = { ● You can specify a default value for a
firstName: 'Jane', destructured property
lastName: 'Doe', ● The default value will be used if the object
age: 29 does not contain the property you are
}; trying to unpack

let { firstName, gender = 'F' } = p1;

console.log(firstName); // 'Jane'
console.log(gender); // 'F'
Object Destructuring: Renaming Properties
let p1 = { ● This is a non-obvious syntax
firstName: 'Jane', ● First you specify the property you want to
lastName: 'Doe', unpack from the object
age: 29 ● You then specify a new name for it after a :
}; ● The variable that is created with the
unpacked value will use the new name
let { firstName: fName } = p1;

console.log(fName); // 'Jane'
Array Destructuring in Function Parameters
function myFunc([op1, op2]) {
console.log(op1);
console.log(op2);
}

let myArray = [12, 7];

myFunc(myArray);
Object Destructuring in Function Parameters
function myOtherFunc ({ lat, lng }) {
console.log(lat);
console.log(lng);
}

let address = {
street: '123 Main St' ,
city: 'Birmingham' ,
state: 'AL',
lat: '33.514961' ,
lng: '86.807853'
};

myOtherFunc (address);
ES2015 JavaScript
JavaScript Modules
JavaScript Modules
● JavaScript module syntax allows code to be exported from and imported into
other files
● Relies on the import, export, and default keywords
Exporting at Declaration
// myStuff.js ● Exporting is a passive act; you are simply
marking something as being available for
export function sayHello(name) { import elsewhere
alert(`Hello ${name}!`); ● To make a function or variable available for
} import in another module (file), simply
place the export keyword in front of the
export let cityCode = 'BHM'; declaration

export const MAX_SEATS = 20;


Exporting Later
// myStuff.js ● This syntax allows you to later specify
which functions/variables will be available
function sayHello(name) { outside this module
alert(`Hello ${name}!`); ● In this example, the MAX_SEATS constant
} was not included in the export, so it will
NOT be available for import elsewhere
let cityCode = 'BHM';

const MAX_SEATS = 20;

export { sayHello, cityCode };


Default Export - Function
// myStuff.js ● So far, we've seen examples of named
exports
export default function sayHello(name) { ● If you have one, main piece of code you
alert(`Hello ${name}!`); want to be exported from this module, you
} can use a default export
● To do that, use the default keyword
export let cityCode = 'BHM'; ● This example contains a default export of
function sayHello and named exports of
export const MAX_SEATS = 20; cityCode and MAX_SEATS
Default Export - Variable/Constant
// myStuff.js ● While the default keyword can be used
in a function declaration, it cannot be used
export function sayHello(name) { inline with a variable/constant declaration
alert(`Hello ${name}!`); ● Instead, you must first declare the
} variable/constant, and then specify it as the
default export
// Bad
export default let cityCode = 'BHM';

// Good
let cityCode = 'BHM';
export default cityCode;

export const MAX_SEATS = 20;


import
● To import resources that have been exported from other modules, we use the
import keyword
● The import syntax varies depending on what type of export you are importing
Importing Named Exports
// myStuff.js ● To import named exports into a JS file,
export function sayHello(name) { specify the name/path to the module or
alert(`Hello ${name}!`); other file after the from keyword
} ● Reads as "import this stuff from this
module here"
export let cityCode = 'BHM'; ● Can specify one or more individually
exported items to bring into this module
export const MAX_SEATS = 20;

// app.js
import { sayHello } from './myStuff.js' ;

sayHello('Jane');
Importing All Named Exports
// myStuff.js ● You can also use the wildcard syntax to
export function sayHello(name) { grab all named exports from a module
alert(`Hello ${name}!`); ● Use the as keyword to specify a name (that
} you came up with) in which to store the
imported code
export let cityCode = 'BHM'; ● In this case, helpers will be an object with
properties sayHello, cityCode, and
export const MAX_SEATS = 20; MAX_SEATS

// app.js
import * as helpers from './myStuff.js' ;

helpers.sayHello('Jane');
Import a Default Export
// myStuff.js ● To import a default export, you simply
export default function sayHello(name) { specify a name in which to store that
alert(`Hello ${name}!`); default export, without the use of curly
} braces
○ import { greet } means "import the
export let cityCode = 'BHM'; named export greet into this module"
○ import greet means "import the default
export const MAX_SEATS = 20; export, whatever it is called, into this
module and refer to it as greet
● To clarify, the name in the import
// app.js statement is something we came up with; it
import greet from './myStuff.js' ; doesn't have to match the name of the
default export (although it can if you'd like)
greet('Jane');
Browser Support
● At this moment in time, most browsers do not support module import syntax
● To be able to use import/export, you need to use a packager
○ There are many packagers available, and many development frameworks include packager
scripts for you

You might also like