Home > Mobile >  Can I compare function parameters within my if statement?
Can I compare function parameters within my if statement?

Time:02-19

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

CodePudding user response:

You mean this?

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

howdy_doody({ name: 'dog' });

CodePudding user response:

function howdy_doody(person) {
  let person = 'dog' // <-- this line overwrites the input `person`; remove it
  if (person == { name: 'dog' }) { // <-- if (person.name === 'dog') {
    return 'hello'
  } else {
    return 'goodbye'
  }
}
howdy_doody({ name: 'dog' });  // <-- "hello" gets returned here, 
                               // but you're not assigning it to
                               // anything, or logging it, so there
                               // won't be a visible result

(...but above I'm assuming you actually mean to check that person has a name param with value 'dog'; if you wanted to check that person is exactly equal to the object {name:'dog'} that gets a little more complicated.)

CodePudding user response:

explanation in progress

function howdy_doody(person = {}) {
  const entries = Object.entries(person);
  return (

       entries.length === 1
    && entries[0][0] === 'name'
    && entries[0][1] === 'dog'

  ) && 'hello' || 'goodbye';
}

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

  • Related