Reputation: 11
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
Upvotes: 0
Views: 471
Reputation: 13376
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; }
Upvotes: 0
Reputation: 21485
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.)
Upvotes: 0
Reputation: 64
You mean this?
function howdy_doody(person) {
let compareValue = 'dog'
if (compareValue == person.name) {
return 'hello'
} else {
return 'goodbye'
}
}
howdy_doody({ name: 'dog' });
Upvotes: 2