Sheiko | Javascript Unlocked | E-Book | www.sack.de
E-Book

E-Book, Englisch, 182 Seiten

Sheiko Javascript Unlocked

Improve your code maintainability, performance, and security through practical expert insights and unlock the full potential of JavaScript
1. Auflage 2025
ISBN: 978-1-78588-506-8
Verlag: De Gruyter
Format: PDF
Kopierschutz: Adobe DRM (»Systemvoraussetzungen)

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

E-Book, Englisch, 182 Seiten

ISBN: 978-1-78588-506-8
Verlag: De Gruyter
Format: PDF
Kopierschutz: Adobe DRM (»Systemvoraussetzungen)



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.

Sheiko Javascript Unlocked jetzt bestellen!

Autoren/Hrsg.


Weitere Infos & Material


Chapter 1. Diving into the JavaScript Core


You may have owned an iPhone for years and regard yourself as an experienced user. At the same time, you keep removing unwanted characters one at a time while typing by pressing delete. However, one day you find out that a quick shake allows you to delete the whole message in one tap. Then you wonder why on earth you didn't know this earlier. The same thing happens with programming. We can be quite satisfied with our coding until, all of sudden, we run into a trick or a lesser-known language feature that makes us reconsider the entire work done over the years. It turns out that we could do this in a cleaner, more readable, more testable, and more maintainable way. So it's presumed that you already have experience with JavaScript; however, this chapter equips you with the best practices to improve your code. We will cover the following topics:

  • Making your code readable and expressive
  • Mastering multiline strings in JavaScript
  • Manipulating arrays in the ES5 way
  • Traversing an object in an elegant, reliable, safe, and fast way
  • The most effective way of declaring objects
  • How to magic methods in JavaScript

Make your code readable and expressive


There are numerous practices and heuristics to make a code more readable, expressive, and clean. We will cover this topic later on, but here we will talk about syntactic sugar. The term means an alternative syntax that makes the code more expressive and readable. In fact, we already had some of this in JavaScript from the very beginning. For instance, the increment/decrement and addition/subtraction assignment operators inherited from C. is syntactic sugar for , and is a shorter form for . Besides, we have a few tricks that serve the same purpose.

JavaScript applies logical expressions to so-called short-circuit evaluation. This means that an expression is read left to right, but as soon as the condition result is determined at an early stage, the expression tail is not evaluated. If we have , the interpreter will know from the first test that the result is true regardless of other tests. So the part is not evaluated, and this opens a way for creativity.

Function argument default value


When we need to specify default values for parameters we can do like that:

function stub( foo ) { return foo || "Default value"; } console.log( stub( "My value" ) ); // My value console.log( stub() ); // Default value

What is going on here? When is (, , , , , or ), the result of the logical expression is otherwise the expression is evaluated until and this is the final result.

Starting with 6th edition of EcmaScript (specification of JavaScript language) we can use nicer syntax:

function stub( foo = "Default value" ) { return foo; }

Conditional invocation


While composing our code we shorten it on conditions:"

var age = 20; age >= 18 && console.log( "You are allowed to play this game" ); age >= 18 || console.log( "The game is restricted to 18 and over" );

In the preceding example, we used the AND () operator to invoke if the left-hand condition is Truthy. The OR () operator does the opposite, it calls if the condition is .

I think the most common case in practice is the shorthand condition where the function is called only when it is provided:

/** * @param {Function} [cb] - callback */ function fn( cb ) { cb && cb(); };

The following is one more example on this:

/** * @class AbstractFoo */ AbstractFoo = function(){ // call this.init if the subclass has init method this.init && this.init(); };

Syntactic sugar was introduced to its full extent to the JavaScript world only with the advance in CoffeeScript, a subset of the language that trans-compiles (compiles source-to-source) into JavaScript. Actually CoffeeScript, inspired by Ruby, Python, and Haskell, has unlocked arrow-functions, spreads, and other syntax to JavaScript developers. In 2011, Brendan Eich (the author of JavaScript) admitted that CoffeeScript influenced him in his work on EcmaScript Harmony, which was finalized this summer in ECMA-262 6th edition specification. From a marketing perspective, the specification writers agreed on using a new name convention that calls the 6th edition as EcmaScript 2015 and the 7th edition as EcmaScript 2016. Yet the community is used to abbreviations such as ES6 and ES7. To avoid confusion further in the book, we will refer to the specifications by these names. Now we can look at how this affects the new JavaScript.

Arrow functions


Traditional function expression may look like this:

function( param1, param2 ){ /* function body */ }

When declaring an expression using the arrow function (aka fat arrow function) syntax, we will have this in a less verbose form, as shown in the following:

( param1, param2 ) => { /* function body */ }

In my opinion, we don't gain much with this. But if we need, let's say, an array method callback, the traditional form would be as follows:

function( param1, param2 ){ return expression; }

Now the equivalent arrow function becomes shorter, as shown here:

( param1, param2 ) => expression

We may do filtering in an array this way:

// filter all the array elements greater than 2 var res = [ 1, 2, 3, 4 ].filter(function( v ){ return v > 2; }) console.log( res ); // [3,4]

Using an array function, we can do filtering in a cleaner form:

var res = [ 1, 2, 3, 4 ].filter( v => v > 2 ); console.log( res ); // [3,4]

Besides shorter function declaration syntax, the arrow functions bring the so called lexical . Instead of creating its own context, it uses the context of the surrounding object as shown here:

"use strict"; /** * @class View */ let View = function(){ let button = document.querySelector( "[data-bind=\"btn\"]" ); /** * Handle button clicked event * @private */ this.onClick = function(){ console.log( "Button clicked" ); }; button.addEventListener( "click", () => { // we can safely refer surrounding object members this.onClick(); }, false ); }

In the preceding example, we subscribed a handler function to a DOM event (). Within the scope of the handler, we still have access to the view context (), so we don't need to bind the handler to the outer scope or pass it as a variable through the closure:

var that = this; button.addEventListener( "click", function(){ // cross-cutting concerns that.onClick(); }, false );

Method definitions


As mentioned in the preceding section, arrow functions can be quite handy when declaring small inline callbacks, but always applying it for a shorter syntax is controversial. However, ES6 provides new alternative method definition syntax besides the arrow functions. The old-school method declaration may look as follows:

var foo = { bar: function( param1, param2 ) { } }

In ES6 we can get rid of the function keyword and the colon. So the preceding code can be put this way:

let foo = { bar ( param1, param2 ) { } }

The rest operator


Another syntax structure that was borrowed from CoffeeScript came to JavaScript as the rest operator (albeit, the approach is called in CoffeeScript).

When we had a few mandatory function parameters and an unknown number of rest parameters, we used to do something like this:

"use strict"; var cb = function() { // all available parameters into an array var args = [].slice.call( arguments ), // the first array element to foo and shift foo = args.shift(), // the new first array element to bar and shift bar = args.shift(); console.log( foo, bar, args ); }; cb( "foo", "bar", 1, 2, 3 ); // foo bar [1, 2, 3]

Now check out how expressive this code becomes in ES6:

let cb = function( foo, bar, ...args ) { console.log( foo, bar, args ); } cb( "foo", "bar", 1, 2, 3 ); // foo bar [1, 2, 3]

Function parameters aren't the only application of the rest operator. For example, we can use it in destructions as well, as follows:

let [ bar, ...others ] = [ "bar", "foo", "baz", "qux" ]; console.log([ bar, others ]); // ["bar",["foo","baz","qux"]]

The spread operator


Similarly, we can spread array elements into arguments:

let args = [ 2015, 6, 17 ], relDate = new Date( ...args ); console.log( relDate.toString() ); // Fri Jul 17 2015 00:00:00 GMT+0200 (CEST)

ES6 also provides expressive syntactic sugar for object creation and inheritance, but we will...



Ihre Fragen, Wünsche oder Anmerkungen
Vorname*
Nachname*
Ihre E-Mail-Adresse*
Kundennr.
Ihre Nachricht*
Lediglich mit * gekennzeichnete Felder sind Pflichtfelder.
Wenn Sie die im Kontaktformular eingegebenen Daten durch Klick auf den nachfolgenden Button übersenden, erklären Sie sich damit einverstanden, dass wir Ihr Angaben für die Beantwortung Ihrer Anfrage verwenden. Selbstverständlich werden Ihre Daten vertraulich behandelt und nicht an Dritte weitergegeben. Sie können der Verwendung Ihrer Daten jederzeit widersprechen. Das Datenhandling bei Sack Fachmedien erklären wir Ihnen in unserer Datenschutzerklärung.