Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Javascript Unlocked
Javascript Unlocked

Javascript Unlocked: Improve your code maintainability, performance, and security through practical expert insights and unlock the full potential of JavaScript

eBook
€8.99 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Javascript Unlocked

Chapter 2. Modular Programming with JavaScript

Engineering in general is all about splitting large tasks into small ones and composing the solutions of these tasks in a system. In software engineering, we break the code-base into modules by following the principles of low coupling and high cohesion. In this chapter, we will talk about the approaches to create modules in JavaScript by covering the following topics:

  • How to get out of a mess using modular JavaScript
  • How to use asynchronous modules in the browser
  • How to use synchronous modules on the server
  • JavaScript built-in module system
  • Transpiling CommonJS for in-browser use

How to get out of a mess using modular JavaScript

How many digital photos do you have, probably thousands, or more? Just imagine if your image viewer had no capacity to categorize. No albums, no books, no categories, nothing. It would not be of much use, does it? Now let's assume that you have a JavaScript application in a single file and it grows. When it approaches thousand or more than a thousand lines of code, however good your code design is, from a maintainability perspective, it still turns into a useless pile like that enormous list of uncategorized photos. Instead of building a monolithic application, we have to write several independent modules that combine together to form an application. Thus, we break a complex problem into simpler tasks.

Modules

So, what is a module? A module encapsulates code intended for a particular functionality. A module also provides an interface declaring what elements the module exposes and requires. A module is often packaged in a single file...

How to use asynchronous modules in the browser

To get a grasp on AMD, we will do a few examples. We will need script loader RequireJS (http://requirejs.org/docs/download.html). So you can download it and then address the local version in your HTML or give it an external link to CDN.

First of all, let's see how we can create a module and request it. We place the module in the foo.js file. We use the define() call to declare the module scope. If we pass an object to this, the object simply gets exported:

foo.js

define({
  bar: "bar",
  baz: "baz"
});

When we pass a function, it is called and its return value is exported:

foo.js

define(function () {
  "use strict";
  // Construction
  return {
    bar: "bar",
    baz: "baz"
  };
});

Next to foo.js, we place main.js. This code can be described as follows: call the given callback when all the modules supplied to the first argument (here only foo, which means ./foo.js) are loaded and available...

How to – use synchronous modules on the server

The following examples require Node.js. It will take just a few minutes to install Node.js using the pre-built installer available at https://nodejs.org/download/ or even faster via a package manager at https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager.

We will start by putting a simple logic into a module:

foo.js

console.log( "I'm running" );

Now we can call the module:

main.js

require( "./foo" );

In order to run the example, we will open the console (under Windows, you can simply run CMD.EXE, but I would recommend an enhanced tool like CMDER available at http://cmder.net/). In the console, we type the following:

node main.js
How to – use synchronous modules on the server

As soon as Enter is pressed, the console outputs I'm running. So when a module is requested, its body code is invoked. But what if we request the module several times?

main.js

require( "./foo" );
require( "./foo" );
require( "./foo&quot...

JavaScript's built-in module system

Well, both AMD and CommonJS are community standards and not a part of the language specification. However, with EcmaScript 6th edition, JavaScript acquired its own module system. At the moment, no browser yet supports this feature, so we have to install the Babel.js transpiler to fiddle with the examples.

Since we already have Node.js that is distributed with NPM (the Node.js package manager), we now can run the following command:

npm install babel -g

Named exports

Now we can write a module as follows:

foo.es6

export let bar = "bar";
export let baz = "baz";

In ES6, we can export multiple elements. Any declaration prefixed with the keyword export becomes available for import:

main.es6

import { bar, baz } from "./foo";
console.log( bar ); // bar
console.log( baz ); // baz

Since we don't yet have any support for ES6 modules in the browser, we will transpile them into CommonJS or AMD. Here Babel.js helps us:

babel --modules...

Transpiling CommonJS for in-browser use

While HTTP/2 and Packaging on the Web are still on their way, we need fast modular applications. As it was previously mentioned, we can divide the application code into CommonJS modules and transpile them for in-browser use. The most popular CommonJS transpiler is surely Browserify (http://browserify.org). The initial mission of this tool was to make Node.js modules reusable. They quite succeeded in this. It may feel like magic, but you can really use EventEmitter and some other Node.js core modules on the client. However, with the main focus on Node.js compatibility, the tool provides too few options for CommonJS compilation. For example, if you want dependency configuration, you have to use a plugin. In a real-world project, you will likely end up with multiple plugins, where each has a specific configuration syntax. So the setup in general gets over-complicated. Rather, we'll examine here another tool called CommonJS Compiler (https://github...

How to get out of a mess using modular JavaScript


How many digital photos do you have, probably thousands, or more? Just imagine if your image viewer had no capacity to categorize. No albums, no books, no categories, nothing. It would not be of much use, does it? Now let's assume that you have a JavaScript application in a single file and it grows. When it approaches thousand or more than a thousand lines of code, however good your code design is, from a maintainability perspective, it still turns into a useless pile like that enormous list of uncategorized photos. Instead of building a monolithic application, we have to write several independent modules that combine together to form an application. Thus, we break a complex problem into simpler tasks.

Modules

So, what is a module? A module encapsulates code intended for a particular functionality. A module also provides an interface declaring what elements the module exposes and requires. A module is often packaged in a single file, which...

Left arrow icon Right arrow icon

Key benefits

  • Improve your JavaScript code for better maintainability and performance
  • Discover how to implement scalable application architecture with JavaScript
  • Learn to use JavaScript behind the browser, including its command-line tools, desktop apps, and native mobile apps

Description

JavaScript stands bestride the world like a colossus. Having conquered web development, it now advances into new areas such as server scripting, desktop and mobile development, game scripting, and more. One of the most essential languages for any modern developer, the fully-engaged JavaScript programmer need to know the tricks, non-documented features, quirks, and best practices of this powerful, adaptive language. This all-practical guide is stuffed with code recipes and keys to help you unlock the full potential of JavaScript. Start by diving right into the core of JavaScript, with power user techniques for getting better maintainability and performance from the basic building blocks of your code. Get to grips with modular programming to bring real power to the browser, master client-side JavaScript scripting without jQuery or other frameworks, and discover the full potential of asynchronous coding. Do great things with HTML5 APIs, including building your first web component, tackle the essential requirements of writing large-scale applications, and optimize JavaScript’s performance behind the browser. Wrap up with in-depth advice and best practice for debugging and keeping your JavaScript maintainable for scaling, long-term projects. With every task demonstrated in both classic ES5 JavaScript and next generation ES6-7 versions of the language, Whether read cover-to-cover or dipped into for specific keys and recipes, JavaScript Unlocked is your essential guide for pushing JavaScript to its limits.

Who is this book for?

JavaScript Unlocked is for those JS developers who want to see just how far they can push their favourite language through practical insight and techniques.

What you will learn

  • Make your code readable and expressive by using simple syntax of JavaScript
  • Grasp existing JavaScript collections such as arrays and array-like objects
  • Develop abstract data types in most effective way to extend JavaScript into a more flexible and powerful programming language
  • Examine the pros and cons of JavaScript by implementing real-time code examples
  • Flourish real-time mini-projects by using JavaScript on server side to develop desktop as well as mobile applications
  • Work on parallel tasks with asynchronous JavaScript
  • Improve code maintainability and readability and boost apps performance through JavaScript

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 07, 2015
Length: 182 pages
Edition : 1st
Language : English
ISBN-13 : 9781785885068
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 07, 2015
Length: 182 pages
Edition : 1st
Language : English
ISBN-13 : 9781785885068
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 66.98
JavaScript at Scale
€41.99
Javascript Unlocked
€24.99
Total 66.98 Stars icon
Banner background image

Table of Contents

9 Chapters
1. Diving into the JavaScript Core Chevron down icon Chevron up icon
2. Modular Programming with JavaScript Chevron down icon Chevron up icon
3. DOM Scripting and AJAX Chevron down icon Chevron up icon
4. HTML5 APIs Chevron down icon Chevron up icon
5. Asynchronous JavaScript Chevron down icon Chevron up icon
6. A Large-Scale JavaScript Application Architecture Chevron down icon Chevron up icon
7. JavaScript Beyond the Browser Chevron down icon Chevron up icon
8. Debugging and Profiling Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(2 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Amazon Customer Feb 05, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
[Disclosure: I am the technical reviewer for this book]Let me start by saying, if you want to maximize the benefit from reading "JavaScript Unlocked" you better have understanding of JavaScript 101. That said, take it from someone who has done a ton of reading on the subject matter that the author covers in this book. It's simply an exceptional resource for modern JS programmers.It gets you started with JavaScript core and then covers one specific but practically vital topic for modern Web App development. My personal favorite chapters are "Modular Programming with JavaScript", "Asynchronous JavaScript" and "A Large Scale JavaScript Application Architecture". Examples are pretty realistic to which you can relate to and that helps you understand the concept completely so that it can be used in your day to day coding.Overall, its a great packaging of cherry picked topics which JS programmers require today to build scalable and realistic Web App.
Amazon Verified review Amazon
Michael Apr 25, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is my kind of technical book! I love the no-fluff, just-the-facts approach. The author makes a statement, then follows it up with a concise example that makes the concept crystal clear. I'm able to put the concepts immediately to use in my own applications. I'm not forced to wade through pages of tutorials that make a single point, like other books. Many thanks to the author for making efficient use of my time. I wish more books were like this. The topic coverage it fantastic, and its packed with tips and tricks I've never seen before.Best of all, it illustrates techniques and best practices for both ES5 and ES2015, which was a pleasant surprise for me. The book will remain relevant for some time to come. There's nothing here that I will have to unlearn in a few months. Love this book. 5 stars!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.