Returning a Function
Lesson 8 of 14 in Coddy's Function Declarations in JavaScript course.
In JavaScript, functions are first-class citizens. This means you can treat them like any other value, including creating functions that return other functions. This powerful concept allows you to create functions that generate or customize other functions based on specific needs.
Imagine you have a recipe book (outer function) that contains a function (inner function) for creating different types of cakes (chocolate cake, vanilla cake, etc.). The recipe book can create and return the specific cake-making function you need based on your request (arguments).
function greet(name) {
function displayName() {
console.log( 'Hi' + ' ' + name );
}
// returning a function
return displayName;
}
const greeting = greet('Alice');
console.log( greeting ); // output: Hi Alice- We define a function named
greetthat takes one argument,name(a string). This represents the base greeting for the inner function. - Inside
greet, we define another function nameddisplayName. This is the inner function that will be returned. - Importantly, the
greetfunction doesn't directly return the greeting message. Instead, it returns the inner functiondisplayNameusing thereturnstatement.
Challenge
EasyWrite a function named formatNumber that takes one argument, number (a number). Inside this create a nested function named formatWithTwoDecimals that takes no arguments. The nested function formatWithTwoDecimals should format the original number with two decimal places and return the formatted string.
Finally, outer function should return the inner function using return statement.
Try it yourself
// Write code here
// Don't change below
const res = formatNumber(10.5687) // res is function
console.log(res())All lessons in Function Declarations in JavaScript
1Course Introduction
What you will learn?3Ways of Function Declaration
Basic FunctionNested FunctionReturning a FunctionFunction ExpressionsArrow FunctionFunction Constructor