'Can I compare function parameters within my if statement?

Here is the code:

function howdy_doody(person) {
  let person = 'dog'
  if (person == { name: 'dog' }) {
    return 'hello'
  } else {
    return 'goodbye'
  }
}
howdy_doody({ name: 'dog' }); 

I'm expecting the output hello. I've tried declaring the person parameter (see code below) but get the identifier person has already been declared syntax error. I'm confused on if I can compare function parameters within an if statement or not.

Thanks



Solution 1:[1]

You mean this?

function howdy_doody(person) {
  let compareValue = 'dog'
  if (compareValue == person.name) {
    return 'hello'
  } else {
    return 'goodbye'
  }
}

howdy_doody({ name: 'dog' });

Solution 2:[2]

For an exact match of { name: 'dog' } one could e.g. utilize Object.entries which for any given object returns an array of this object's own key-value pairs / entries. Each entry gets provided as a key-value tuple.

Thus the entries array length value should be exyctly 1 and the key of this sole tuple has to equal 'name' whereas the value has to equal 'dog'.

function isValidHowdyType(value) {
  const entries = Object.entries(value ?? {});
  return (
    entries.length === 1 &&
    entries[0][0] === 'name' &&
    entries[0][1] === 'dog'
  );
}
function howdy_doody(value) {
  let phrase = 'goodbye';

  if (isValidHowdyType(value)) {
    phrase = 'hello';
  }
  return phrase;
}

console.log(
  howdy_doody({ name: 'dog' })
);
console.log(
  howdy_doody({ name: 'dog', owner: 'Jane' })
);
console.log(
  howdy_doody({ name: 'cat' })
);
console.log(
  howdy_doody({})
);
console.log(
  howdy_doody(null)
);
console.log(
  howdy_doody()
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jinyoung So
Solution 2