Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

365
Views
Check property exist in object or not in JavaScript?

I have one problem statement.

Implement a function propertyExists(obj, path) that takes in an object and a path (string) as arguments and returns ‘False’ if the property doesn’t exist on that object or is null, else returns the value of the property.

And here is solution.

function propertyExists(obj,path) {
    // Write logic here
    let result =  obj.hasOwnProperty(path);
    if(result)
    {
     return (obj.path);       
    }
    else
    {
        return result;        
    }
}

Is this correct way of doing it?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Multiple issues: the first name of the function should represent what it is doing, Path as variable name is vague but propertyName as a variable is clear. what you should do is either:

  1. write function called, "getValue" it returns value if exist or null

    function getValue(obj,propertyName) {
            if(!obj) { // if object not exist
           return null;
            }
           return  obj[propertyName];
        }

  1. write function called, "propertyExists" should return true if exist else false.

   function propertyExists(obj,propertyName) {
        if(!obj) { // if object not exist
       return false;
        }
       return  obj.hasOwnProperty(propertyName);
    }
 

about 4 years ago · Juan Pablo Isaza Report

0

object->obj,propertyname->path

function propertyExist(obj, path){
           if (obj.hasOwnProperty(path)) return obj[path];
                   else return false;
                      };
about 4 years ago · Juan Pablo Isaza Report

0

Here, as far as I can understand, the objects could be nested also.

Let's take obj as {"a":{"b":"dadsa"}} and path as ab

Now, the the solution which you have posted will not work. Ideally, it should return dadsa, but it will return false.

Try the below code, it will work for nested objects also.

function propertyExists(obj,path) {
    // Write logic here
    var val=obj;
    for(a of path){
        val=val[a];
        if(!val)
            return false;
    }
    return val;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!