Ok! So this happened! I failed an interview because I overlooked the basic!
There are two ways to access property values of an object in javascript:
- Dot notation (
user.name
) - Square Bracket notation (
user["name"]
)
And most of the time, property names are known and simple and dot notation comes naturally to many of us.
But there is a catch. Read on!
Objects
TL;TR -
Square bracket notation saved you from breaking your head compared to dot notation.
When you defined a key into a variable and wants to add it as new property into an object, it will only work if square bracket notation is used.let user = { name: "John", age: 30 }; let key = "gender"; user.key = "male"; alert( user.gender ) // undefined user[key] = "male"; alert( user.gender ) // male
Use dot notation:
When an object is already defined and you just want to read the property provided all property are single word.
Single word: "name"
Avoid dot notation:
When an object is already defined and you just want to read the property but few or all property are multiword.
multiword: "first name"
let user = {
name: "John",
age: 30,
"likes birds": true // multiword property name must be quoted
};
user.likes birds = true // this would give a syntax error
Use square bracket notation:
I mean in all case (at least from what I know, feel free to comment )
few examples: Works for all operators like charm
let user = {};
// set
user["likes birds"] = true;
// get
alert(user["likes birds"]); // true
// delete
delete user["likes birds"];
Avoid square bracket notation:
Guess we'll never know....
Read more about Objects