Exoriri
Exoriri

Reputation: 435

Return in condition

Return does not work in condition. Although console.log works fine. Problem is that function always return false.

function func(obj, input) {
  if (input === obj) {
    console.log('Here it works');
    return true; //expected return tr
  };

  for (let key in obj) {
    func(obj[key], input);
  }

  return false;

}

Upvotes: 1

Views: 49

Answers (2)

Vimit Dhawan
Vimit Dhawan

Reputation: 677

I think it's working fine

    function func(obj, input) {
  if (input === obj) {
    console.log('Here it works');
    return true; //expected return tr
  };

  for (let key in obj) {
    contains(obj[key], input);
  }

  return false;}

var a ={}

console.log(func(a,a));
Here it works
 true

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386680

You need to check the return value of the call inside of the for loop and exit with returning true.

function contains(obj, input) {
    if (input === obj) {
        return true;
    }

    if (!obj || typeof obj !== 'object') { // check for objects
        return false;                      // and exit if not with false
    }

    for (let key in obj) {
        if (contains(obj[key], input)) {  // check for true
            return true;                  // return only if true
        }
    }
    return false;
}

console.log(contains('a', 'a'));
console.log(contains('a', 'b'));
console.log(contains({ foo: { bar: { baz: 42 } } }, '42'));
console.log(contains({ foo: { bar: { baz: 42 } } }, 42));

Upvotes: 1

Related Questions