DEV Community

DR
DR

Posted on

46 1 1 1 1

#2667: Create Hello World Function

In response to the recently created 30 Days of JS challenge on LeetCode, I'll be putting out my own solutions to each problem and working through a solving strategy while I'm at it.

The first challenge posted was #2667 - a problem involving a simple function-inside-function trick. Let's take a look.

Process

A brief set of instructions are given.

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

The thing I'm liking about this particular set of problems chosen for the challenge is that the majority of them have unit tests that have already been written, giving us a guideline to shoot for.

Here's the test created for this problem.

const f = createHelloWorld();
f(); // "Hello World"
Enter fullscreen mode Exit fullscreen mode

So we'll obviously start by making the createHelloWorld function, and following that we'll put another function in it that will be the return value for the first.

function createHelloWorld() {
  return function() { return "Hello World" }
}
Enter fullscreen mode Exit fullscreen mode

Note that this is ES5 syntax, using arrow functions is another option and can be done more simply by far because the function we're returning happens to be an anonymous function - a fantastic example of where we can use an arrow to shorten the code.

const createHelloWorld = () => () => "Hello World";
Enter fullscreen mode Exit fullscreen mode

Conclusion

In three lines or one, this is a simple problem with a simple solution. The most important takeaway from this problem is that we can return functions from inside of functions - a critical feature that we're going to be using a lot in the coming challenges.

If you found this helpful, be sure to leave a 💖 on the post and a ⭐ on the Github repo!

Follow for more LC content :)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay