I'm trying to understand the difference between the Dot and the Square Bracket Notation. While going through various examples here on SO and on some other sites, I came across these two simple examples:
var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello
var user = {
name: "John Doe",
age: 30
};
var key = prompt("Enter the property to modify","name or age");
var value = prompt("Enter new value for " + key);
user[key] = value;
alert("New " + key + ": " + user[key]);
The first example returns y to be undefined if in third line I replace the obj[x]
with obj.x
. Why not "hello"
But in the second example the expression user[key]
can simply be replaced with user.key
without any anomalous behavior (at-least to me).
Now this confuses me as I recently learned that if we want to access properties by name stored in a variable, we use the [ ] Square bracket Notation.