Javascript Lodash project: Implement .has():Why does bracket notation work and dot notation doesn't

My initial implementation of the .has() method (steps 19 - 22) used dot notation and did NOT work

has(object,key){
    if (object.key != undefined){
      return true;
    } else {
      return false
    }
  }

when I change the dot notation to bracket notation it WORKS.

has(object,key){
    if (object[key] != undefined){
      return true;
    } else {
      return false
    }
  }

A previous lesson said:

We must use bracket notation when accessing keys that have numbers, spaces, or special characters in them. Without bracket notation in these situations, our code would throw an error.

Why did this fail using dot notation? Is undefined a special character??

1 Like

It is because key works like an attribute and simply using .key would look for the key in the object attribute that is given, but using bracket notation it looks for the key attribute in the object attribute that is given.

Hope this helps :grinning:

In regards to variables representing keys, the name key does not exist in the object. What it represents is the real attribute. We cannot use dot notation when key is a variable, that is why we must use subscript notation (brackets) to pass the represented value as a key.

Now if key actually exists as an own property, then

object.key

will work, but only then. Otherwise we must write,

object[key]
1 Like