JS Built-ins
Closuresbeginner

Closures β€” Greeter factory

πŸ“– Usage Example
function makeGreeter(prefix) {
  return name => `${prefix} ${name}`
}
const greetHi = makeGreeter('Hi')
greetHi('Alice')  // β†’ 'Hi Alice'
greetHi('Bob')    // β†’ 'Hi Bob'

The greeter factory closes over the prefix string, so each produced function always prepends the same greeting without needing extra parameters.

String Concatenation Factory

Create a factory that produces greeting functions with a custom prefix.

Challenge: Create a makeGreeter(prefix) function that returns a function. The returned function takes a name and returns a greeting string in the format "{prefix} {name}".

Example:

const greetHello = makeGreeter('Hello')
greetHello('World')   // 'Hello World'
greetHello('Alice')   // 'Hello Alice'
πŸ’‘ Hints (2)
  • β€’ Use template literals to construct the greeting string
  • β€’ Capture the prefix in closure