The JavaScript Workshop: Learn to develop interactive web applications with clean and maintainable JavaScript code
By Joseph Labrecque, Jahred Love, Daniel Rosenbaum and
5/5
()
Javascript
Node.js
Web Development
Functional Programming
Asynchronous Tasks
Browser Apis
Javascript Programming
Css
Object-Oriented Programming
Javascript Libraries & Frameworks
About this ebook
Get to grips with the fundamentals of JavaScript and learn to build the programming skills that will kickstart your career as a software developer
Key Features- Learn the basics of JavaScript programming to create dynamic web pages
- Explore the fundamentals of back-end development using Node.js
- Tackle challenging development problems and apply solutions to real-world situations
If you're looking for a programming language to develop flexible and efficient apps, JavaScript is a great choice. However, while offering real benefits, the complexity of the entire JavaScript ecosystem can be overwhelming. This Workshop is a smarter way to learn JavaScript. It is specifically designed to cut through the noise and help build your JavaScript skills from scratch, while sparking your interest with engaging activities and clear explanations.
Starting with explanations of JavaScript's fundamental programming concepts, this book will introduce the key tools, libraries and frameworks that programmers use in everyday development. You will then move on and see how to handle data, control the flow of information in an application, and create custom events. You'll explore the differences between client-side and server-side JavaScript, and expand your knowledge further by studying the different JavaScript development paradigms, including object-oriented and functional programming.
By the end of this JavaScript book, you'll have the confidence and skills to tackle real-world JavaScript development problems that reflect the emerging requirements of the modern web.
What you will learn- Write clean, maintainable and eloquent JavaScript code
- Build websites using plain JS and various frameworks and libraries
- Simplify your workflow with package managers such as Gulp and Grunt
- Use Node.js to build server-side JavaScript applications
- Improve the functionality of your applications with browser APIs
- Implement asynchronous programming to build apps that can multitask
The JavaScript Workshop is the ideal guide to JavaScript for beginners. It is designed for anyone who wants to get started learning JavaScript. Whether you're an aspiring web developer, or are just curious about learning how to code with a versatile programming language, this book will help you get up and running. Previous development experience is not required, but basic prior knowledge of HTML and CSS will help you get the most from this book.
Read more from Joseph Labrecque
Flash Development for Android Cookbook Rating: 3 out of 5 stars3/5Adobe Edge Quickstart Guide Rating: 0 out of 5 stars0 ratings
Related to The JavaScript Workshop
Related ebooks
JavaScript and JSON Essentials Rating: 5 out of 5 stars5/5Mastering JavaScript Rating: 4 out of 5 stars4/5JavaScript: Beginner's Guide to Programming Code with JavaScript: JavaScript Computer Programming Rating: 0 out of 5 stars0 ratingsResponsive Web Design with HTML5 and CSS3 Rating: 4 out of 5 stars4/5JavaScript Unlocked Rating: 5 out of 5 stars5/5Object-Oriented JavaScript Rating: 4 out of 5 stars4/5JavaScript: Beginner's Guide to Programming Code with JavaScript Rating: 5 out of 5 stars5/5Object-Oriented JavaScript - Third Edition Rating: 4 out of 5 stars4/5JavaScript and AJAX For Dummies Rating: 4 out of 5 stars4/5React.js Essentials Rating: 4 out of 5 stars4/5Node.js By Example Rating: 2 out of 5 stars2/5JavaScript for Gurus: Use JavaScript programming features, techniques and modules to solve everyday problems Rating: 0 out of 5 stars0 ratingsThe Joy of JavaScript Rating: 0 out of 5 stars0 ratingsReactJS for Jobseekers: The Only Guide You Need to Learn React and Crack Interviews (English Edition) Rating: 0 out of 5 stars0 ratingsMastering JavaScript Object-Oriented Programming Rating: 0 out of 5 stars0 ratingsMastering C# and .NET Framework Rating: 5 out of 5 stars5/5The PHP Workshop: Learn to build interactive applications and kickstart your career as a web developer Rating: 0 out of 5 stars0 ratingsReact and React Native Rating: 4 out of 5 stars4/5React Components Rating: 0 out of 5 stars0 ratingsJavaScript Regular Expressions Rating: 3 out of 5 stars3/5Java Programming: 24-Hour Trainer Rating: 0 out of 5 stars0 ratingsJavaScript Bible Rating: 4 out of 5 stars4/5Learning ASP.NET Core MVC Programming Rating: 5 out of 5 stars5/5Javascript Concepts: 1St Edition Rating: 0 out of 5 stars0 ratings.NET Design Patterns Rating: 3 out of 5 stars3/5Learn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5Learning JavaScript Data Structures and Algorithms Rating: 5 out of 5 stars5/5Mastering JavaScript: The Complete Guide to JavaScript Mastery Rating: 5 out of 5 stars5/5
Programming For You
Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsSQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsPython Data Structures and Algorithms Rating: 5 out of 5 stars5/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Coding with JavaScript For Dummies Rating: 0 out of 5 stars0 ratingsA Slackers Guide to Coding with Python: Ultimate Beginners Guide to Learning Python Quick Rating: 0 out of 5 stars0 ratingsLearn SQL in 24 Hours Rating: 5 out of 5 stars5/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Spies, Lies, and Algorithms: The History and Future of American Intelligence Rating: 4 out of 5 stars4/5
Reviews for The JavaScript Workshop
3 ratings1 review
- Rating: 5 out of 5 stars5/5
Feb 4, 2023
This book is enjoyable to read, with simple definitions of technical subjects. Well written and keeps my interest through practical examples.
Book preview
The JavaScript Workshop - Joseph Labrecque
The JavaScript Workshop
Copyright © 2020 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 authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.
Authors: Joseph Labrecque, Jahred Love, Daniel Rosenbaum, Nick Turner, Gaurav Mehla, Alonzo L. Hosford, Florian Sloot, and Philip Kirkbride
Reviewers: Andrew Artajos, Lior Avital, Tarunkumar N. Bagmar, Archit Goyal, Christer Johansson, Peter Kehl, Gavin Orland, David Parker, Dixit Patel, Shubham Shrivatava, and Weijie (Kenvi) Zhu
Managing Editors: Vrushti Ajmera and Anushree Arun Tendulkar
Acquisitions Editor: Sarah Lawton
Production Editor: Shantanu Zagade
Editorial Board: Bharat Botle, Megan Carlisle, Mahesh Dhyani, Manasa Kumar, Alex Mazonowicz, Bridget Neale, Dominic Pereira, Shiny Poojary, Abhishek Rane, Brendan Rodrigues, Mugdha Sawarkar, Erol Staveley, Ankita Thakur, Nitesh Thakur, and Jonathan Wray
First published: November 2019
Production reference: 5241220
ISBN 978-1-83864-191-7
Published by Packt Publishing Ltd.
Livery Place, 35 Livery Street
Birmingham B3 2PB, UK
Table of Contents
Preface
Introduction
What Is JavaScript and How Is It Used?
JavaScript versus Other Languages
Exercise 1.01: Languages Discovery
A Brief History of the JavaScript Language
Netscape Mocha and LiveScript
Sun Microsystems and Java
Ecma International and ECMAScript
Versions of ECMAScript (and JavaScript)
ECMAScript 1 (1997)
ECMAScript 2 (1998)
ECMAScript 3 (1999)
ECMAScript 4 (unreleased)
ECMAScript 5 (2009)
ECMAScript 6 (2015)
ECMAScript 7 (2016), ECMAScript 8 (2017), and ECMAScript 9 (2018)
Exercise 1.02: Can I Use This Feature?
Accessing Web Browser Developer Tools
Google Chrome
Microsoft Edge
Apple Safari
An Introduction to Variables
Exercise 1.03: Programming First Steps
Activity 1.01: Creating an Alert Box Popup in the Web Browser
Overview of JavaScript Capabilities
Client-Side Form Validation
JavaScript Widgets or Components
XML HTTP Requests (XHR)
Storing Local Data
DOM Manipulation
Animations and Effects
Summary
2. Working with JavaScript
Introduction
Integrated Development Environments (IDE)
GitHub's Atom
Sublime Text
Adobe Dreamweaver
JetBrains WebStorm
Microsoft Visual Studio Code
JavaScript Project and File Management
Project Folders and Files
Exercise 2.01: Creating a Working Project Directory
JavaScript Syntax and Structure
Exercise 2.02: Creating Project Boilerplate
Basic JavaScript Syntax
JavaScript Execution Order
Exercise 2.03: Verifying an Execution Order
Overview of JavaScript Environments
Browser-Based JavaScript
Server-Based JavaScript
Desktop JavaScript
Mobile JavaScript
A Closer Look at Web Browser Developer Tools
The Elements View
The Console View
The Sources View
The Network View
HTML Element Manipulation with JavaScript
Activity 2.01: Adding and Modifying an Item to/in the To-Do List
Summary
3. Programming Fundamentals
Introduction
Data Types
Representation of Data
Literal Values
Using Operators in Expressions
Exercise 3.01: Implementing Expressions and Operators
Using Variables and Constants in Expressions
Exercise 3.02: Working with Variables Using the Web Browser Console
Functions That Return Values
Exercise 3.03: Using Functions in Expressions
The Object Data Type
Ready-Made Objects
Exercise 3.04: Working with Ready-Made Objects
Self-Made Objects
Object Dot Notation
The Array Object
Using the Console Object
Syntax
Semicolon at the End of Code Statements
Lines of Code versus Statements
Comments
Conditional and Loop Flow
Code Blocks
Conditional Flow Statements
if...else Statement
if Statement
Exercise 3.05: Writing an if statement
if Statement and else Statement
Exercise 3.06: Writing an if...else Statement
if Statements with Multiple else...if Statements
if Statement, Multiple else...if statements, and the else Statement
Exercise 3.07: Writing an if Statement with Multiple if else Statements and the else Statement
The break Statement
switch Statement
Exercise 3.08: Writing a switch Statement and Testing It
Loop Statements
for Statement
Exercise 3.09: Writing a for Loop and Testing It
do...while Statement
Exercise 3.10: Writing a do...while Loop and Testing It
while Statement
Exercise 3.11: Writing a while Loop and Testing It
for...in Statement
Exercise 3.12: Writing a for...in Loop and Testing It
for...of Statement
Exercise 3.13: Writing a for...of Loop and Testing It
continue Statement
Labeled Statement
Writing and Invoking Functions
Defining Functions
Function Declaration
Exercise 3.14: Writing a Function as a Statement and Invoking It
Function Expression
Exercise 3.15: Writing a Function as an Expression and Invoking It
Arrow Function Expression
Defining and Invoking an Arrow Function Expression
Exercise 3.16: Writing an Arrow Function and Invoking It
Reacting to User Input Events and Updating the DOM
The DOM HTML Element Object
Getting Access to Elements in the DOM
Creating Elements and Content in the DOM
DOM Events
Exercise 3.17: Working with DOM Manipulation and Events
Debugging
Silent Fail
Syntax Bugs
Logic Bugs
Debugging
Debuggers
Activity 3.01: The To-Do List Shuffle Program
Summary
4. JavaScript Libraries and Frameworks
Introduction
Framework versus Library
Vanilla.js
Popular JavaScript Frameworks
Everlasting jQuery
Where to Find and How to Use External Code
Exercise 4.01: Using a Third-Party Library in Your Code
jQuery versus Vanilla.js
Manipulating the DOM
Making XHR Requests
Exercise 4.02: Handling Click Events with jQuery
Exercise 4.03: Handling the Same Event with Vanilla.js
UI Animation Using jQuery
Exercise 4.04: Animating a Peek-a-boo
on Button Click
Frameworks versus Core JavaScript
Exercise 4.05: Rendering a List of To-Dos Using React
Exercise 4.06: Rendering a List of To-Dos without a Library
Exercise 4.07: Creating a Library Yourself
Activity 4.01: Adding an Animation to the To-Do List Application
Summary
5. Beyond the Fundamentals
Introduction
Creating Variables
A Note on Referencing
Global Assignment
Declaring with var
Declaring with let
Declaring with const
Exercise 5.01: Variables and Scope
Identifying a Variable's Type
Exercise 5.02: Evaluating Types from Variables
Fixed Types
The null Value
The undefined Value
Boolean Values
Boolean Operators
Comparison Operators
Logical Operators
Exercise 5.03: Odds and Evens
Testing the Truth of Values
The NOT Operator
Boolean Operator Precedence
Boolean Operator Associativity
Exercise 5.04: Free Home Delivery Eligibility Validation
Why You Shouldn't Compare Boolean and Non-Boolean Expressions
Why You Shouldn't Chain Comparison Expressions
The Ternary Operator
Working with Numbers
Arithmetic Limitations
The Number Object
Number Functions
Number Methods
Number Properties
Exercise 5.05: Currency Formatter
Working with Strings
Special Characters
Concatenation
Template Literals
Exercise 5.06: Email Templates
The String Object
The length Property
String Methods
Exercise 5.07: Sentence Reversal
The toString Method
Numbers with Strings
Working with Functions
Anonymous Functions
Callbacks
Exercise 5.08: Functional Parameters
Arrow Functions
Arrow Function Caveats
Generator Functions
The this Keyword
The arguments Keyword
Call and Apply
Exercise 5.09: Dynamic Currying
Activity 5.01: Simple Number Comparison
Working with Objects
Objects as Hashtables
Object Keys and Memory
Object and Pass-By Reference
Object Iteration
Object Accessors
Exercise 5.10: Converting Objects to toString
Working with Arrays
Arrays and Mutability
Array Iteration
Built-In Array Functions
Working with Dates
Parsing Date Strings
Formatting Dates into Strings
Date Math
Activity 5.02: Creating a To-Do Model
Summary
6. Understanding Core Concepts
Introduction
Event Types
Timer Events
Exercise 6.01: Custom Timer
Event Timers
The setInterval Function
The setTimeout Function
Timer Parameters
Exercise 6.02: Real-Time Clock
The JavaScript Events Model
Event Bubbling
Traversing the Node Tree
Direct Node Acquisition
Assigning and Removing an Event Handler
Exercise 6.03: Tabbed Content
Bubbling versus Capturing
The JavaScript Event Life Cycle
Halting Event Propagation
Halting Event Actions
Exercise 6.04: Conditional Event Prevention
Event Triggers
Custom Events
Native Event Triggers
Event Hander Attributes
Events and Memory
Working with Forms
HTTP
The Form Tag
Submitting a Form with JavaScript
Form Submission Events
Preventing Form Submission
Resetting a Form
Form Reset Event
Exercise 6.05: Simple Form Handling
Form Controls
Input Controls
The Button Control
The Checkbox Control
The Radio Control
The Text Control
The Password Control
email, tel, and url Controls
The Hidden Control
The Number Control
The Image Control
The File Control
The Textarea Control
The Select Control
Activity 6.01: Making Changes to the Model
Summary
7. Popping the Hood
Introduction
JavaScript Execution and the Event Loop
The JavaScript Runtime
JavaScript Engine
Environment APIs
Message Queue
Event Loop
Call Stack
Memory Heap
Event Loop in Action
Exercise 7.01: Working with the Event Loop
Stack Overflow
Exercise 7.02: Stack Overflow
Memory Management
The Garbage Collector
Memory Leaks
Event Listeners
Detached DOM Nodes
Global Variables
Identifying Memory Leaks
Exercise 7.03: Identifying Memory Leaks
Exercise 7.04: Fixing the Memory Leak
Activity 7.01: Finding out the Number of Stack Frames
Summary
8. Browser APIs
Introduction
Canvas
Exercise 8.01: Drawing Shapes Using Canvas Elements
Manipulate Shapes Using Path
Activity 8.01: Creating a Simple Fractal
Web Audio API
Exercise 8.02: Creating an Oscillator Waveform
Activity 8.02: Playing Sound and Controlling Frequency Using Two Oscillators
Audio Visualization
Web Storage API
Exercise 8.03: Storing and Populating Name Using the localStorage API
IndexedDB
Exercise 8.04: Creating an Object Store and Adding Data
Querying IndexedDB
Exercise 8.05: Querying the Database
IndexedDB Cursor
Exercise 8.06: Fetching, Storing, and Querying Data
Performance API
Exercise 8.07: Assessing Performance
Web Socket API
Exercise 8.08: Creating Chat Rooms Using WebSockets
Activity 8.03: Audio Visualization
Summary
9. Working with Node.js
Introduction
The Node.js Environment
Sync versus Async
Background of Request Processing
What Are Callbacks?
The Node.js Shell
Exercise 9.01: Your First Program
How to Import/Require a Module in a Node.js Application
Node Package Manager (npm)
Flags
Commands
package.json
Publishing a Package
Node Modules
Node.js Modules
Exercise 9.02: Updating URL Information Using the URL Module
Filesystem
Operating System
Exercise 9.03: Fetching Details about the Operating System
Path Module
Exercise 9.04: How to Extract and Join Directories
HTTP
Exercise 9.05: Using a Node.js Server
Third-Party Modules
Express.js
The bodyParser Module
Morgan Logger
Working with Databases
Setting up Databases
Connecting with Databases
MySQL
Exercise 9.06: Install, Connect, and Process Responses with a MySQL Server
MongoDB
Exercise 9.07: Installing and Configuring a Connection in MongoDB
Making Real-Time Web Apps
WebSocket
Socket.IO
Exercise 9.08: Building a Chat Application
Activity 9.01: Create a Web Application to Upload, Store, and Save Image Details
Summary
10. Accessing External Resources
Introduction
JSON
REST
What Is HTTP?
TheSportsDB
Exercise 10.01: Using a REST API to Make Calls
HTTP Headers
AJAX
jQuery
Exercise 10.02: Using AJAX and the jQuery ajax() Method to Invoke a Service
Exercise 10.03: More AJAX and Some CSS Styling
CSS
Other Libraries and XMLHttpRequest
Axios and the Fetch API
For Comparison: XMLHttpRequest and jQuery
Using jQuery and XMLHttpRequest for POST Requests
Cross-Domain Requests
CORS Header
Activity 10.01: Implement REST Service Calls Using Various Techniques
Summary
11. Creating Clean and Maintainable Code
Introduction
What Is a Regex?
Regexes in Detail
Literal Characters
Special Characters, Anchors, and Escaping
Word Boundary
Shorthand Character Classes and Word Characters
Inverse Classes
Dot Character
Sets
Ranges
Excluding Sets and Ranges
Quantifiers
Shorthand Quantifiers
Alternation
Many More Regex Concepts
Pattern Specification and Flags
Finding Matches with String.match()
Exercise 11.01: The Effect of the g Flag
Other String Methods for Regexes
Exercise 11.02: Modifying Regex to Match a Pattern
Adding More Strings to the Regex
Activity 11.01: Expanding Phone Number Matching Patterns to Accept Multiple Formats
Activity 11.02: Expanding Phone Number Matching Patterns to Accept a Particular Format
Useful Regexes
Best Practices for Clean Coding
Good Naming Practices
JavaScript Linters
Exercise 11.03: JSLint
Activity 11.03: Refactoring to Clean Code
Summary
12. Using NextGeneration JavaScript
Introduction
Browser Differences
polyfills
Transpilers
Development Methodology Libraries
Package Managers
The Node Package Manager
Installing Modules
The Yarn Package Manager
The Babel Transpiler
@babel/core
@babel/cli
@babel/preset-env
@babel/polyfill
.babelrc Configuration File
Exercise 12.01: A Basic Babel Project
Babel Applications with Parcel
What is Parcel?
Using Parcel
Modular Applications in Parcel
Exercise 12.02: A Basic Parcel Project
Babel Applications with Webpack
Webpack Architecture
Webpack Loaders and Plugins
Webpack Configuration
Exercise 12.03: A Basic Webpack Project
Other Popular Bundlers
Other Language Transpiling
The TypeScript Language
Exercise 12.04: A Basic TypeScript Project
Elm and ClojureScript
Haxe
Code Support Libraries
jQuery
Underscore, Lodash, and Ramda
Client Frameworks Overview
Models, Views, and Controllers
Virtual DOMs
Reactive Programming
Popular Frameworks
AngularJS
ReactJS
Vue.js
Server-Side Libraries
Express
Request
Socket.IO
Activity 12.01: Creating a Project to Recognize and Compile TypeScript Files
Summary
13. JavaScript Programming Paradigms
Introduction
JavaScript Paradigms
The Procedural Paradigm
Exercise 13.01: Implementing Procedural Programming
The Object-Oriented Paradigm
Exercise 13.02: Implementing OOP
Encapsulation
Inheritance
Exercise 13.03: Inheritance Implementation Using the extends Keyword
Basic JavaScript Concepts
Prototypes and Prototypical Inheritance
What Is Prototypical Inheritance?
Exercise 13.04: Prototypical Inheritance Implementation
Anonymous Functions
The Differences between Named Functions and Anonymous Functions
Data Scope
Global Scope
Local Scope
Function-Level Scope
Block-Level Scope
Hoisting
The Difference between var and let
Closures
JavaScript Memory Management
Memory Life Cycle
Static versus Dynamic Allocation
Releasing Memory
Reference-Counting Garbage Collection
Activity 13.01: Creating a Calculator App
Summary
14. Understanding Functional Programming
Introduction
Pure Functions
Side Effects
Immutability
Exercise 14.01: Immutable Values and Objects – Strings
Exercise 14.02: Immutable Values and Objects – Numbers
Exercise 14.03: Mutability – Arrays
Exercise 14.04: Mutability – Objects
Cloning Objects and Arrays
Sample Data for Examples and Exercises
Higher-Order Functions
The Array.prototype.filter Method
A Refresher
Eliminating for Loops
The Array.prototype.map Method
Exercise 14.05: Another Way of Using Array.prototype.map
The Array.prototype.reduce method
Exercise 14.06: Grouping with Array.prototype.reduce
Implementation of compose() and pipe()
Composition with compose() and pipe()
Currying Functions
Exercise 14.07: More Uses for Composition and Curried Functions
Function Recursion
Exercise 14.08: Creating a Deck of Cards Using reduce()
Exercise 14.09: Using the pipe Method to Create a Card Shuffling Function
Blackjack
Mapping Card Values to Cards
Activity 14.01: Blackjack Card Functions
Managing Blackjack Game State
Blackjack Game Logic Flow
Blackjack Game Display Functions
Blackjack Code Listing
Summary
15. Asynchronous Tasks
Introduction
Callbacks
setTimeout()
Exercise 15.01: Asynchronous Execution with setTimeout()
Callback Hell and the Pyramid of Doom
Promises and the Fetch API
Using the Fetch API to Get Player Honors
Exercise 15.02: Refactoring the Honors List to Use the Fetch API
An Improvement for Better Performance
Tidying Up Fetch Code
Some Fetch API Usage Details
Some Details Concerning Promises
Exercise 15.03: Creating a Utility Function to Delay Execution
Further Refinements to addDelay()
Async/Await
Asynchronous Generators and Iterators
Activity 15.01: Refactoring Promise Code to await/async Syntax
Activity 15.02: Further Simplifying Promise Code to Remove Function Parameters
Summary
Appendix
Preface
About
This section briefly introduces the coverage of this book, the technical skills you'll need to get started, and the hardware and software requirements required to complete all of the included activities and exercises.
About the Book
If you’re looking for a programming language to develop flexible and efficient apps, JavaScript is a great choice. However, whilst offering real benefits, the complexity of the entire JavaScript ecosystem can be overwhelming. This Workshop is a smarter way to learn JavaScript. It is specifically designed to cut through the noise and help build your JavaScript skills from scratch, while sparking your interest with engaging activities and clear explanations.
Starting with explanations of JavaScript’s fundamental programming concepts, this book will introduce the key tools, libraries and frameworks that programmers use in everyday development. You will then move on and see how to handle data, control the flow of information in an application, and create custom events. You’ll explore the differences between client-side and server-side JavaScript, and expand your knowledge further by studying the different JavaScript development paradigms, including object-oriented and functional programming.
By the end of this JavaScript book, you’ll have the confidence and skills to tackle real-world JavaScript development problems that reflect the emerging requirements of the modern web.
Audience
Our goal at Packt is to help you be successful, in whatever it is you choose to do. The JavaScript Workshop is an ideal tutorial for the JavaScript beginner who is just getting started. A basic understanding of HTML and CSS will help you to get the best out of this Workshop. Pick up a Workshop today and let Packt help you develop skills that stick with you for life.
About the Chapters
Chapter 1, Getting to Know JavaScript, introduces a foundational background of JavaScript in order to move forward and achieve competency. This chapter introduces you to JavaScript, through its history through to modern implementations, with additional information on various uses of the language to provide a proper context for what comes next.
Chapter 2, Working with JavaScript, covers some hands-on work with the language. We'll provide an overview of some popular tools for writing JavaScript and the various available runtimes for executing your code. We'll pay particular attention to the primary target for most JavaScript applications and a great tool in itself, the modern web browser.
Chapter 3, Programming Fundamentals, serves as an introduction to the fundamental concepts and structures involved when working in JavaScript and programming in general. We'll cover all the basics, from object types to conditionals and looping structures, how to go about writing and invoking functions, and even commenting and debugging your code.
Chapter 4, JavaScript Libraries and Frameworks, focuses on plain-old vanilla JavaScript, along with various frameworks and libraries that exist today. The primary focus of this chapter is to provide an understanding that, while extensions to the core language can be great, sometimes, core JavaScript is really all you need.
Chapter 5, Beyond the Fundamentals, explains that data is represented differently in different languages and runtimes. JavaScript is based on the ECMAScript specification and has definitive rules for how data is represented. This chapter discusses data in JavaScript, how to convert between types, and how types are passed around within a script.
Chapter 6, Understanding Core Concepts, utilizes an HTML page using JavaScript in this book, as well as being the first chapter to explain the abstract nature of the event messaging system. Understanding these concepts is very valuable when building a useful web application in JavaScript. Throughout this chapter, you will explore the various nuances of event message bubbling and capturing, along with how it can best be used to control the flow of information within an application. You will also see how to halt these events in their tracks and to create your own custom events. This chapter will give you the foundations to tackle applications of any size or complexity.
Chapter 7, Popping the Hood, clarifies how the thing many people think of as 'just JavaScript' can actually be broken down into separate components: the JavaScript engine, consisting of the call stack, memory heap, and the garbage collector; and the JavaScript runtime environment, such as a browser, or Node.js, which contains the JavaScript engine, and gives the engine access to additional functions and interfaces, such as setTimeout() or a filesystem interface. We will also look at how JavaScript manages memory allocation and deallocation, and how even though it is managed automatically, it's important for developers to bear in mind the processes involved, in order to write code that enables the garbage collector to work correctly.
Chapter 8, Browser APIs, introduces a few of the most useful and interesting browser APIs that open up wide-ranging functionality that we can make use of in our JavaScript application. We'll see that while these APIs are most commonly accessed through JavaScript, they are not a part of the ECMAScript specification to which the JavaScript engines are programmed and are not part of JavaScript core functionality.
Chapter 9, Working with Node.js, guides us in unifying the entire web application development around a single programming language, as opposed to learning different languages and building different projects for server-side and client-side. In this chapter, you will go through how the node works in the background and how it processes requests asynchronously. Furthermore, you will study different types of modules and how to use them.
Chapter 10, Accessing External Resources, explores the fact that web pages are static and of limited use without fresh data. This chapter covers various approaches to using Ajax to obtain data, primarily from RESTful services.
Chapter 11, Creating Clean and Maintainable Code, introduces you to best practices for clean and maintainable coding. You will learn that refactored code that uses clean coding techniques results in code that is much longer than before. But you will see that the code is much cleaner and easier to understand and test compared to the original. The value of this programming style really shows itself more in complex real-world applications, and it is good practice to work this way. Developers and tech leads need to decide what standards and clean coding practices make sense for their particular project.
Chapter 12, Using Next-Generation JavaScript, looks at the various tools available in the market for advanced development in JavaScript. We will learn how to use the latest JavaScript syntax in older browsers and identify the different options for the development of JavaScript applications in other languages. We will also explore various package managers, such as npm and Yarn, that are compatible with JavaScript, along with several different frameworks, such as AngularJS, React, and Vue.js. Finally, we will look at some server-side libraries, such as Express, Request, and Socket.IO.
Chapter 13, JavaScript Programming Paradigms, teaches you that JavaScript is a multi-paradigm programming language. We can use it to write code in procedural, object-oriented, and functional design patterns. During the learning phase of any programming language, people usually code in a procedural way where, instead of planning, they put most of their focus on the execution and understanding the concepts of that particular programming language. But when it comes to practical execution in real life, the object-oriented programming paradigm, or OOP, is a scalable option.
Chapter 14, Understanding Functional Programming, discusses how functional programming is quite different from other programming paradigms such as imperative and object-oriented approaches, and it takes some getting used to. But, properly applied, it is a very powerful way of structuring programs to be more declarative, correct, and testable with fewer errors. Even if you don't use pure functional programming in your projects, there are many useful techniques that can be used on their own. This is especially true for the map, reduce, and filter array methods, which can have many applications. The topics covered in this chapter will help you bolster the skills you need to pursue a programming project in the functional style.
Chapter 15, Asynchronous Tasks, discusses how asynchronous tasks allow the execution of the main thread of a program to proceed even while waiting for data, an event, or the result of another process, and achieve snappier UIs and some forms of multitasking. Recent enhancements to the language, such as promises and the async/await keywords, simplify such development and make it easier to write clean and maintainable asynchronous code.
Note
There are also two bonus chapters available with the free interactive edition of this book. You can find these online at: https://courses.packtpub.com/
Conventions
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
The if, else if, and else statements give you four structures for selecting or skipping blocks of code.
Words that you see on the screen, for example, in menus or dialog boxes, also appear in the text like this: "Press the F12 key to launch the debugger or select More Tools | Developer Tools from the menu."
A block of code is set as follows:
function logAndReturn( value ) {
console.log(logAndReturn:
+value );
return value;
}
if ( logAndReturn (true) || logAndReturn (false)) {
console.log(|| operator returned truthy.
);
}
New terms and important words are shown like this: Timer events provide forced asynchronous functionality within your applications. They allow you to invoke a function after a period of time; either once or repeatedly.
Long code snippets are truncated and the corresponding names of the code files on GitHub are placed at the top of the truncated code. The permalinks to the entire code are placed below the code snippet. It should appear as follows:
activity.html
1
2 en>
3
4 utf-8>
5
6 stylesheet>
7
8 body {
9 background-color:rgb(37, 37, 37);
10 color:aliceblue;
11 padding:2rem;
12 margin:0;
13 font-family:'Architects Daughter', cursive;
14 font-size: 12px;
15 }
The full code is available at: https://packt.live/2Xc9Y4o
Before You Begin
Each great journey begins with a humble step. Our upcoming adventure with JavaScript programming is no exception. Before we can do awesome things using JavaScript, we need to be prepared with a productive environment. In this short note, we will see how to do that. If you have any issues or questions about installation please email us at [email protected].
Installing Visual Studio Code
Here are the steps to install Visual Studio Code (VSCode):
Download the latest VSCode from https://packt.live/2BIlniA:
Figure 0.1: Downloading VSCodeFigure 0.1: Downloading VSCode
Open the downloaded file, follow the installation steps, and complete the installation process.
Installing the Open in Default Browser
Extension
Open your VSCode, click on the Extensions icon, and type in Open In Default Browser in the search bar, as shown in the following screenshot:
Figure 0.2: Open in Default Browser extension searchFigure 0.2: Open in Default Browser extension search
Click on Install to complete the installation process, as shown in the following screenshot:
Figure 0.3: Installing the extensionFigure 0.3: Installing the extension
Downloading Node.js
Node.js is open source and you can download it from its official website https://nodejs.org/en/download/ for all platforms. It supports all three major platforms: Windows, Linux, and macOS.
Windows
Visit their official website and download the latest stable .MSI installer. The process is very simple. Just execute the .MSI file and follow the instructions to install it on the system. There will be some prompts about accepting license agreements. You have to accept those and then click on Finish. That's it.
Mac
You have to download the .pkg file from the official website and execute it. Then, follow the instructions. You may have to accept the license agreement. After that, follow the prompts to finish the installation process.
Linux
In order to install Node.js on Linux, execute the following commands as root in the same order they are mentioned:
$ cd /tmp
$ wget http://nodejs.org/dist/v8.11.2/node-v8.11.2-linux-x64.tar.gz
$ tar xvfz node-v8.11.2-linux-x64.tar.gz
$ mkdir -p /usr/local/nodejs
$ mv node-v8.11.2-linux-x64./* /usr/local/nodejs
Here, you first change the current active directory to the temporary directory (tmp) of the system. Second, you download the tar package of the node from their official distribution directory. Third, you extract the tar package to the tmp directory. This directory contains all the compiled and executable files. Fourth, you create a directory in the system for Node.js. In the last command, you are moving all the complied and executable files of the package to that directory.
Verifying the Installation
After the installation process, you can verify whether it is installed properly in the system by executing the following command in the directory of Node.js:
$ node -v && npm -v
It will output the current installed version of Node.js and npm:
Figure 0.4: Installed version of Node.js and npmFigure 0.4: Installed version of Node.js and npm
Here, it is showing that the 8.11.2 version of Node.js is installed on the system, as is the 5.6.0 version of npm.
Installing the Code Bundle
Download the code and relevant files from GitHub at https://github.com/PacktWorkshops/The-JavaScript-Workshop and place them in a new folder called C:\Code on your local system. Refer to these code files for the complete code bundle.
1. Getting to Know JavaScript
Overview
By the end of this chapter, you will be able to locate JavaScript elements along with other code elements in a web browser; identify different versions of JavaScript supported by various web browsers; construct simple JavaScript commands; discuss the range of modern approaches to JavaScript; describe JavaScript's capabilities and create an alert box popup in a web browser.
This chapter describes the foundational background of JavaScript so that we can move forward and achieve competency with this widely used programming language.
Introduction
JavaScript is a language with interesting beginnings. In its early days, it was not taken very seriously—the only widely accepted, functionally correct use for the language was to perform client-side validation of form data. Many developers only copied and pasted simple code snippets that performed a single action on a website they were building. All these code snippets did were very simple actions such as reveal an alert to the user or provide a date countdown—simple logic.
Today, JavaScript is a whole different beast—and one with the power to literally build out entire HTML documents, revise CSS styling on the fly, and securely transport and interpret data from various remote sources. Whereas in times past, HTML was the primary technology on the web, in the present era, JavaScript is king.
Any introduction to JavaScript requires a foundational background of the history and origins of the language in order to move forward and achieve competency. This chapter introduces us to JavaScript, from its history to modern implementations. It also provides us with additional information on various uses of the language so that we can provide a proper context for what comes next.
What Is JavaScript and How Is It Used?
JavaScript is a weakly-typed, multi-paradigm, event-driven, object-oriented programming language. It includes the ability to work with strings, dates, arrays, objects, and more. It is generally used on the client-side within web browser environments but can also be used in other environments such as servers and desktop applications. The runtime environment is very important for JavaScript—especially since it, by itself, does not include any networking, file, graphics, or storage capabilities on its own.
JavaScript versus Other Languages
If you are approaching JavaScript with experience in other languages such as Java or Python, things might seem a bit odd. While many languages (such as Java) must be compiled to run, JavaScript is run exactly as-is and does not require this additional step.
Though the language is used within many environments and for many purposes, JavaScript is fundamentally one of the three languages that are native to the web. The other two languages are the HTML semantic markup language and the CSS styling and layout language. All three are very different from one another in purpose and function, but they are all meant to work together in a single environment. Let's go over them:
Hypertext Markup Language (HTML): This is the most fundamental of these three languages as it defines the elements that compose an HTML page and defines the flow of basic information that's presented to the user.
Cascading Style Sheets (CSS): This is used to define a set of stylistic layout rules, which adds visual flourish and advanced layout to defined HTML elements.
JavaScript(JS): This works to enable interactivity in web pages and is what will be the focus of this book.
With all three of these languages, there is a basic understanding of the separation of concerns, that is, HTML provides the content and structure, CSS provides the styling and layout, and JavaScript provides the interactivity. While this understanding still holds sway, many frameworks do not exactly abide by this separation and mix these various languages together in some shape or form. Some developers are okay with this, while others are not. It's definitely an issue to be aware of when getting into this field, but it is ultimately up to you which stance you take, based on your particular needs. In my opinion, there is no hard and fast answer to a question like this.
Exercise 1.01: Languages Discovery
Let's go ahead and examine a website to see whether we can spot how HTML, JavaScript, and CSS are all represented. You can choose any website you like for this exercise.
Note
All the examples and screenshots in this book will use Google Chrome as the web browser of choice. You can use the browser you prefer, though some of the steps that are shown may differ between various browsers.
Let's get started:
Within your web browser, enter a URL in the address bar and press Enter/Return to load the chosen resource. For this example, let's use https://packt.live/2oXOE67—the Angular website. Of course, you can choose any website that you'd like to explore.
Now, right-click anywhere within the browser viewport to summon a contextual menu. Select the option that allows you to view the source code of the page. In Chrome, this is labeled View Page Source.
The source code for the page will then appear in a new tab. You can examine how the page is structured and pick out the various HTML, CSS, and JavaScript elements from the bare source code:
Figure 1.1: Much can be learned from examining the bare source codeFigure 1.1: Much can be learned from examining the bare source code
With the source code exposed, scroll down and identify the various HTML elements within the page structure. You'll likely find a tag and a tag (which are mandatory), along with various and to
tags within the page.
Here is an example of some basic HTML content (not actually from the Angular website):
Welcome!
Angular is a framework used to build web applications.
Create high-performing and accessible applications using Angular.
Now, try and locate either embedded CSS rules within a
color: red;
margin-top: 40px;
position: relative;
text-align center;
And here is a linked CSS file:
stylesheethref=styles.css
>
Finally, we'll locate some JavaScript. Much like CSS, JavaScript can be found embedded within a page using the
function writeMessage() {
document.getElementById(message
).innerHTML = Hello From JavaScript!
;
}
Here is a linked JavaScript file:
Choosing to view the source code of public web pages like this was once a common way to learn about web technologies.
Note
In various websites and examples, you may see a type attribute included with the
So far, we have introduced the JavaScript programming language and examined its primary runtime environment (the web browser). We also had a brief look at JavaScript's relationship to HTML and CSS as one of the three native web technologies.
In the next section, we'll take a look at the history of JavaScript and how it has evolved over the years.
A Brief History of the JavaScript Language
We've seen how JavaScript is often integrated within a web environment, but how did this language come about? We need to go back to the early 1990s and understand what the web looked like in those days before we begin talking about JavaScript itself.
The story really begins with Netscape and the web browser they created named Netscape Navigator. This new browser was based on the successful Mosaic web browser with the intent to commercialize it. During that time, and depending on who you speak to, Netscape Navigator was the web browser of choice to develop for. Around the middle of the decade, Microsoft released its Internet Explorer browser, which ignited the first browser wars.
Netscape Mocha and LiveScript
Around this same time, Netscape hired Brendan Eich to develop a programming language for Netscape's web browser. Eich took inspiration from Scheme (Lisp), Self, and most importantly, Java. The work on this language, then called Mocha, was initially (and infamously) completed in the time span of only 10 days. With the initial version completed, Netscape changed their name and began calling it LiveScript.
It turned out that LiveScript, as a language name, was just as temporary as Mocha until Netscape partnered with a certain other large company to advance the idea of a two-pronged approach to web development.
Sun Microsystems and Java
The popular Java language came into play with a partnership between Netscape and Sun Microsystems. Sun was looking at the web as the next step for Java, and Netscape was looking for allies in the coming war against Microsoft, so an allegiance was formed. The language being developed by Eich was from then on named JavaScript as it was meant to work alongside Java in the web browser as a more approachable way to add interactivity to that environment.
This would mean that the Java language would be what serious developers used to write interactive content for the web, while JavaScript would provide similar interactive capabilities but was geared more toward hobbyists and those who wanted to tinker.
Note
What happened, of course, was quite different. JavaScript was integrated into the browser well before Java was, and, once Java came on board, it was only through the use of applets. With Java applets falling out of popularity quite some time ago, we are left with JavaScript alone today and not the two languages that were initially envisioned, though the JavaScript name has stuck.
Ecma International and ECMAScript
Ecma adopted and standardized the specification and renamed the language itself to ECMAScript, with JavaScript becoming the commercial implementation of that specification. Ecma International remains the organization that develops and publishes the ECMAScript specification and all the new versions of it, which eventually influence the JavaScript language.
In this section, we read about how JavaScript came to be and performed a quick exercise that showed how it can be examined live within the web browser itself. At this point, you should have a pretty good idea of exactly what JavaScript is, where it came from, and how it operates.
In the next section, we'll look at some more history behind this language by examining the version history of JavaScript beyond ECMA standardization.
Versions of ECMAScript (and JavaScript)
With JavaScript now granted Ecma International standardization and the ECMAScript specification, it also needed to follow standard versioning practices. For the first few iterations of the language, this didn't mean much to developers. However, as you will see, as needs grew and the language evolved, major changes would be coming to ECMAScript. They would, in some cases, flow on to JavaScript, and in other cases die altogether.
ECMAScript 1 (1997)
The first version to undergo standardization codified its features more or less from LiveScript. This version is sometimes referred to as ECMAScript First Edition.
It generally corresponds to JavaScript version 1.3.
ECMAScript 2 (1998)
This release saw few changes aside from edits to better conform with established standards. It should probably have been labeled version 1.1.
It also generally corresponds to JavaScript version 1.3.
ECMAScript 3 (1999)
This version of ECMAScript added some fundamental, yet expected (necessary), language enhancements. One of the most important of these is the use of regular expressions (regex), which allows complex pattern matching within text data. The try…catch conditional structure was also introduced, providing an alternative to the more basic if…else statement, allowing more sophisticated error handling. The in operator was also introduced. This generally corresponds to JavaScript version 1.5.
ECMAScript 4 (unreleased)
This release included real classes, modules, generators, static typing, and many language features that were added to the specification many years later.
Note
Eventually, due to committee and corporate infighting, ECMAScript 4 was completely abandoned. Instead, it was replaced with incremental improvements to ECMAScript 3, also known as ECMAScript 3.1.
At this time, Adobe decided to base a complete revision of the ActionScript language (ActionScript 3.0 on this new ECMAScript version. It was an attempt to closely align the language behind the Flash Player and the browsers that commonly hosted it. Here is an example of a basic ActionScript 3.0 class—note that it's quite different from previous versions of ECMAScript:
package com.josephlabrecque {
import flash.display.MovieClip;
public class Main extends MovieClip {
public function Main() {
// constructor code
}
}
}
ECMAScript 5 (2009)
This version is, in actuality, ECMAScript 3.1, with version 4 completely abandoned. This was more of a politically motived release than anything of substance, though certain bug fixes from ECMAScript 4 were included, along with strict mode, JSON support, and a number of additional methods for working with arrays.
This generally corresponds to JavaScript version 1.8.5 and is the version of JavaScript that conforms to most browsers today.
ECMAScript 6 (2015)
Features including arrow functions, maps, typed-arrays, promises, and many more were introduced with this version of ECMAScript, and many of them form the basis for modern development with JavaScript today. This specification also allows for the writing of classes and modules—finally. The following table explains the browser support for ES6:
Figure 1.2: Browser support table for ECMAScript 2015 via w3schools.comFigure 1.2: Browser support table for ECMAScript 2015 via w3schools.com
This version of JavaScript is generally SVG supported by modern web browsers and is a major functional release.
ECMAScript 7 (2016), ECMAScript 8 (2017), and ECMAScript 9 (2018)
All versions post2015 have been incremental, with yearly modifications to what was established in ECMAScript 6. This has happened for a number of reasons:
It establishes that this is a stable, mature language without the need for major disruption.
It allows developers and browser vendors to easily keep up with the changes and enhancements that are adopted.
It provides a stable release cycle for new versions of the specification:
Figure 1.3: Browser support table for ECMAScript 2016 via w3schools.comFigure 1.3: Browser support table for ECMAScript 2016 via w3schools.com
When writing in ECMAScript 2015 (or ES6
) and later, you will likely need to transpile your JavaScript down to a previous version so that it can be understood by the JavaScript engines within the current web browsers. While this is an additional step, the tooling to process tasks such as this has become more approachable in recent years.
Exercise 1.02: Can I Use This Feature?
There is no easy way to tell which versions of JavaScript are supported by which browsers—a more reliable approach is to test whether features you wish to use are supported by the engine currently running the code. Let's take a look at the Can I Use table:
Figure 1.4: "Can I Use" table for ECMAScript 2015 support across browsersFigure 1.4: Can I Use
table for ECMAScript 2015 support across browsers
To help us do this, there are a number of resources and services on the web that keep track of JavaScript features and the level of support within each browser. Probably, the most popular of these is the Can I Use table, which includes an abundance of support information around CSS, JavaScript, SVG, HTML5, and more.
Let's go ahead and check out the support for Promise.prototype.finally, which was first implemented in ECMAScript 2018:
Open a web browser and instruct it to load https://packt.live/2WSQhhY. Notice that you have immediate access to the latest and most searched features directly from the home page, without even searching:
Figure 1.5: The Can I Use websiteFigure 1.5: The Can I Use website
We are looking for something specific, though. Locate the search area toward the top, which reads Can I use ___________?, and type in finally, since we want to see which browsers support Promise.prototype.finally. The results for our search will be displayed automatically within a colored grid:
Figure 1.6: The grid of browser support for Promise.prototype.finallyFigure 1.6: The grid of browser support for Promise.prototype.finally
Note that certain blocks are red, while others are green. A red color indicates that the feature is unsupported, and green indicates that the feature is supported. You may also see a yellow color, indicating partial support.
If you want to see the specifics pertaining to a certain browser version, hover your cursor over the indicated version or version range and a small overlay will appear with additional information such as the date of version release and even usage statistics for that version:
Figure 1.7: Specific support information for Chrome 73Figure 1.7: Specific support information for Chrome 73
Go ahead and search for additional options within the interface—there is a lot to explore.
In this section, we reviewed the different versions of ECMAScript and looked at how the features of JavaScript, which originated from those particular specifications, are supported within web browsers today.
In the next section, we'll look at how to access the web browser developer tools in order to get a better view of what JavaScript is doing—and even write JavaScript live in the browser.
Accessing Web Browser Developer Tools
Our understanding of JavaScript's relationship with the web browser is becoming clearer with each topic that we discuss. In the previous exercise, we saw how to dig in and discover the different levels of JavaScript feature support across different web browsers. That leads us directly to have a look at the various browsers themselves, as well as the tools that are available within each for inspecting and even writing JavaScript code.
Browsers are built to abide by standards such as HTML and CSS. However, there are many differences in both the interpretation of these standards and in the tooling available with each major web browser. When writing JavaScript for the web browser, it is important to know how to access and use the browser developer tools—especially the JavaScript console tab.
Google Chrome
Chrome is the most popular web browser at the time of this writing—this fact holds true for both general users and developers. Chrome was initially released in September 2008 and is now available on multiple desktops and mobile operating systems.
Note
You can download Google Chrome from https://packt.live/2NQRQcn.
To access developer tools and the JavaScript console within Chrome, you can right-click anywhere in the viewport and choose Inspect from the menu that appears. Alternatively, press F12. Once the developer tools are open, click on the Console tab to inspect and write JavaScript code within Chrome itself:
Figure 1.8: Google Chrome Developer ToolsFigure 1.8: Google Chrome Developer Tools
Using the Chrome developer tools, you can filter the sort of things that show errors, warnings, or even just information such as that returned by console.log(). You can even write JavaScript within the browser using the Console tab view, as you'll see shortly. There is also a Sources tab, which allows for modifying and debugging of code.
Microsoft Edge
Having once reigned as the most used web browser in the world, Internet Explorer reached its final version with IE11. This doesn't mean that Microsoft is finished with web browsers though, as, with the release of Windows 10, the newly created Edge browser was made available to users as a replacement in July 2015.
Note
Microsoft Edge comes installed with Windows 10 (https://packt.live/2CnMv6P).
To access the developer tools and the JavaScript console within Edge, you can right-click anywhere in the viewport and choose Inspect Element from the menu that appears. Alternatively, press F12:
Figure 1.9: Microsoft Edge Developer ToolsFigure 1.9: Microsoft Edge Developer Tools
The developer tools in Microsoft Edge are pretty ugly, aren't they? Much like other browsers, Edge's developer tools include a Console and a JavaScript Debugger view. Similar to Chrome, you can also filter the types of output present in the Console itself as your code executes.
Note
As of this writing, Microsoft Edge is being rewritten based on a Chromium base. This will mean that Chrome, Opera, Safari, and Edge will eventually make use of the exact same browser technologies under the hood.
Apple Safari
On Apple macOS and iOS operating systems, Safari is the default web browser and is tightly integrated into the user experience on those machines. Similar to Windows and Internet Explorer/Edge, many users will never deviate from the browser that is preinstalled on their machine.
Safari was once even available on Windows, but development ceased with the final Windows version in 2012.
Note
Apple Safari comes installed with Apple macOS (https://packt.live/32moJTq).
To access the developer tools and the JavaScript console within Safari, you must first tweak some of the preferences within the browser itself. Let's get started:
First, access the preferences dialog by choosing Safari | Preferences through the Application menu.
Within the Preferences dialog, click on the tab called Advanced.
Once the contents of the Advanced tab has appeared, look to the bottom and enable the Show Develop menu in menu bar option:
Figure 1.10: Apple Safari Advanced PreferencesFigure 1.10: Apple Safari Advanced Preferences
With that option enabled, close the Preferences dialog.
Now, choose the newly enabled Develop option from the Application menu and select Show JavaScript Console to display the developer tools. You can also right-click and choose Inspect Element as well.
The good news is that once the Develop menu is enabled, it will remain so between sessions. You'll only need to open the developer tools to access these features:
Figure 1.11: Apple Safari Developer ToolsFigure 1.11: Apple Safari Developer Tools
Today, Safari does seem to lag behind most other browsers in adopting certain features, but you will find Apple's version of the Console and Debugger views in the developer tools all the same.
An Introduction to Variables
In almost any language, JavaScript included, the first step to programming is to understand the common variable. A variable can be thought of as an identifier for a certain piece of data. To declare a variable in JavaScript, we use the reserved word var:
var name;
In the preceding example, we declare a variable with the name identifier. Our variable does not have any data associated with it yet. For that, we must use an assignment operator:
name = Joseph
;
Since the variable name