Accessing an object property with a dynamically-computed name
To access an object's property with a dynamically computed key, use bracket notation object[variable]
.
This method is critical when utilizing property names that are to be determined at runtime.
Mastering property access in JavaScript
Limitations of the dot notation
While dot notation offers brevity, it proves its limitations when the property name is not known until runtime, or when using complex property names (special characters, spaces). It lacks the flexibility to go with the flow of dynamic property names.
The squared secret: Bracket notation
On the flip side, hold on to your seats, bracket notation comes to the rescue here. Any valid expression, including variables, can be used within the brackets to access properties - as long as the expression results in a string.
Dealing with nested objects
When you are up against nested objects, brace yourself for keys that are a few levels deep. The good news is - JavaScript's reduce
function loves a good workout.
Remember, to avoid Mother Nature from throwing a TypeError tantrum, handle undefined intermediate properties safely.
Computed property names unveil code magic in ES6
The sorcery of computed property names in ES6 transformed the mundane object-literal declaration into a thriller. Ever felt like dynamically creating properties? Fret no more.
Advanced techniques in JavaScript property access
Round and round with for...in
The for...in
loop is your magic carpet for a joyride through enumerable properties (including those pesky ones with dynamic names). Don't forget to strap on hasOwnProperty
to avoid tripping over prototype chain properties.
Enter the ever-so-sleek destructuring
Destructuring pulls out properties from objects like a magician pulling out a rabbit from his hat. You can even lend these properties an alias.
Collect'em all with Object.getOwnPropertyNames()
For the times when you seek an exhaustive collection of properties, knock on Object.getOwnPropertyNames()
.
Cruise control with 'self' for global scope
In strict mode where this
cannot bask in the global scope, self
dons the superhero cape:
And.. action! with for...of and Object.entries
Modern JavaScript throws for...of
and Object.entries()
into the mix, and voila - an elegant iteration for objects with iterable properties.
Was this article helpful?