Home > front end >  Trying to create function that would compare my age to somebody else's age
Trying to create function that would compare my age to somebody else's age

Time:11-05

Trying to create a function that would compare my age to somebody else's age. Clearly, I'm missing something because no matter what input-output is always the same. Please help.

This is what I have so far:
function compareAge(name,age){
  let myAge=27;
  if (age = myAge){
    return `${name} is the same age as me.`
  }else if (age < myAge){
    return `${name} is younger than me.`
  }else if (age > myAge){
    return `${name} is older than me.`
  }
}
  console.log(compareAge('Kat',2));

CodePudding user response:

In this if Statement you are assigning age the value of myAge and passing the result to the if.

if (age = myAge){

In Javascript the boolean value of any integer is true.

console.log(Boolean(27));
//prints true

To actually compare the values age and myAgeyou need to use the double equal sign operator. Like this:

function compareAge(name,age){
  let myAge=27;
  if (age == myAge){
    return `${name} is the same age as me.`
  }else if (age < myAge){
    return `${name} is younger than me.`
  }else if (age > myAge){
    return `${name} is older than me.`
  }
}
  console.log(compareAge('Kat',2));
  • Related