Create Hello World Function
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Write a function createHelloWorld. It should return a new function that always returns "Hello World".
Examples
Example 1
Input: args = []
Output: "Hello World"
Explanation:
const f = createHelloWorld();
f(); // "Hello World"
The function returned by createHelloWorld should always return "Hello World".
Example 2
Input: args = [{},null,42]
Output: "Hello World"
Explanation:
const f = createHelloWorld();
f({}, null, 42); // "Hello World"
Any arguments could be passed to the function but it should still always return "Hello World".
Constraints
0 <= args.length <= 10
Solution
Method 1 – Closure Returning Constant
Intuition
The key idea is to use a closure that ignores its arguments and always returns the string "Hello World". This leverages JavaScript/TypeScript's ability to return a function from another function, capturing the desired behavior.
Approach
- Define a function
createHelloWorldthat returns a new function. - The returned function accepts any arguments (using rest parameters) but always returns the string "Hello World".
- The closure ensures the returned function always produces the same output, regardless of input.
Code
JavaScript
function createHelloWorld() {
return function(...args) {
return "Hello World";
};
}
TypeScript
function createHelloWorld(): (...args: any[]) => string {
return function(...args: any[]): string {
return "Hello World";
};
}
Complexity
- ⏰ Time complexity:
O(1), as the function always returns a constant string. - 🧺 Space complexity:
O(1), as no extra space is used beyond the closure.