JavaScript Best Practices: Behaviors

Welcome to Part 3 of this review of the new Pluralsight course JavaScript Best Practices by Jonathan Mills.

jonathan-mills-v2

Jonathan is a JavaScript and Node.js expert working mostly in the MEAN Stack with individuals and companies to help build their technical skills to cope with the constantly changing landscape of software development.

He is also an ASP.NET insider and an international speaker focusing on JavaScript both in the browser and on the server.

Also in this series:

Part 1: Why Best Practices
Part 2: Syntax
Part 3: Behaviors
Part 4: Async Patterns
Part 5: Production Code

This module includes a discussion of some of the behaviors that may seem unexpected or even weird. JavaScript tries to be helpful, but this isn’t always a good thing.

Behaviors

Global Variables

Jonathan shows a simple example of string variables inside and outside of a function.

We see ‘Hello’ printed twice, which is kind of weird since we never declared stringToPrint as a variable. Only the positioning of the log statement is preventing the program from blowing up.

Jonathan explains how our variable, which was meant to be function scoped, is leaked up to the global scope. JavaScript can be unhelpfully helpful.

Strict Mode

Strict Mode was added in JavaScript as part of EcmaScript 5 and we can use it to prevent problems like the phantom global variable that Jonathan described.

Strict mode protects us from JavaScript’s unhelpful helpfulness, and we can easily enable it like this:

“use strict”;

Once enabled, we get errors informing us of our stupid mistakes, instead of the ridiculous smoke screen that JavaScript otherwise provides.

We might not want to apply to apply strict mode globally: it may cause a big problem when concatenating your files with legacy or otherwise sloppy JavaScript.

Read Only Properties

We see how to use Object.defineProperty to set a property as read only.

Then we see that attempting to update a readOnly value neither succeeds in updating the value nor creates an error. The operation just fails silently.

Jonathan says if he’s doing something wrong he wants to know about it.

We see that this is another area where strict mode saves us from unhelpful helpfulness.

Deleting Properties

This example shows that the delete operator doesn’t actually delete the object from memory. As MDN says:

“Unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory”

Again we can get our error messages for the stupid things we might occasionally do by using strict mode.

Duplicates

Another example of strict mode saving us from ourselves. This example is:


function x(a,b,a) {
console.log(a);
}


x(1,2,3);

Which value gets outputted to the console? 1 or 3?

Octals and Hexadecimals, Oh My

Open up your browser’s dev tools now and type 120+012

It gives the answer 130. Wait, shouldn’t that be 132?

JavaScript sees the 0 at the beginning and assumes that we want to use an octal number. 012 is octal is 10 in decimal.

Using strict mode forces us to use parseInt(12, 8) if we want to specify that we want to use 12 in octal format.

The ‘with’ statement

with‘ can be used to make our code look cleaner, but it’s got some problems.

It is so bad that it has actually been deprecated.

“with violates lexical scope, making program analysis (e.g. for security) hard to infeasible.” – Brendan Eich

Again strict mode saves us from coding insanity by throwing an error when it sees this abomination.

Jonathan shows us that we can simplify our code without using the ‘with’ statement by using an IIFE to pass in a complex reference and give it a simpler name in the function parameter.

What is this Anyway?

Jonathan says this is one of the most confusing and irritating things in JavaScript.

We see a ‘Hi there’ and ‘Whats up’ code example. The this refers to object 2 instead of object, and then later we get undefined.

We learn that if this doesn’t have anything else to bind to, it binds itself to the global scope (the window object).

This is another situation where strict mode protects us from weirdness by throwing an error:

TypeError: Cannot read property ‘val’ of undefined

Jonathan stresses that what matters is how the function is executed, not where the function is created.

This in New Objects

In this demo we see this.hello used inside a function and the effect of using and not using the new keyword when we invoke it.

The new keyword binds a new this scope onto the function.

We also see  var _this = this; and you may also have this seen pattern used before where the variable is called ctrl or vm or that.

The best practice is to take a copy of this and use that copy throughout. It’s much easier than always trying to figure out what this might reference at each point in time.

For further discussion and explanation of this see Lambdas and How ‘this’ Works in TypeScript by Steve Ognibene.

Continue to Part 4 – Async Patterns

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s