Use Dot Notation

ID

javascript.dot_notation

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

JavaScript

Tags

code-smell, style

Description

Reports bracket-access expressions of the form obj["foo"] whose key is a string literal that is also a valid JavaScript identifier. In those cases dot notation obj.foo is shorter, easier to read, and lets editors rename the property safely. Bracket notation is reserved for keys that genuinely need it — dynamic property names, hyphenated keys, or keys that start with a digit.

Rationale

  • obj["foo"] is just noisier obj.foo — they compile to the same property access.

  • Renaming foo in an editor catches obj.foo references but typically misses the string "foo", so bracket-with-string form silently survives the rename and breaks at runtime.

  • Code search by symbol name is more reliable when properties are accessed by dot.

  • Reserved words (class, default, constructor, …​) are valid identifiers in modern JavaScript property positions, so the rule flags obj["class"] as well — obj.class parses fine. If your project must remain compatible with very old runtimes that disallow reserved-word property names, prefer keeping bracket form for those keys and disable this rule.

// Bad - bracket notation with a literal identifier key
obj["foo"];
arr["length"];
this["constructor"];

Remediation

Use dot notation when the key is a fixed identifier; keep bracket notation only when it is required.

// Good - dot notation for plain identifiers
obj.foo;
arr.length;
this.constructor;

// Bracket notation is still required for:
obj[key];          // dynamic key
obj["my-prop"];    // not a valid identifier (hyphen)
obj["3rd"];        // not a valid identifier (leading digit)
obj[`tag-${i}`];   // template literal