Search code examples
javascriptnotation

why in the below code i'm not able to print the return statement with the dot notation in javascript


I'm learning javascript and i came across this problem in which i have a function that takes an object and a property and i have to check with the help of object.hasOwnProperty function that the object passed to the function has the property or not and if it has the property than return the value of it else return "Not Found".

This is the function i created:

function checkObj(obj, checkProp) {
  if(obj.hasOwnProperty(checkProp)){
    return obj.checkProp;  
  }else{
    return "Not Found";
  }  
}

input for the function:

checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")

so what i found that after hours of trying and finally watching the solution video is that the bracket notation would do the job solution code

function checkObj(obj, checkProp) {
  if(obj.hasOwnProperty(checkProp)){
    return obj[checkProp];  
  }else{
    return "Not Found";
  }  
}

So can anyone please shed some light on why dot notation could not achieve the task?


Solution

  • In Javascript, the dot operator is used to access properties of objects. It's takes a object as first parameter, and a property name as second operator. Note: it takes property name as second parameter - no further substitution or code execution is done on the second parameter.

    If you use obj.checkProperty, you're accessing the property named checkProperty of the object stored in obj. This object does not have a property with that name in your example, so this will fail.

    What you want to achieve is to call the property with the name stored in the variable checkProperty. This has to be done using the bracket notation, since here, further code execution is done - note the difference between obj["checkProperty"] (which is euqal to obj.checkProperty) and obj[checkProperty].