Javascript Object Dot Notation and Bracket Notation

Hi, please I would like some to explain to me why dot notation didn’t work in the programme below:
function phoneticLookup(val) {
var result = “”;

var lookup = {
alpha: “Adams”,
bravo: “Boston”,
charlie: “Chicago”,
delta: “Denver”,
echo: “Easy”,
foxtrot: “Frank”
result = lookup.val;
// Only change code above this line
return result;
But using writing result = lookup[val]; gave the desired result. I would like to know if there is any important difference between the two type of notations, which is responsible for this result.

There is no key called “val” in that object. obj[val] is saying “evaluate the thing in the brackets to figure out what key it is”. obj.val is saying get the value for the key “val”. If possible you always want the dot notation because it’s unambiguous, but often you don’t know the value in advance, so you need to use the option that evaluates something, like here.

1 Like

Thanks a lot for your reply. I’ve truly learnt something new.

1 Like