32,39 €
Get up and running with all the new features of ECMAScript and explore new ways of coding with JavaScript.
Key Features
Book Description
Learn ECMAScript explores implementation of the latest ECMAScript features to add to your developer toolbox, helping you to progress to an advanced level. Learn to add 1 to a variable andsafely access shared memory data within multiple threads to avoid race conditions.
You’ll start the book by building on your existing knowledge of JavaScript, covering performing arithmetic operations, using arrow functions and dealing with closures. Next, you will grasp the most commonly used ECMAScript skills such as reflection, proxies, and classes. Furthermore, you’ll learn modularizing the JS code base, implementing JS on the web and how the modern HTML5 + JS APIs provide power to developers on the web. Finally, you will learn the deeper parts of the language, which include making JavaScript multithreaded with dedicated and shared web workers, memory management, shared memory, and atomics. It doesn’t end here; this book is 100% compatible with ES.Next.
By the end of this book, you'll have fully mastered all the features of ECMAScript!
What you will learn
Who this book is for
This book is for web developers who have some basic programming knowledge and want to learn to write cleaner code with the power of ECMAScript.
Mehul Mohan: Mehul Mohan is an independent developer and a security researcher. Currently, he is pursuing his bachelor’s degree in computer science at BITS Pilani. He aims to provide free technical knowledge to all through his website “codedamn”. He loves reading about techy stuff and you’ll often find him creating programming tutorials on his YouTube channel, codedamn; he has over 50,000 subscribers on his YouTube channel. He has been acknowledged by companies such as Google, Microsoft, Sony, Envoy, InVision, and such for his contribution as a security researcher. Narayan Prusty: Narayan Prusty is a full-stack developer with 5 years of experience. He specializes in Blockchain, Cloud, and JavaScript. His commitment has allowed him to build scalable products for start-ups, governments, and enterprises across India, Singapore, USA, and UAE. At present, Ethereum, Bitcoin, Hyperledger Fabric 1.0, IPFS, and Ripple are some of the things he uses on a regular basis to build decentralized applications. Currently, he works as a full-time full-stack and Blockchain Engineer at ConsenSys Enterprise. He starts working on something immediately if he feels it’s exciting and solves real work problems. He built a MP3 search engine at the age of 18 years and since then he has built various other applications, which are used by people around the globe. His ability to build scalable applications from top to bottom is what makes him special. Currently, he is on a mission to make things easier, faster, and cheaper using blockchain technology. Also, he is looking at possibilities to prevent corruptions and fraud and bring transparency to the world using blockchain technology.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 297
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Amarabha BanerjeeAcquisition Editor: Noyonika DasContent Development Editor: Gauri PradhanTechnical Editor: Leena PatilCopy Editor: Safis EditingProject Coordinator: Sheejal ShahProofreader: Safis EditingIndexer: Tejal Daruwale SoniGraphics:Jason MonteiroProduction Coordinator: Arvindkumar Gupta
First published: August 2015 Second edition: February 2018
Production reference: 1230218
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78862-006-2
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Mehul Mohan is an independent developer and likes to develop useful things. He has been working with JavaScript for over 5 years in multiple environments, such as mobile apps, frontend, and backend. He likes to learn and use new languages and frameworks. He runs Codedamn, his YouTube channel, which was started as a programming hobby but has been growing since then to teach various programming languages to millions of people. He's currently pursuing his bachelor's degree in computer science at BITS, Goa.
Narayan Prusty is a full-stack developer with 5 years of experience. He specializes in Blockchain, Cloud, and JavaScript. His commitment has allowed him to build scaleable products for startups, governments, and enterprise across India, Singapore, USA, and UAE. At present, Ethereum, Bitcoin, Hyperledger Fabric 1.0, IPFS, Ripple, and so on are some of the things he uses on regular basics to build decentralized applications. Currently he is a full time Full-Stack and Blockchain Engineer at ConsenSys Enterprise. He starts working on something immediately if he feels it's exciting and solves real work problem. He build a MP3 search engine at the age of 18 and since then he has build various other applications which are used by people around the globe. His ability to build scaleable applications from top-to-bottom is what makes him special. Currently he is on a mission to make things easier, faster, and cheaper using blockchain technology. And also he is looking at possibilities to prevent corruptions, fraud, and bring transparency to the world using blockchain technology.
Domenico Luciani, is a 25-year-old young passionate programmer, currently working as a software engineer for XPeppers, performing extreme programming. He graduated in computer science from the university of Palermo. He is a computer vision enthusiast and loves security, and in his free time, he takes part in bounty programs, hackathons, and dedicated open source events.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Learn ECMAScript Second Edition
PacktPub.com
Why subscribe?
PacktPub.com
Contributors
About the authors
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Getting Started with ECMAScript
The let keyword
Declaring function-scoped variables
Declaring block-scoped variables
Re-declaring variables
Closures and let keyword
The const keyword
The scope of const variables
Referencing objects using constant variables
When to use var/let/const 
Let versus var versus const performance benchmarks
Immutability in JavaScript
Object.freeze versus const
Default parameter values
The spread operator
Other uses of the spread operator
Making array values a part of another array
Pushing the values of an array into another array
Spreading multiple arrays
The rest parameter
Hoisting
Destructuring assignments
The array destructuring assignment
Ignoring values
Using the rest operator in an array destructuring assignment
Default values for variables
Nested array destructuring
Using a destructuring assignment as a parameter
Object destructuring assignments
Default values for variables
Destructuring nested objects
Using the object destructuring assignment as a parameter
Arrow functions
The value of "this" in an arrow function
Other differences between arrow and traditional functions
Enhanced object literals
Defining properties
Defining methods
Computed property names
Trailing commas and JavaScript
The semicolon dilemma
Automatic semicolon insertion in JavaScript
Where to insert semicolons in JavaScript?
Summary
Knowing Your Library
Working with numbers
The binary notation
The octal notation
The Number.isInteger(number) method
The Number.isNaN(value) method
isNaN versus Number.isNaN
The Number.isFinite(number) method
The Number.isSafeInteger(number) method
The Number.EPSILON property
Doing math
Trigonometry-related operations
Arithmetic-related operations
Exponential operator
Miscellaneous math methods
The Math.imul(number1, number2) function
The Math.clz32(number) function
The Math.sign(number) function
The Math.trunc(number) function
The Math.fround(number) function
Working with strings
The repeat(count) method
The includes(string, index) method
The startsWith(string, index) method
The endsWith(string, index) function
The indexOf(string) function
The lastIndexOf(string)
The padStart(length [, padString])
The padEnd(length [, padString])
Template strings
Expressions
Tagged template literals
Multiline strings
Raw strings
Escape sequence problem with template literals
Arrays
The Array.from(iterable, mapFunc, this) method
The Array.of(values…) method
The fill(value, startIndex, endIndex) method
The includes() method
The includes() versus the indexOf() method
The find(testingFunc) method
The findIndex(testingFunc) method
The copyWithin(targetIndex, startIndex, endIndex) function
The entries(), keys(), and values() methods
Array iteration
The map() method
The filter() method
forEach() method
some() method
Collections
ArrayBuffer
Typed arrays
Set
WeakSet
Map
WeakMap
Objects
Object.values()
Object.entries()
The __proto__ property
The Object.is(value1, value2) method
The Object.setPrototypeOf(object, prototype) method
The Object.assign(targetObj, sourceObjs…) method
Object.getOwnPropertyDescriptors()
Summary
Using Iterators
Symbols – primitive data type
The typeof operator
The new operator
Using symbols as the object property keys
The Object.getOwnPropertySymbols() method
The Symbol.for(string) method
Well-known symbols
The iteration protocol
The iterator protocol
The iterable protocol
Generator function
The return(value) method
The throw(exception) method
The yield* keyword
The for…of loop
Tail call optimization
Why tail call optimization?
Converting non-tail calls into tail calls
Summary
Asynchronous Programming
JavaScript execution model
The event loop
The call stack
Stack, queue, and Web APIs
Writing asynchronous code
Asynchronous code involving events
Asynchronous code involving callbacks
Promises and async programming
Promise states
Promises versus callbacks
Promise constructor and (resolve, reject) methods
The then(onFulfilled, onRejected) method
The catch(onRejected) method
The Promise.resolve(value) method
The Promise.reject(value) method
The Promise.all(iterable) method
The Promise.race(iterable) method
async/await – the future of asynchronous programming
async/await versus promises
The async function and await keyword
Making asynchronous code look synchronous
Summary
Modular Programming
JavaScript modules 101
Implementing modules – the old way
Immediately-Invoked Function Expression (IIFE)
Asynchronous Module Definition (AMD)
CommonJS
exports versus module.exports
Universal Module Definition (UMD)
Implementing modules – the new way
Importing/exporting modules
Named versus default exports
Naming named imports
Wildcard imports
Additional information on export
Additional information on import
Tree shaking
How tree shaking is performed
Using modules on the web
Summary
Implementing the Reflect API
The Reflect object
The Reflect.apply(function, this, args) method
The Reflect.construct(constructor, args, prototype) method
The Reflect.defineProperty(object, property, descriptor) method
Understanding the data properties and accessor properties
The Reflect.deleteProperty(object, property) method
The Reflect.get(object, property, this) method
The Reflect.set(object, property, value, this) method
The Reflect.getOwnPropertyDescriptor(object, property) method
The Reflect.getPrototypeOf(object) method
The Reflect.setPrototypeOf(object, prototype) method
The Reflect.has(object, property) method
The Reflect.isExtensible(object) method
The Reflect.preventExtensions(object) method
The Reflect.ownKeys(object) method
Summary
Proxies
Proxies in a nutshell
Terminology for proxies
Working with the Proxy API
Proxy traps
The get(target, property, receiver) method
Rules for using get trap
The set(target, property, value, receiver) method
Rules for using set trap
The has(target, property) method
Rules for using has trap
The isExtensible(target) method
Rule for using isExtensible trap
The getPrototypeOf(target) method
Rules for using getPrototypeOf trap
The setPrototypeOf(target, prototype) method
Rule for using setPrototypeOf trap
The preventExtensions(target) method
Rule for using preventExtensions trap
The getOwnPropertyDescriptor(target, property) method
Rules for using getOwnPropertyDescriptor trap
The defineProperty(target, property, descriptor) method
Rule for using defineProperty
The deleteProperty(target, property) method
Rule for deleteProperty trap
The ownKeys(target) method
Rules for using ownKeys trap
The apply(target, thisValue, arguments) method
The construct(target, arguments) method
The Proxy.revocable(target, handler) method
Use case of revocable proxy
The uses of proxies
Summary
Classes
Understanding object-oriented JavaScript
The JavaScript data types
Creating objects
Understanding the prototypal inheritance model
The constructors of primitive data types
Using classes
Defining a class
The class declaration
The class expression
The prototype methods
Getters and setters
The generator method
Static methods
Implementing inheritance in classes
Computed method names
The attributes of properties
Classes are not hoisted!
Overriding the result of the constructor method
The Symbol.species static accessor property
The new.target implicit parameter
Using super in object literals
Summary
JavaScript on the Web
HTML5 and the rise of modern JavaScript
The HTML DOM
What is the Document Object Model (DOM)?
DOM methods/properties
Using the getElementById method
Using the getElementsByTagName method
Using the getElementsByClassName method
Using the querySelector method
Using the querySelectorAll method
Modern JavaScript browser APIs
Page Visibility API - is the user still on the page?
navigator.onLine API – the user's network status
Clipboard API - programmatically manipulating the clipboard
The Canvas API - the web's drawing board
The Fetch API - promise-based HTTP requests
Fetch API customization
Accessing and modifying history with the history API
Handling window.onpopstate events
Modifying history - the history.go(distance) method
Jumping ahead - the history.forward() method
Going back - the history.back() method
Pushing on the history - history.pushState()
Pushing on the history stack - history.replaceState()
Summary
Storage APIs in JavaScript
HyperText Transfer Protocol (HTTP)
What is a TLS/SSL handshake?
Mimicking an HTTP state
Storing data with cookies
Setting cookies
The document.cookie is a strange object
Deleting cookies
Getting a cookie value
Working with localStorage
Creating a local storage entry
Getting a stored item
Removing a stored item
Clearing all the items
localStorage.getItem('key') versus localStorage.key versus localStorage['key']
Working with SessionStorage
Creating a session storage entry
Getting a stored item
Removing a stored item
Clearing all items
Handling storage changes across multiple tabs
Cookies versus local storage
The indexedDB - storing large data
Opening an indexedDB database
Handling the upgradeneeded event
Adding data to object stores
Reading data from object stores
Deleting data from object stores
Summary
Web and Service Workers
An introduction to the concept of threads
What makes something thread-safe?
What, exactly, is a deadlock?
What, exactly, is a race condition?
Introduction to web workers
Checking if worker support is available
Working with dedicated web workers
Setting up a dedicated worker
Working with dedicated workers
Listening for messages on the main script
Listening for messages on the worker script
Sending messages from the main script
Sending messages from the worker script
Error handling in workers
Terminating workers
Terminating from the worker script
Terminating from the main script
Transferring (not copying) data through postMessage
Working with shared workers
Setting up a shared worker
Working with shared workers
Listening for messages on the main script
Listening for messages on the worker script
Sending messages from parent scripts
Sending messages from the worker script
Error handling
Terminating a shared worker connection
Terminating a single parent-worker connection
Terminating a shared worker completely
Introduction to inline web workers
Same origin policy
Working with service workers
Prerequisites for service workers
Checking for browser support
The service worker life cycle
Registering a service worker
Installing service workers
Fetching with service workers
Summary
Shared Memory and Atomics
Basics of memory
Abstraction of memory management
Garbage collection
Manually managing memory
What is shared memory?
Introduction to SharedArrayBuffer
Understanding parallel programming
Parallel versus concurrent programming
Myth-busting--Parallel computation is always faster
Let's count one billion!
The race condition
What are atomics?
Information about lock and mutex
Atomics in JavaScript
Using the Atomics.load(typedArray, index) method
Using the Atomics.add(typedArray, index, value) method
Using the Atomics.sub(typedArray, index, value) method
Using the Atomics.and(typedArray, index, value) method
How bitwise AND works
Using the Atomics.or(typedArray, index, value) method
How bitwise OR works
Using the Atomics.xor(typedArray, index, value) method
How bitwise XOR works
Fixing one billion count with atomics
The optimized fix
A peek into Spectre
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
JavaScript is an integral part of web development and server-side programming. Understanding the fundamentals of JavaScript can not only help a person create interactive web applications but also help set up web servers, create mobile applications through frameworks such as React Native, and even create desktop applications using frameworks such as electronJS.
This book introduces the fresh and core concepts of JavaScript in the form of ECMAScript 2017 (ES8), which includes everything you'll need to get started with JavaScript and have a basic-to-advanced understanding so that you can implement everything mentioned in the first paragraph.
This book is for anybody who is absolutely new to JavaScript and is willing to learn this technology. This book can also be used by people who are familiar with old JavaScript and want to level up their knowledge to the latest standard and use techniques. For more advanced users, this book can be used to brush up concepts such as modularity, web workers, and shared memory.
Chapter 1, Getting Started with ECMAScript, discusses what ECMAScript really is and why we call it ECMAScript and not JavaScript. It also discusses how to create variables, perform basic operations, and provides new ways to do those operations in ES8.
Chapter 2, Knowing Your Library, demonstrates all the functions you need to know as a beginner and intermediate JavaScript developer to work smoothly on various kinds of projects. The functions taught in this chapter are universal and generic functions, which you'll be able to understand and apply anywhere they're necessary for your code.
Chapter 3, Using Iterators, covers how to iterate over iteratable things in JavaScript the proper way. We discuss Symbol, a new native JavaScript type, what it is, and why we need it. We also discuss the tail call optimization technique, which is implemented by browsers to speed up the code.
Chapter 4, Asynchronous Programming, explores modern ways to implement asynchronous programming and compares it with the not-so-beautiful past approaches, which included callback hell. It'll teach you about implementing asynchronous programming in a synchronous way.
Chapter 5, Modular Programming, discusses modularizing your JavaScript code into different files so that it is easy to reuse and debug individual modules. We start with primitive and third-party solutions available earlier and then cover the native support browsers are bringing to the world.
Chapter 6, Implementing the Reflect API, demonstrates information about the Reflect API provided in JavaScript, which basically helps to manipulate the properties and methods of the objects.
Chapter 7, Proxies, introduces a new implementation in JavaScript, that is, proxies over objects. It has a number of advantages, such as hiding private properties, setting default values for object properties and methods, and making awesome custom features. Such as Python-like array slicing for JavaScript.
Chapter 8, Classes, explores classes, how they're implemented, inheritance in classes, and how finally classes is just a syntatic sugar over the function implementation only. This is important because classes make the code more readable and understandable to people coming from an OOP background.
Chapter 9, JavaScript on the Web, explores the basics of using JavaScript on websites, some popular APIs exposed by browser on the web to the developers, and how JavaScript can be used to interact with the DOM to manipulate things on a web page.
Chapter 10, Storage APIs in JavaScript, explores the available storage APIs in web browsers and shows how to make use of them to store data locally on the user's computer.
Chapter 11, Web and Service Workers, discusses web workers available in HTML5, service workers for progressive web apps, and shows how to use these workers efficiently to distribute loads of tasks.
Chapter 12, Shared Memory and Atomics, teaches us how to harness a multithreaded environment provided by web workers using shared memory to allow blazingly fast access to memory by the web workers through SharedArrayBuffer. It covers some of the common problems related to threads sharing the same data, and also provides solutions to those problems.
Although it's not strictly required, it'll be great if you know a little about HTML/CSS and a little about how to create basic web pages using it.
You should be familiar with a modern browser (Chrome or Firefox is preferred) on a desktop/laptop.
To get the most out of this book, don't just read the book alone; keep other study sources open and implement as many of the demo and example codes as you can.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learn-ECMAScript-Second-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
ECMAScript 2017 (ES8) was released at the end of June 2017 by Technical Committee number 39 (TC39). It's part of ECMA, the institution that standardizes the JavaScript language under the ECMAScript specification. Currently, the standard aims to publish a new ES specification version once a year. ES6 was published in 2015 and ES7 was published in 2016. A lot changed when ES6 was released (arrow functions, classes, generators, module loaders, async programming, and so on) and even more interesting stuff keeps happening, as time goes by.
In this chapter, we'll be starting off with the fundamentals of JavaScript, starting off with ES6 basics and heading towards ES8 stuff. Furthermore, we'll be taking a look at some interesting aspects of traditional JS such as closures, and some new ones such as arrow functions.
As an autodidact, I highly recommend not only reading this book, but also trying to apply whatever you're learning here in some small but interesting projects. This will help you to retain a lot of stuff effortlessly.
In this chapter, we'll be covering:
Creating block-scoped variables using the
let
keyword
Creating constant variables using the
const
keyword
The spread operator and the rest parameter
Hoisting
Extracting data from iterables and objects using a destructuring assignment
Arrow functions
Closures and how to deal with them
Use of semicolons in JavaScript
Benchmarking
let
versus
var
versus
const
The new syntaxes for creating object properties
The let keyword is used to declare a block-scoped variable (more on this later), optionally initializing it to a value. Programmers who come from a different programming language background, but are new to JavaScript, often end up writing error-prone JavaScript programs, believing that the JavaScript variables created using the traditional var keyword are block-scoped. Almost every popular programming language has the same set of rules when it comes to the variable scopes, but JavaScript acts a bit differently due to a lack of block-scoped variables. Due to the fact that JavaScript variables are not block-scoped, there are chances of memory leaks and JavaScript programs are harder to read and debug.
