samedi 28 janvier 2017

If / Else statement with curly braces

I'm trying to create a function with two arguments, one for an array (ary) and the second for an name that will be search inside the array.

However, I don't understand why the first code does not work and the second does.

Can someone explain it, please?

// wrong code
var fruit = ['banana', 'apple', 'cherry', 'watermelon'];
var food = ['pizza', 'rice', 'cheese', 'potato'];
var search = function(ary, name) {
    for (var i = 0; i < ary.length; i++) {
        if (name == ary[i]) {
            return name + " was found!";
        } else {
            return name + " was not found";
        }
    }
};
search(food, 'potato');
//"potato was not found"


// right code
var fruit = ['banana', 'apple', 'cherry', 'watermelon'];
var food = ['pizza', 'rice', 'cheese', 'potato'];
var search = function(ary, name) {
    for (var i = 0; i < ary.length; i++)
        if (name == ary[i]) 
            return name + " was found!";
    return name + " was not found";
};

search(food, 'potato');
//"potato was found!"

Thanks!

Aucun commentaire:

Enregistrer un commentaire