Haji
Haji

Reputation: 1775

Accessing JS attributes - data.att vs. data["attr"]?

var person = {name: "Johen", address: "USA"}

Is there a difference between the following 2 ways to access the person's attributes? Are there any performance implications?

var name = person.name
var address = person["address"]

Thanks!

Upvotes: 0

Views: 91

Answers (3)

Ran Tab
Ran Tab

Reputation: 31

they are mainly the same, but there is mainly 2 differences the first appears when you will try to access the data from the object with number keys.

this is better cleared with an example

const countries = {1: 'UAE', 2: 'UK'}
console.log(countries.1) //error
console.log(countries['1']) //'UAE'
console.log(countries[1]) //'UAE'

also if you have a variable with the key value you will have to use []

const countries = {first: 'UAE', second: 'UK'}
const value2 = 'first';

console.log(countries.value2) //error
console.log(countries[value2]) //'UK'

Upvotes: 0

RobG
RobG

Reputation: 147413

Both "dot" and "square bracket" access methods for object properties are described in ECMA-262 section 11.2.1. Dot access can be used only in limited cases where the name conforms to the rules for allowed characters for identifiers.

Square bracket notation can be used where the name is evaluated from an expression. It essentially says "evaluate the expression and use the result as the property name" so you can do things like:

function foo() {return 'foo'}
var obj = {};
obj[foo()] = 'foo';

Array properties are accessed in exactly the same way as object properties - arrays are just objects with a special length property.

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318518

They are equal. You need the array syntax if the key contains characters not allowed outside a string though. The same applies if you want to use a dynamic key - long time ago people used to use messy hacks like foo = eval('obj.' + propname); but foo = obj[propname]; is much nicer of course

IMO the obj.property syntax is much nicer since it's shorter and more natural.

Upvotes: 2

Related Questions