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 a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781785881572
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Dec 07, 2015
Length: 182 pages
Edition : 1st
Language : English
ISBN-13 : 9781785881572
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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.