Home > Software design >  Trying to write a function that takes a name (string) and age to return a greeting
Trying to write a function that takes a name (string) and age to return a greeting

Time:07-07

I am trying to write a function that takes a name (string) and age (number) to return a greeting.

function createLongGreeting(name, age) {
   if (name === "" && age === number);
   return name, age;
}

Henter code hereow do I console.log it to the expected result below?

The expected result should be: Hello, my name is Daniel and I'm 30 years old

CodePudding user response:

To console log you can try:

function createLongGreeting(name, age) {
   return `Hello, my name is ${name} and I'm ${age} years old`;
}
console.log(createLongGreeting('Daniel', 30))

CodePudding user response:

Template strings allow you to insert variables into a string as long as you use backticks to replace the quotes you would normally use with a "normal" string.

But it also looks like you're trying to validate the name and age. and for that we can use the typeof operator, along with any additional checks you need to make (using || - logical OR).

function createLongGreeting(name, age) {

  if (typeof name !== 'string' || name === '') {
    return 'Name must be a non-empty string';
  }
  
  if (typeof age !== 'number' || age <= 0) {
    return 'Age must be a number greater than zero';
  }
  
  return `Hello, my name is ${name} and I'm ${age} years old`;

}

console.log(createLongGreeting('bob', 34));
console.log(createLongGreeting('bob', 'number'));
console.log(createLongGreeting('', 34));
console.log(createLongGreeting('janice', 134));

  • Related