Nested Function
Lesson 7 of 14 in Coddy's Function Declarations in JavaScript course.
Nested functions are like superheroes with sidekicks – they're powerful functions that can create and use other functions within them.
A nested function is a function defined inside another function. The inner function has access to the outer function's variables and parameters, creating a local scope within the outer function.
Imagine you have a main function (the superhero) that needs help with a specific task. Instead of relying on an external function, it can create a helper function (the sidekick) within itself to handle that specific task. This helper function can only be accessed and used by the main function. For Example:
function calculateDiscount(originalPrice, discountPercentage) {
function calculateDiscountAmount(price, discount) {
return price * discount; // Calculate discount amount (inner function)
}
const discountAmount = calculateDiscountAmount(originalPrice, discountPercentage / 100);
const finalPrice = originalPrice - discountAmount;
return finalPrice;
}
const discountedPrice = calculateDiscount(100, 20);
console.log(discountedPrice); // Output: 80- Outer Function:
- We define a function named
calculateDiscountthat takes two arguments:originalPriceanddiscountPercentage.
- We define a function named
- Inner Function:
- Inside the outer function, we define another function named
calculateDiscountAmount. This is the nested function. It takes two arguments:priceanddiscount(notice it doesn't have access tooriginalPriceordiscountPercentagedirectly).
- Inside the outer function, we define another function named
- Output: The function returns the final price, which is 80 (after applying the 20% discount).
Challenge
EasyYour task is to create a nested function named calculateTaxAmount should takes the price and taxRate from the outer function calculateWithTax and Calculates tax amount and returns it. (The tax amount is the price multiplied by the tax rate)
Finally, the outer function should calculate and return the final price (including tax) by adding the tax amount to the original price and returns final price.
Try it yourself
function calculateWithTax(product) {
let price = product.price;
let taxRate = product.taxRate;
// write code here
}
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