Search code examples
javascriptarraysfor-loopjavascript-objectsand-operator

how do nested if statements and the && (and) operator differ inside this for loop?


There's similar questions on here, but I couldn't find one related to this. Here's my question:

These two functions output different results. I was under the impression that the && operator essentially worked the same as a nested if statement. There is obviously a misunderstanding/logic mistake on my end about how the && operator works. I believe it has something to do with being in the loop and trying to read the conditions at the same time or something similar, but if anyone could elaborate on what's happening it would be appreciated. What is going on with the && operator in the second function and why is it outputting the property as not found?

var contacts = [
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    },
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    }
];

function lookUp(arr, firstName, prop){
  for (var x = 0; x < contacts.length; x++){
    if (arr[x].firstName === firstName) 
      if (arr[x].hasOwnProperty(prop)) 
        return arr[x][prop];
      else 
        return "No such property";
  }
}

lookUp(contacts, "Kristian", "likes")
// ["Javascript", "Gaming", "Foxes"]

function lookUp(arr, firstName, prop){
  for (var x = 0; x < contacts.length; x++){
    if (arr[x].firstName === firstName && arr[x].hasOwnProperty(prop))  
      return arr[x][prop];
    else 
        return "No such property";
  }
}

lookUp(contacts, "Kristian", "likes")
// "No such property"

Solution

  • A correct function could look like the following:

    function lookUp(arr, firstName, prop) {
        for (var x = 0; x < contacts.length; x++) {
            if (arr[x].firstName === firstName && arr[x].hasOwnProperty(prop)) 
                return arr[x][prop];
        }
        return "No such property";
    }
    

    Explanation

    Your loop will just have one iteration because when the first if is true it will return arr[x][prop] or if it is false it will return "No such property"

    A return jumps allways out of a function and that is the reason why the loop stops

    Instead of the "correct" solution will iterate through all array elements and if there isn't the provided name it will return with the "No such property"