IDM 231 - digm.drexel.edudigm.drexel.edu/crs/IDM231/presentations/IDM231-08-es6.pdf · ECMAScript...
Transcript of IDM 231 - digm.drexel.edudigm.drexel.edu/crs/IDM231/presentations/IDM231-08-es6.pdf · ECMAScript...
IDM 231ECMAScript
IDM 231: Scripting for IDM I 1
The ECMAScript specification details the standards that scripting languages like JavaScript should meet. A quick history lesson: (click) JavaScript was invented by NetScape in 1995 and released as part of the Netscape Navigator browser in 1996. In response, (click) Microsoft developed a similar language called JScript. Since there were differences between the two languages, Netscape gave JavaScript to the (click) European Computer Manufacturers Association (ECMA) to develop a standard. (click) Version 1 of the standard was released in 1997, and (click) several versions have been released since then.
History
• invented in 1995 by NetScape
• Microsoft develops JScript late 1996
• European Computer Manufacturers Association (ECMA)
• version 1 released 1997
• several versions since then
IDM 231: Scripting for IDM I 2
When the sixth version of the ES specification was released, the committee in charge of the specification changed how it would release new versions going forward. Instead of having a set specification that they would release when all the features were completed, they moved to yearly releases of features that had been approved to that point. That s̓ why the ECMAScript versions starting with ES6 are named by year rather than by version number.
Versions & Releases
Version Release date
1 June 1997
2 June 1998
3 December 1999
4 Abandoned
5 December 2009
5.1 June 2011
2015 (ES6) June 2015
2016 (ES7) June 2016
IDM 231: Scripting for IDM I 3
Adds Promises, which is a simpler syntax for callback functions.Adds several syntax improvements that make code easier to read and understand.Adds block scope and easier ways to work with classes.Adds several built-in methods for working with strings, numbers, objects, and arrays.
Enhancements (ES6)
• promises
• syntax improvements
• block scope
• several built-in methods
IDM 231: Scripting for IDM I 4
Adds a simpler syntax for computation with powers.Adds an array method to check if an array includes a speci ed element
Enhancements (ES7)
• syntax for computation with powers.
• array method
IDM 231: Scripting for IDM I 5
Can I Use It
• ES6
• ES7
IDM 231: Scripting for IDM I 6
If you want to use some of the new features of ECMAScript but still support a wide range of browsers, you can use pollyfill files and transpilers. Polyfill files are JavaScript libraries that you include with your applications. Transpilers convert new JavaScript code to older versions of JavaScript code.
New Features, Old Browsers
IDM 231: Scripting for IDM I 7
A polyfill file (also called a shim file) is a JavaScript library that implements features in browsers that donʼt support them. The shim les support features that are either additions to existing objects or new objects themselves. Some examples of these are the Promise object type, and new methods of the String, Number, Math, Array, and Object object types.
Polyfills
• ES6 Shim
IDM 231: Scripting for IDM I 8
A transpiler is a program that takes code written in one language and converts it to another language. A transpiler lets you work with new ECMAScript features. Babel is a popular ES2015+ transpiler.
Transpiler
• Babel
IDM 231: Scripting for IDM I 9
Transpiler Example
{ const one = 1;
const myArray = [1, 2, 3];
for (let myNumber of myArray) { console.log(myNumber); }
const myFunction = myParameter => { console.log(`Hello ${myParameter} World`); }}
IDM 231: Scripting for IDM I 10
Let's look at a few enhancements available with ES6 that can simplify our code.
ES6 Enhancements
IDM 231: Scripting for IDM I 11
Variables that are declared outside a function have global scope so they are available to all functions. Conversely, variables that are declared inside a function have local scope so they are only available within the function.Prior to ES2015, those were the only types of scope that were available. But now, ES2015 provides a let keyword that lets you create block scope. This means that the variable is only available within the block of code in which it s̓ coded, like a while statement or a for loop.
let Keyword
IDM 231: Scripting for IDM I 12
let Example part 1
function varTest() { var x = 1; if (true) { var x = 2; // same variable! console.log(x); // 2 } console.log(x); // 2}
IDM 231: Scripting for IDM I 13
let Example part 2
function letTest() { let x = 1; if (true) { let x = 2; // different variable console.log(x); // 2 } console.log(x); // 1}
IDM 231: Scripting for IDM I 14
Variables declared with the var or let keyword can have their values re-assigned. But with ES2015, you can use the const keyword to create a constant. When you declare a constant, you must also assign its value, and its value canʼt ever be re-assigned.
const Keyword
IDM 231: Scripting for IDM I 15
const Example
const taxrate = 0.78;
let tax = subtotal + taxrate;
taxrate = 0.75; // TypeError: Assignment to constant variable
IDM 231: Scripting for IDM I 16
Arrow functions make it easier to pass a function definition as an argument to a function or method. They do that by removing a lot of the boilerplate code of a function definition.
Arrow Functions
(param1, param2) => { statements }
IDM 231: Scripting for IDM I 17
Arrow Function Examples
// Traditional ES5 functionvar phraseSplitter = function phraseSplitter(phrase) { return phrase.split(' ');}
// ES6const phraseSplitter = phrase => phrase.split(' ');
let newPhrase = phraseSplitter('Hello World');
IDM 231: Scripting for IDM I 18
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.Template literals are enclosed by the back-tick character instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}).
Template Literals
`string text ${expression} string text`
IDM 231: Scripting for IDM I 19
Multi-line Strings
// Concatinated stringconsole.log('string text line 1\n' +'string text line 2');
// Template Literalconsole.log(`string text line 1string text line 2`);
IDM 231: Scripting for IDM I 20
In order to embed expressions within normal strings, you would use the following syntax:
Expression Interpolation
var a = 5;var b = 10;console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');// "Fifteen is 15// and not 20."
IDM 231: Scripting for IDM I 21
Now, with template literals, you are able to make use of the syntactic sugar making substitutions like this more readable:
Expression Interpolation Continued
var a = 5;var b = 10;console.log(`Fifteen is ${a + b} andnot ${2 * a + b}.`);// "Fifteen is 15 and// not 20."
IDM 231: Scripting for IDM I 22
It doesn't end there either. In certain times, nesting a template is the easiest and perhaps more readable way to have configurable strings. Within a backticked template it is simple to allow inner backticks simply by using them inside a placeholder ${ } within the template. For instance, if condition a is true: then return this templated literal.
Nesting Template
const classes = `header ${ isLargeScreen() ? '' : `icon-${(item.isCollapsed ? 'expander' : 'collapser')}` }`;
IDM 231: Scripting for IDM I 23
variable: On each iteration a value of a different property is assigned to variable.iterable: Object whose iterable properties are iterated.
For Of Loop Syntax
for (variable of iterable) { statement}
IDM 231: Scripting for IDM I 24
For Of Loop Example
let iterable = [10, 20, 30];
for (let value of iterable) { console.log(value);}
// 10// 20// 30
IDM 231: Scripting for IDM I 25
ECMAScript 2015 introduces a new feature called Promises, which allows you to designate functions that should run in response to the eventual success or failure of asynchronous code.
Promises
IDM 231: Scripting for IDM I 26
Promise - Simple Example
let myPromise = new Promise((resolve, reject) => { // Create some dynamic elements and add them to the page. resolve();});
myPromise.then(() => { // Add event listeners to all of the new elements.});
IDM 231: Scripting for IDM I 27
Promise Example
let myPromise = new Promise((resolve, reject) => { document.body.appendChild(myButton); resolve('Success!');});
myPromise.then((successMessage) => { myButton.addEventListener('click', myFunction); console.log(successMessage);});
IDM 231: Scripting for IDM I 28
We're only scratching the surface here. There are dozens of additional updates and optimizations in ES6 and ES7. Once you have a strong foundation of JavaScript, it would be ideal to dive into these updates deeper and understand as much as possible about the cutting edge syntax.
The Future
IDM 231: Scripting for IDM I 29
Let's Build Something
IDM 231: Scripting for IDM I 30