Dot Notation Gotchas in Javascript

It is quite common to use dot notation to access object’s props. How can you ever go wrong?

We have seen a bit of dot and bracket notations in all about Javascript objects and props post.

We have learnt to use dot notations to make our code more readable -

const apple = { name: "apple", color: "reddish red", shape: "round" };

console.log("name: ", apple.name); // apple
console.log("shape: ", apple.shape); // round

At the same time, you want to be careful with stuffing dots down the throat of every program. Note the following gotchas while using dot notation.

Reserved words and special characters

In bits and pieces across many programs, you may have also come to understand that using dot notations may not work as expected for reserved words and strings with special characters.

const apple = {
  'short name': "apple",
  color: "red",
  shape: "round",
  prototype: "sweet fruit"
};

// don't do

console.log("prototype: ", apple.prototype); // apple

// won't work

console.log("short: ", apple.short name); // round
//SyntaxError: missing ) after argument list
Non-existential Props

Dot notations may also throw errors when the said prop does not exist.

console.log(vehicle.brand);

// If you are not sure if prop exists, use -
console.log(vehicle["brand"]);
Primitives and methods

There are many other cases of primitives being accorded the treatment they don’t deserve when it comes to using dot notation to access a method.

Consider below examples where a string is treated as an object.

console.log("Oabc".match(/a/));
// [ 'a', index: 1, input: 'Oabc', groups: undefined ]

console.log("Obj".match(/a/)); // null
//console.log("Obj".match(/a/).length);
// TypeError: Cannot read property 'length' of null
Numbers

Consider a number being treated as - well, a number.

console.log(42.toString());
// SyntaxError: Invalid or unexpected token

While, this works -

console.log((42).toString()); // 42

In the above case, Javascript is trying to force a decimal on a number instead of seeing it as a method.

In Conclusion

Here are a few important points to keep in mind when using dot notations -

  • Do not use dot notations on methods or props containing special characters or reserved words
  • Always enclose numbers in brackets while using dot notation - lest it is confused with decimal point
  • When in doubt about a prop, always use bracket notation. Looks ugly but gets things done
comments powered by Disqus