Taro Logo

Create Hello World Function

Easy
6 views
22 days ago

Write a function createHelloWorld. It should return a new function that always returns "Hello World".

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

Sample Answer
/**
 * @return {Function} return a function that always returns "Hello World".
 */
var createHelloWorld = function() {
    
    return function(...args) {
        return "Hello World"
    }
};


/**
 * const f = createHelloWorld();
 * f(); // "Hello World"
 */

This code defines a function createHelloWorld that returns another function. The returned function, when called with any arguments, will always return the string "Hello World".

Explanation:

  1. createHelloWorld = function() { ... }: This defines a function named createHelloWorld. This function's purpose is to create and return another function.
  2. return function(...args) { ... }: Inside createHelloWorld, we define and return an anonymous function. The ...args syntax uses the rest parameter, which allows the function to accept any number of arguments. However, these arguments are not used in the function's logic.
  3. return "Hello World": Regardless of the arguments passed to the inner function (if any), it always returns the string "Hello World".

Example Usage:

const f = createHelloWorld(); // Call createHelloWorld to get the function.
console.log(f());           // Output: "Hello World" (calling f with no arguments)
console.log(f({}, null, 42)); // Output: "Hello World" (calling f with arguments)