Mastering JavaScript
By Antani Ved
3.5/5
()
About this ebook
About This Book
- Write powerful code with the high-level functions that JavaScript offers
- Test and debug issues with JavaScript code using various modern mechanisms
- Offers an expert's eye on the latest ES6 features and how these advanced tasks fit together in JavaScript as a whole
Who This Book Is For
This book is ideal for web developers who are looking to master modern JavaScript concepts and design principles. You should already have an intermediate level of JavaScript knowledge before starting this book.
What You Will Learn
- Get a run through of the basic JavaScript language constructs
- Get familiar with the Functions and Closures of JavaScript
- Explore Regular Expressions in JavaScript
- Code using the powerful object-oriented feature in JavaScript
- Test and debug your code using JavaScript strategies
- Master DOM manipulation, cross-browser strategies, and ES6
- Understand the basic concurrency constructs in Javascript and best performance strategies
- Learn to build scalable server application in JavaScript using Node.js
In Detail
JavaScript is a high-level, dynamic, untyped, lightweight, and interpreted programming language. Along with HTML and CSS, it is one of the three essential technologies of World Wide Web content production, and is an open source and cross-platform technology. The majority of websites employ JavaScript, and it is well supported by all modern web browsers without plugins. However, the JavaScript landscape has changed dramatically in recent years, and you need to adapt to the new world of JavaScript that people now expect. Mastering modern JavaScript techniques and the toolchain are essential to develop web-scale applications.
Mastering JavaScript will be your companion as you master JavaScript and build innovative web applications. To begin with, you will get familiarized with the language constructs and how to make code easy to organize. You will gain a concrete understanding of variable scoping, loops, and best practices on using types and data structures, as well as the coding style and recommended code organization patterns in JavaScript. The book will also teach you how to use arrays and objects as data structures. You will graduate from intermediate-level skills to advanced techniques as you come to understand crucial language concepts and design principles. You will learn about modern libraries and tools so you can write better code.
By the end of the book, you will understand how reactive JavaScript is going to be the new paradigm.
Style and approach
This is a comprehensive guide with a clear focus on practical use cases and patterns. Each chapter consists of best practices, useful advice, and a bunch of easy-to-follow examples that will build up your skills as you advance through the book.
Read more from Antani Ved
Object-Oriented JavaScript - Third Edition Rating: 4 out of 5 stars4/5JavaScript : Object-Oriented Programming Rating: 0 out of 5 stars0 ratingsManaging IaaS and DBaaS Clouds with Oracle Enterprise Manager Cloud Control 12c Rating: 0 out of 5 stars0 ratings
Related to Mastering JavaScript
Related ebooks
JavaScript Unlocked Rating: 5 out of 5 stars5/5JavaScript and JSON Essentials Rating: 5 out of 5 stars5/5Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications, and libraries Rating: 3 out of 5 stars3/5Mastering JavaScript Design Patterns Rating: 4 out of 5 stars4/5JavaScript Projects for Kids Rating: 0 out of 5 stars0 ratingsJavaScript Security Rating: 4 out of 5 stars4/5Mastering JavaScript Object-Oriented Programming Rating: 0 out of 5 stars0 ratingsReactJS by Example - Building Modern Web Applications with React Rating: 4 out of 5 stars4/5Learning jQuery 3 - Fifth Edition Rating: 0 out of 5 stars0 ratingsMastering JavaScript Promises Rating: 1 out of 5 stars1/5Mastering JavaScript Design Patterns - Second Edition Rating: 5 out of 5 stars5/5React.js Essentials Rating: 4 out of 5 stars4/5JavaScript: Beginner's Guide to Programming Code with JavaScript: JavaScript Computer Programming Rating: 0 out of 5 stars0 ratingsClean Code in JavaScript: Develop reliable, maintainable, and robust JavaScript Rating: 5 out of 5 stars5/5Mastering Bootstrap 4 Rating: 5 out of 5 stars5/5JavaScript: Beginner's Guide to Programming Code with JavaScript Rating: 5 out of 5 stars5/5The Joy of JavaScript Rating: 0 out of 5 stars0 ratingsJavaScript Regular Expressions Rating: 3 out of 5 stars3/5React Design Patterns and Best Practices Rating: 0 out of 5 stars0 ratingsTypeScript Essentials Rating: 4 out of 5 stars4/5Getting Started with React Rating: 0 out of 5 stars0 ratingsNode.js By Example Rating: 2 out of 5 stars2/5Mastering Node.js Rating: 1 out of 5 stars1/5Learn Java 12 Programming: A step-by-step guide to learning essential concepts in Java SE 10, 11, and 12 Rating: 0 out of 5 stars0 ratingsGetting Started with React Native Rating: 4 out of 5 stars4/5Django Design Patterns and Best Practices Rating: 5 out of 5 stars5/5Express Web Application Development Rating: 3 out of 5 stars3/5Mastering Reactive JavaScript Rating: 0 out of 5 stars0 ratingsModular Programming with PHP 7 Rating: 0 out of 5 stars0 ratingsJavaScript for Gurus: Use JavaScript programming features, techniques and modules to solve everyday problems Rating: 0 out of 5 stars0 ratings
Programming For You
Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5HTML & CSS: Learn the Fundaments in 7 Days 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/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5101 Amazing Nintendo NES Facts: Includes facts about the Famicom Rating: 4 out of 5 stars4/5Java for Beginners: A Crash Course to Learn Java Programming in 1 Week Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Pokemon Go: Guide + 20 Tips and Tricks You Must Read Hints, Tricks, Tips, Secrets, Android, iOS Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5Learn SQL in 24 Hours Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5C# 7.0 All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsGrokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5ReactJS by Example - Building Modern Web Applications with React Rating: 4 out of 5 stars4/5
Reviews for Mastering JavaScript
3 ratings1 review
- Rating: 2 out of 5 stars2/5Its good good book about Java Script. I read it here and the codes, the way they are presented here with words breaking along the page, is very hard to read, i have to copy and paste them and then remove - in sublime text to actually be able to read them. If they can fix the way they have presented the code in the book, this book can be very useful.
In the end, i am better in java script then i was when i started reading this book. Worth a read for sure.1 person found this helpful
Book preview
Mastering JavaScript - Antani Ved
Table of Contents
Mastering JavaScript
Credits
About the Author
About the Reviewer
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. JavaScript Primer
A little bit of history
How to use this book
Hello World
An overview of JavaScript
Comments
Variables
Constants
Number
String
Undefined values
Booleans
The instanceof operator
Date objects
The + operator
The ++ and -- operators
Boolean operators
Equality
Strict equality using ===
Weak equality using ==
JavaScript types
Automatic semicolon insertion
JavaScript style guide
Whitespaces
Parentheses, line breaks, and braces
Quotes
End of lines and empty lines
Type checking
Type casting
Conditional evaluation
Naming
The eval() method is evil
The strict mode
Enabling the strict mode for an existing code can break it
Package with care
Variables must be declared in strict mode
The eval() function is cleaner in strict mode
Features that are blocked in strict mode
Running JSHint
Summary
2. Functions, Closures, and Modules
A function literal
A function declaration
Functions as data
Scoping
Global scope
Local scope
Function-level scope versus block-level scope
Inline function expressions
Block scopes
Function declarations versus function expressions
The arguments parameter
The this parameter
Invocation as a function
Invocation as a method
Invocation as a constructor
Invocation using apply() and call() methods
Anonymous functions
Anonymous functions while creating an object
Anonymous functions while creating a list
Anonymous functions as a parameter to another function
Anonymous functions in conditional logic
Closures
Timers and callbacks
Private variables
Loops and closures
Modules
Stylistic considerations
Summary
3. Data Structures and Manipulation
Regular expressions
Exact match
Match from a class of characters
Repeated occurrences
Alternatives – OR
Beginning and end
Backreferences
Greedy and lazy quantifiers
Arrays
Maps
Sets
A matter of style
Summary
4. Object-Oriented JavaScript
Understanding objects
Behavior of JavaScript objects
Prototypes
Instance properties versus prototype properties
Inheritance
Getters and setters
Summary
5. JavaScript Patterns
Design patterns
The namespace pattern
The module pattern
ES6 modules
The factory pattern
The mixin pattern
The decorator pattern
The observer pattern
JavaScript Model-View-* patterns
Model-View-Controller
Models
Views
Controllers
The Model-View-Presenter pattern
Model-View-ViewModel
Summary
6. Testing and Debugging
Unit testing
Test-driven development
Behavior-driven development
JavaScript debugging
Syntax errors
Using strict
Runtime exceptions
Console.log and asserts
Chrome DevTools
Summary
7. ECMAScript 6
Shims or polyfills
Transpilers
ES6 syntax changes
Block scoping
Default parameters
Spread and rest
Destructuring
Object literals
Template literals
Maps and Sets
Symbols
Iterators
For..of loops
Arrow functions
Summary
8. DOM Manipulation and Events
DOM
Accessing DOM elements
Accessing specific nodes
Chaining
Traversal and manipulation
Working with browser events
Propagation
jQuery event handling and propagation
Event delegation
The event object
Summary
9. Server-Side JavaScript
An asynchronous evented-model in a browser
Callbacks
Timers
EventEmitters
Modules
Creating modules
npm
Installing packages
JavaScript performance
JavaScript profiling
The CPU profile
The Timeline view
Summary
Index
Mastering JavaScript
Mastering JavaScript
Copyright © 2016 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, 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.
First published: January 2016
Production reference: 1250116
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78528-134-1
www.packtpub.com
Credits
Author
Ved Antani
Reviewer
Ivano Malavolta
Commissioning Editor
Sarah Crofton
Acquisition Editor
Kevin Colaco
Content Development Editor
Merint Mathew
Technical Editor
Manthan Raja
Copy Editor
Tasneem Fatehi
Project Coordinator
Francina Pinto
Proofreader
Safis Editing
Indexer
Monica Ajmera Mehta
Production Coordinator
Conidon Miranda
Cover Work
Conidon Miranda
About the Author
Ved Antani is an AVP (engineering) at Myntra. Before Myntra, he worked with Electronic Arts, NetApp, and Oracle. Ved is passionate about programming and has been programming in JavaScript since 2005. He has extensive experience in building scalable systems and mobile applications. Ved is a minimalist, a father, and an avid tea drinker.
I would like to thank my wife, Meghna, for her support. She was always there to encourage and help me when I needed it the most.
About the Reviewer
Ivano Malavolta is a postdoctoral researcher at the Gran Sasso Science Institute (L'Aquila, Italy), and he holds a PhD in computer science from the University of L'Aquila. His research is positioned in three main fields: software architecture, Model-Driven Engineering (MDE), and mobile-enabled systems. He is especially interested in investigating how MDE techniques can be exploited for architecting complex and mobile-enabled software systems at the right level of abstraction. He is the author of more than 40 papers in international journals and peer-reviewed international conferences' proceedings; among them, he has coauthored two articles published in the IEEE Transactions on Software Engineering (TSE), which is considered the leading journal in the field of software engineering. He is a reviewer for four international journals, a program committee member of 10 international conferences, a reviewer for 13 international conferences, and a guest editor of an international journal.
He is an instructor of three courses on software engineering, mobile computing, and mobile application development via web technologies; these courses are held at the University of L'Aquila and Gran Sasso Science Institute, Italy.
He has previously reviewed other books about web technologies for Packt Publishing, such as Backbone.js Cookbook by Vadim Mirgorod and Backbone.js Blueprints by Andrew Burgess.
www.PacktPub.com
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.com.
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
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.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Preface
It would seem that everything that needs to be written about JavaScript has been written. Frankly, it is difficult to find a topic related to JavaScript that has not been discussed ad nauseam. However, JavaScript is changing at a rapid pace. ECMAScript 6 has the potential to transform the language and how we code in it. Node.js has already changed the way in which we write servers in JavaScript. Newer ideas such as React and Flux will drive the next iteration of the language. While we spend our time learning the new features, there is no denying that the foundational ideas of JavaScript have to be mastered. These ideas are fundamental and need attention. If you are already an experienced JavaScript developer, you will realize that modern JavaScript is vastly different from the language that most people have known. Modern JavaScript demands a specific stylistic discipline and rigor of thought. Tools are more powerful and slowly becoming an integral part of the development workflow. Though the language seems to be changing, it is built on some very solid and constant ideas. This book emphasizes on these fundamental ideas.
While the book was being written, things kept changing in the JavaScript landscape. Luckily, we were able to include all the important and relevant updates in this book.
Mastering JavaScript provides you with a detailed overview of the language's fundamentals and some of the modern tools and libraries, such as jQuery, Underscore.js, and Jasmine.
We hope that you enjoy this book as much as we enjoyed writing it.
What this book covers
Chapter 1, JavaScript Primer, focuses on the language constructs without spending too much time on the basic details. We will cover the trickier parts of variable scoping and loops and best practices for using types and data structures. We will also cover a lot of ground on the coding style and recommended code organization patterns.
Chapter 2, Functions, Closures and Modules, covers the core of the language intricacies. We will discuss the complexities involved in using functional aspects with different treatment for closures in JavaScript. This is a careful and elaborate discussion that will prepare you to explore more advanced design patterns further on.
Chapter 3, Data Structures and Manipulation, takes a detailed look at regular expressions and arrays. Arrays are a fundamental data type in JavaScript and this chapter will help you work effectively with arrays. Regular expressions can make your code concise—we will take a detailed look at how to use RegEx effectively in your code.
Chapter 4, Object-Oriented JavaScript, discusses object orientation in JavaScript. We will discuss inheritance and the prototype chain and focus on understanding the prototypal inheritance model that JavaScript offers. We will also discuss how different this model is from other object-oriented models to help Java or C++ programmers get familiarized with the change.
Chapter 5, JavaScript Patterns, discusses common design patterns and how to implement them in JavaScript. Once you master the object-oriented model for JavaScript, it is easier to understand design and programming patterns to write modular and easy-to-maintain code.
Chapter 6, Testing and Debugging, covers various modern methods to test and debug issues in JavaScript code. We will also explore continuous testing and test-driven methodologies for JavaScript. We will use Jasmine as the test framework.
Chapter 7, ECMAScript 6, focuses on the newer language features introduced by ECMAScript 6 (ES6). It makes JavaScript more powerful and this chapter will help you understand the newer features and how to use them in your code.
Chapter 8, DOM Manipulation and Events, takes a detailed look at JavaScript as a language of the browser. This chapter discusses DOM manipulation and browser events.
Chapter 9, Server-Side JavaScript, explains how we can use Node.js to write scalable server systems in JavaScript. We will discuss the architecture of Node.js and several useful techniques.
What you need for this book
All the examples in this book can be run on any modern browser. For the last chapter, you will need Node.js. You will need the following prerequisites to run the examples and samples from this book:
A computer with Windows 7 or higher, Linux, or Mac OS X installed.
The latest version of the Google Chrome or Mozilla Firefox browser.
A text editor of your choice. Sublime Text, vi, Atom, or Notepad++ would be ideal. The choice is entirely yours.
Who this book is for
This book is intended to equip you with the details necessary to master JavaScript. This book will be useful for the following audience:
Experienced developers familiar with other object-oriented languages. Information in this book will enable them to transition to JavaScript using their existing experience.
Web developers with some amount of experience with JavaScript. This book will help them learn advanced concepts of JavaScript and refine their programming style.
Beginners who want to understand and eventually master JavaScript. This book has the necessary information for them to get started.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: First, the
A block of code is set as follows:
function sayHello(what) {
return Hello
+ what;
}
console.log(sayHello(world
));
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Any command-line input or output is written as follows:
EN-VedA:~$ node > 0.1+0.2 0.30000000000000004 > (0.1+0.2)===0.3 false
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: You can run the page and inspect using Chrome's Developer Tool
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/MasteringJavaScript_ColorImages.pdf.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at <questions@packtpub.com>, and we will do our best to address the problem.
Chapter 1. JavaScript Primer
It is always difficult to pen the first few words, especially on a subject like JavaScript. This difficulty arises primarily because so many things have been said about this language. JavaScript has been the Language of the Web—lingua franca, if you will, since the earliest days of the Netscape Navigator. JavaScript went from a tool of the amateur to the weapon of the connoisseur in a shockingly short period of time.
JavaScript is the most popular language on the web and open source ecosystem. http://githut.info/ charts the number of active repositories and overall popularity of the language on GitHub for the last few years. JavaScript's popularity and importance can be attributed to its association with the browser. Google's V8 and Mozilla's SpiderMonkey are extremely optimized JavaScript engines that power Google Chrome and Mozilla Firefox browsers, respectively.
Although web browsers are the most widely used platforms for JavaScript, modern databases such as MongoDB and CouchDB use JavaScript as their scripting and query language. JavaScript has become an important platform outside browsers as well. Projects such as Node.js and io.js provide powerful platforms to develop scalable server environments using