Menu
Coddy logo textTech

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 greet that takes one argument, name (a string). This represents the base greeting for the inner function.
  • Inside greet, we define another function named displayName. This is the inner function that will be returned.
  • Importantly, the greet function doesn't directly return the greeting message. Instead, it returns the inner function displayName using the return statement.
challenge icon

Challenge

Easy

Write 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