Dot and Bracket Notation in ES6

const person = {
firstName: 'foo',
'lastName': 'baz' };
const x = 'firstName';
const y = 'lastName';

The two most common ways to access properties in JavaScript are with a dot and with square brackets. Both value.x and value[x] access a property on value — but not necessarily the same property. The difference is in how x is interpreted. When using a dot, the part after the dot must be a valid variable name, and it directly names the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas value.x fetches the property of value named “x”, value[x] tries to evaluate the expression x and uses the result as the property name.”⁴

let person = {
'first name': 'foo',
'last-name': 'baz',
2: 'baz'
};
for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(person.key); // expected output: undefined
console.log(person[key]); // expected output: 'foo' then 'baz'
}
class Vehicle {
constructor(arr) {
this.wheelTotal = arr[0];
this.energySource = arr[1];
this.manufacturer = arr[2];
if (arr[3] === undefined) this.isOn = false;
}
getSpec(spec) {
if (spec === 'getSpec') return undefined
return this[spec]
}
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Framework or Library: Which is Better?

Angular Tutorial: Building a Postman clone — Part 1

From React.Component to hooks

Introducing Material-UI component mapper for Data Driven Forms

Data Driven Forms and Material-UI logos

After Effects Expressions (Animation)

Frontend JWT token storage

Composite Pattern in TypeScript

How to Integrate Payment Gateway in Your Mobile App

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dean Gladish

Dean Gladish

More from Medium

Version controlling And JavaScript

Should I use JavaScript or TypeScript with React?

Introduction JavaScript

Solved — Format Javascript (/React) Date for Form Input