Back to practice

Keep string output explicit

Difficulty: Easy

TypeScript

Try your first run

No account is needed to try this exercise. Write your answer, run the tests, and use the feedback to improve it.

  1. Read the examples and the required return value.
  2. Edit the supplied function in the editor, keeping its name and parameters. Return your answer, then select Run code.
  3. Use the test feedback to try again. Hints are available without replacing your code.

Sign in to save items for review and keep private notes.

Implement greeting(name: string): string. Trim surrounding JavaScript whitespace and return "Hello, NAME!" using the trimmed name. If the trimmed name is empty, return "Hello, friend!". Preserve case, accents, and whitespace inside the name.

What this practices

Separate normalization from a fallback decision. An input can contain characters but become empty after trimming. The decision therefore depends on the cleaned string rather than the original length.

Work through an example

" Ada Lovelace " becomes "Ada Lovelace", producing "Hello, Ada Lovelace!". The internal space remains. A tab-only input becomes empty and produces "Hello, friend!".

Edge cases to check

  • An empty input and whitespace-only input use the fallback.
  • Tabs and line breaks at the ends are whitespace too.
  • "Éva" retains its accent and case.
  • Internal repeated spaces are preserved, not collapsed.

TypeScript details

trim() returns a new string; it does not modify the input. TypeScript can infer the local cleaned value as a string, while the function signature explicitly declares the boundary. An empty string is falsey in JavaScript, but the literal string "0" is not. Do not treat a nonempty numeric-looking name as missing.

Return exactly the greeting, including its comma, space, and exclamation mark.

Examples

' Ada ''Hello, Ada!'
'\t''Hello, friend!'
'Éva''Hello, Éva!'

Constraints

Use strict TypeScript and a standalone function. No imports, packages, DOM, network, or file access. Inputs are JSON-compatible with at most 1,000 elements and 100,000 characters. Do not mutate inputs. Return the specified result rather than printing. Medium tasks combine narrowing and typed transformations.

Review lesson: Inference and explicit boundaries
TypeScript

Ready when you are

Write your solution, then run it against the practice tests.

Press Esc, then Tab to leave the editor. Code runs in an isolated browser workspace. Tests support learning, not verified grading.

Reset your code?

This replaces your current code with the starter and stops any running tests.