Modern JavaScript
Copyright 2017 SitePoint Pty. Ltd.
Cover Design:
Natalia Balska
Notice of Rights
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 embodied in critical articles or reviews.
Notice of Liability
The author and publisher have made every effort to ensure the accuracy of the information herein. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors and SitePoint Pty. Ltd., nor its dealers or distributors will be held liable for any damages to be caused either directly or indirectly by the instructions contained in this book, or by the software or hardware products described herein.
Trademark Notice
Rather than indicating every occurrence of a trademarked name as such, this book uses the names only in an editorial fashion and to the benefit of the trademark owner with no intention of infringement of the trademark.
Published by SitePoint Pty. Ltd.
48 Cambridge Street Collingwood
VIC Australia 3066
Web: www.sitepoint.com
Email: books@sitepoint.com
About SitePoint
SitePoint specializes in publishing fun, practical, and easy-to-understand content for web professionals. Visit http://www.sitepoint.com/ to access our blogs, books, newsletters, articles, and community forums. Youll find a stack of information on JavaScript, PHP, design, and more.
Preface
It's not uncommon these days to see people complaining about just how complex JavaScript development seems to have become. We can have some sympathy with that view when it's coming from someone new to the language. If you're learning JS, it won't take long for you to be exposed to the enormity of the ecosystem and the sheer number of moving pieces you need to understand (at least conceptually) to build a modern web application. Package management, linting, transpilation, module bundling, minification, source maps, frameworks, unit testing, hot reloading... it can't be denied that this is a lot more complex that just including a couple of script tags in your page and FTPing it up to the server.
For a long time, JavaScript was looked upon by many as a joke; a toy language whose only real use was to add non-essential eye-candy, such as mouseover changes, and was often a source of weird errors and broken pages. The language is still not taken seriously by some today, despite having made much progress since those early days. It's not hard to have some sympathy with PHP developers. For better or for worse, JavaScript was (and still is) the only language supported natively by the vast majority of web browsers. The community has worked hard to improve the language itself, and to provide the tooling to help build production-grade apps.
This anthology is a collection of articles, hand-picked from SitePoints JavaScript channel with the aim of giving you a head start on modern JavaScript development. Of course, with the fast pace of change of both the language and the ecosystem, its important to keep up to date with the latest developments. Dont be left behind, head over to the channel after youve finished this book to stay abreast of new trends and techniques!
James Hibbard & Nilson Jacques, SitePoint JavaScript channel editors.
Conventions Used
Youll notice that weve used certain layout styles throughout this book to signify different types of information. Look out for the following items.
Code Samples
Code in this book is displayed using a fixed-width font, like so:
A Perfect Summer's Day
It was a lovely day for a walk.
Some lines of code should be entered on one line, but we've had to wrap them because of page constraints. An indicates a line break that exists for formatting purposes only, and should be ignored:
URL.open("http://www.sitepoint.com/responsive-web-design-real-user-testing/?responsive1");
Tips, Notes, and Warnings
Hey, You!
Tips provide helpful little pointers.
Ahem, Excuse Me ...
Notes are useful asides that are relatedbut not criticalto the topic at hand. Think of them as extra tidbits of information.
Make Sure You Always ...
... pay attention to these important points.
Watch Out!
Warnings highlight any gotchas that are likely to trip you up along the way.
Chapter 1: The Anatomy of a Modern JavaScript Application
by James Kolce
There's no doubt that the JavaScript ecosystem changes fast. Not only are new tools and frameworks introduced and developed at a rapid rate, the language itself has undergone big changes with the introduction of ES2015 (aka ES6). Understandably, many articles have been written complaining about how difficult it is to learn modern JavaScript development these days.
In this article, I'll introduce you to modern JavaScript. We'll take a look at the most recent developments in the language and get an overview of the tools and techniques currently used to write frontend web applications. If you're just starting out with learning the language, or you've not touched it for a few years and are wondering what happened to the JavaScript you used to know, this article is for you.
A Note about Node.js
Node.js is a runtime that allows server-side programs to be written in JavaScript. It is possible to have full-stack JavaScript applications, where both the front and backend of the app is written in the same language. Although this article is focused on client-side development, Node.js still plays an important role.
The arrival of Node.js had a significant impact on the JavaScript ecosystem, introducing the npm package manager and popularizing the CommonJS module format. Developers started to build more innovative tools and develop new approaches to blur the line between the browser, the server, and native applications.
JavaScript ES2015+
In 2015, the sixth version of ECMAScriptthe specification that defines the JavaScript languagewas released under the name of ES2015 (still often referred to as ES6). This new version included substantial additions to the language making easier and more feasible to build ambitious web applications. But improvements dont stop with ES2015; each year, a new version is released.
Declaring variables
JavaScript now has two additional ways to declare variables: let and const .
let is the successor to var - although var is still available, let limits the scope of variables to the block (rather than the function) they're declared within, which reduces the room for error:
// ES5
for (var i = 1; i < 5; i++) {
console.log(i);
}
// <-- logs the numbers 1 to 4
console.log(i);
// <-- 5 (variable i still exists outside the loop)
// ES2015
for (let j = 1; j < 5; j++) {
console.log(j);
}
console.log(j);
// <-- 'Uncaught ReferenceError: j is not defined'
Using const allows you to define variables that cannot be rebound to new values. For primitive values such as strings and numbers, this results in something similar to a constant, as you cannot change the value once it has been declared.
const name = 'Bill';
name = 'Steve';
// <-- 'Uncaught TypeError: Assignment to constant variable.'
// Gotcha
const person = { name: 'Bill' };
person.name = 'Steve';
// person.name is now Steve.
// As we're not changing the object that person is bound to, JavaScript doesn't complain.
Arrow functions
Arrow functions provide a cleaner syntax for declaring anonymous functions (lambdas), dropping the function keyword and the return keyword when the body function only has one expression. This can allow you to write functional style code in a nicer way.
Next page