CODE CHALLENGES: INTERMEDIATE JAVASCRIPT dogFactory()


in the task 1 of exercice challenge,i had create this code to have an object contains the name breed and weight carracter the dog’s particulars passed in the function like this :

// Write your code here:
const dogFactory = (name, breed, weight) => {
  if (typeof (name && breed) =='string' && typeof weight =='number') {
    return {
      _name : name,
      _breed : breed,
      _weight : weight
    }
  }
}
console.log(dogFactory(58, 'staff', 57))
but the console run also the code when i passed a number to the dog name
output\\{ _name: 58, _breed: 'staff', _weight: 57 }

this comparison:

typeof (name && breed) =='string'

doesn’t work. JavaScript will resolve what is between brackets first

not sure how JavaScript type coercien is handling this, but it seems you always get string:

console.log(typeof ('' && ''))
console.log(typeof ('abc' && 'def'))
console.log(typeof (1 && 'def'))
console.log(typeof (1 && 2))

unless both are numbers.

so can i do if (typeof name == typeof breed && typeof weight ==‘Number’)

No, that only checks both name and breed are of the same type. So both are a Boolean or a Number for example, then the condition would also be true

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.