Write a greeting function

“The greeter”, a White belt challenge from the CurlyScript Dojo. It uses what Grade 2: Data Types: What Goes in the Boxes? teaches, and 3 tests check your answer.

The challenge

Write a function greet(name) that returns "Hello, NAME!". If the name is an empty string, return "Hello, friend!" instead.

Example
greet("Mia")  // "Hello, Mia!"
greet("")     // "Hello, friend!"

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • greet("Mia") gives "Hello, Mia!"
  • greet("Lucas") gives "Hello, Lucas!"
  • greet("") gives "Hello, friend!"

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

A template literal makes this easy: `Hello, ${name}!`

Hint 2

An empty string is falsy, so name || "friend" gives a fallback.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function greet(name) {
  return `Hello, ${name || "friend"}!`;
}

Learn what you need

This exercise uses what Grade 2: Data Types: What Goes in the Boxes? teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning