[Easy] LeetCode JS 30 - 2667. Create Hello World Function

March 5, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2667. Create Hello World Function

Question Prompt

Given a function fn and a time in milliseconds t, return a debounced version of that function.

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"

// Example 2
Input: args = [{},null,42]
Output: "Hello World"
Explanation:
const f = createHelloWorld();
f({}, null, 42); // "Hello World"

Solutions

We need a function createHelloWorld that doesn't directly print "Hello World", but instead returns another function that does. This hints at using functions as values and closures.

We define an inner function within createHelloWorld that simply returns "Hello World". This inner function captures the environment (scope) of createHelloWorld when it's created, even though it's called later.

The createHelloWorld function doesn't execute the inner function, it simply returns it. This allows us to store the returned function and call it later, even outside the createHelloWorld scope.

var createHelloWorld = function () {
  return function () {
    return "Hello World";
  };
};

Or we can use the arrow function syntax to make it more concise. Arrow functions can be shorter, but their readability might suffer for those unfamiliar with the syntax

const createHelloWorld = () => () => "Hello World";
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee