JavaScript can return functions?? WHAT?

Varnit sharma
2 min readMay 6, 2023

tldr; yes it can

Ps. This is a series for the Solution plus concepts for LeetCode’s 30 days of JS and this is 1/30 I’ll add problem link at the end.

Functions in JavaScript can also be treated as objects or as the JS terminology goes

First Class Citizens

and hence we can pass functions inside of other functions as a parameter and we can also return a function as result from inside of other function which is also a separate concept of JS which is called

Closures

besides that you must have also noticed one more piece of code in the solution

return function(...args) {
return "Hello World"
}

here when we are returning a function and it does not have a name!

WHAT A FUNCTION WITHOUT NAME??
A. Yes you can have functions without a name but in certain conditions like IIFE or Closures and in few other places as well and these type of functions in JS terminology is called as Anonymous Functions

And hence combining the concept of Anonymous function and First order Citizen we are able to define the function in a variable like we did in our code

var createHelloWorld = function() {}

And one more minor thing but can have a major impact when solving problems and understanding JS the Spread Operator (…) which was introduced by ECMAScript foundation in ES6 version of JS

here in code when we returning the anonymous function we have coded it like

function(...args)

this can be later seen that it gets converted into an Array where you can access N number of variables
Ex

function x(...args){
console.log(args)
}
x("s","s","sss");
// this outputs ["s","s","sss"]

Code

/**
* @return {Function}
*/
var createHelloWorld = function() {
return function(...args) {
return "Hello World"
}
};
/**
* const f = createHelloWorld();
* f(); // "Hello World"
*/

Conclusion

So you see here a lot of things are going on in your weird function which returns a function and this is how JS makes it possible using few of the concepts we used above, every single line of JS is a new discovery in itself 😂 but as 30 day proceeds I’ll try writing more of these breaking the code line by line and concept by concept type of posts!

Happy 30 days of JavaScript!!

Problem — https://leetcode.com/problems/create-hello-world-function/description/

--

--

Varnit sharma
Varnit sharma

No responses yet