๐Ÿง  JavaScript Function Concepts: Closures, Rest Parameters, Default Parameters & Function Hoisting

Payal PorwalPayal Porwal
7 min read

In modern JavaScript and especially while working with React, understanding how functions behave internally helps us write clean and bug-free code. In this article, we'll cover:

  • Closures

  • Rest Parameters

  • Default Parameters

  • Hoisting in Functions


โœ… 1. Closures

๐Ÿ“˜ What is a Closure?

A closure is a function that remembers variables from its outer (parent) function, even after the parent function has finished executing.

Itโ€™s like a backpack that the inner function carries, which contains all the variables from the parent function.


๐Ÿ” Real-life Example 1 โ€“ Counter Function

function createCounter() {
  let count = 0;
  return function () {
    count++;
    return count;
  };
}

const counter = createCounter();

console.log(counter()); // 1
console.log(counter()); // 2

โœ… Here, the inner function remembers the count variable even after createCounter() has run.


๐Ÿ›’ Real-life Example 2 โ€“ Cart Items

function createCart() {
  let items = [];
  return function (item) {
    items.push(item);
    return items;
  };
}

const cart = createCart();

console.log(cart("Milk")); // ["Milk"]
console.log(cart("Bread")); // ["Milk", "Bread"]

โœ… Even though createCart() is done, the inner function can still access items.


๐Ÿ” Real-life Example 3 โ€“ Personalized Greeter

function greetUser(name) {
  return function (message) {
    return `Hello ${name}, ${message}`;
  };
}

const greetPayal = greetUser("Payal");

console.log(greetPayal("welcome to our site!"));
// Output: Hello Payal, welcome to our site!

โœ… The returned function keeps access to the name even outside the parent.


โœ… 2. Rest Parameters

๐Ÿ“˜ What is a Rest Parameter?

The rest parameter allows a function to accept any number of arguments as an array using ... syntax.


๐Ÿ“Š Real-life Example 1 โ€“ Calculate Total Price

function totalPrice(...prices) {
  return prices.reduce((sum, price) => sum + price, 0);
}

console.log(totalPrice(100, 200, 50)); // Output: 350

๐Ÿงฎ Real-life Example 2 โ€“ Count Arguments

function countArgs(...args) {
  return `You passed ${args.length} arguments`;
}

console.log(countArgs("HTML", "CSS", "JS", "React")); 
// Output: You passed 4 arguments

๐Ÿ”ง Real-life Example 3 โ€“ Join Words

function joinWords(...words) {
  return words.join(" ");
}

console.log(joinWords("Frontend", "Development", "Rocks!")); 
// Output: Frontend Development Rocks!

โœ… Use this when you donโ€™t know in advance how many arguments will be passed.


โœ… 3. Default Parameters

๐Ÿ“˜ What are Default Parameters?

Default parameters are used to give default values to function parameters if no value or undefined is passed.


๐Ÿ’ฌ Real-life Example 1 โ€“ Greeting Message

function greet(name = "Guest") {
  console.log(`Hello, ${name}!`);
}

greet("Payal"); // Hello, Payal!
greet();        // Hello, Guest!

๐Ÿ“ฆ Real-life Example 2 โ€“ Product with default quantity

function addToCart(product, quantity = 1) {
  console.log(`${product} added with quantity ${quantity}`);
}

addToCart("Milk");          // Milk added with quantity 1
addToCart("Rice", 3);       // Rice added with quantity 3

๐ŸŽฏ Real-life Example 3 โ€“ Calculator with default operator

function calculate(a, b, operator = "add") {
  if (operator === "add") return a + b;
  if (operator === "subtract") return a - b;
}

console.log(calculate(5, 3)); // 8
console.log(calculate(5, 3, "subtract")); // 2

โœ… Saves time by avoiding extra checks or writing conditional logic for undefined values.


โœ… 4. Function Hoisting

๐Ÿ“˜ What is Function Hoisting?

In JavaScript, function declarations are hoisted โ€” meaning they are moved to the top of their scope before the code runs.

So, you can call the function before it's defined.


โซ Example 1 โ€“ Works fine (function declaration)

sayHello(); // Output: Hello!

function sayHello() {
  console.log("Hello!");
}

โœ… Works because sayHello is hoisted.


โŒ Example 2 โ€“ Not hoisted (function expression)

sayHi(); // โŒ Error: Cannot access before initialization

const sayHi = function() {
  console.log("Hi!");
};

โŒ sayHi is not hoisted because it's a function expression, not a declaration.


๐Ÿ“ฆ Example 3 โ€“ Hoisting with variables and functions

console.log(product); // undefined (due to var hoisting)
var product = "Milk";

show(); // Output: Showing product
function show() {
  console.log("Showing product");
}

โœ… Variables declared with var are also hoisted, but only their declaration, not the value.


๐Ÿ” Summary Table

ConceptPurposeReal-world Use Example
ClosuresInner function remembers outer scopeCounters, personalization, state
Rest ParametersAccept unlimited arguments as arrayBilling, filters, string join
Default ParametersSet fallback values for missing argumentsGreeting, quantity, role-based display
Function HoistingCall function before it's declaredUtility functions in scripts

โœ… Final Tips

  • Use closures when you want to maintain state or create private variables.

  • Use rest parameters to handle dynamic inputs (e.g., user skills, cart items).

  • Use default parameters to reduce code repetition and avoid undefined values.

  • Understand hoisting well to avoid runtime errors โ€” especially in React event handlers and lifecycle methods.


โœ… Mini Project: "Quiz App with Score Tracker"


๐Ÿ’ก Purpose:

This small app will:

  • Display a question with options

  • Track score using a closure

  • Accept any number of questions using rest parameters

  • Use default parameters to avoid missing data

  • Demonstrate function hoisting with utility functions


๐Ÿ“ Project Files:

  • index.html โ€” structure

  • style.css โ€” minimal styling

  • script.js โ€” full logic using closures, rest, default, hoisting


๐Ÿ“„ 1. index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Quiz App</title>
  <link rel="stylesheet" href="style.css" />
</head>
<body>
  <div class="container">
    <h2>๐Ÿง  Quiz App</h2>
    <div id="questionBox">Loading question...</div>
    <div id="options"></div>
    <p>Score: <span id="score">0</span></p>
    <button id="nextBtn">Next</button>
  </div>

  <script src="script.js"></script>
</body>
</html>

๐ŸŽจ 2. style.css

body {
  font-family: sans-serif;
  background-color: #f2f2f2;
  display: flex;
  justify-content: center;
  padding-top: 50px;
}

.container {
  background: white;
  padding: 20px;
  border-radius: 10px;
  width: 350px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

button {
  margin-top: 10px;
  padding: 10px;
  background: teal;
  color: white;
  border: none;
  cursor: pointer;
  width: 100%;
}

๐Ÿง  3. script.js

// โœ… Function hoisting (you can call setupQuiz before it's defined)
setupQuiz();

// โœ… Closure for score tracking
const scoreManager = (function () {
  let score = 0;
  return {
    increment: function () {
      score++;
    },
    getScore: function () {
      return score;
    }
  };
})();

// โœ… Quiz data using rest and default parameters
function getQuestions(...questions) {
  return questions.length ? questions : [
    {
      question: "What is JavaScript?",
      options: ["Programming Language", "Animal", "Toy"],
      answer: "Programming Language"
    }
  ];
}

// ๐Ÿง  Main quiz logic
function setupQuiz() {
  const questions = getQuestions(
    {
      question: "What does HTML stand for?",
      options: ["Hyper Text Markup Language", "How To Make Lasagna", "Hot Mail"],
      answer: "Hyper Text Markup Language"
    },
    {
      question: "Which company developed JavaScript?",
      options: ["Microsoft", "Netscape", "Google"],
      answer: "Netscape"
    },
    {
      question: "What is React?",
      options: ["Library", "Game", "Browser"],
      answer: "Library"
    }
  );

  let currentIndex = 0;

  function showQuestion() {
    const current = questions[currentIndex] || {};
    const questionBox = document.getElementById("questionBox");
    const optionsBox = document.getElementById("options");

    if (!current.question) {
      questionBox.innerHTML = "๐ŸŽ‰ Quiz Completed!";
      optionsBox.innerHTML = "";
      document.getElementById("nextBtn").style.display = "none";
      return;
    }

    questionBox.innerHTML = current.question;
    optionsBox.innerHTML = "";

    current.options.forEach((opt) => {
      const btn = document.createElement("button");
      btn.textContent = opt;

      // โœ… Using default parameter in event handler
      btn.onclick = function handleAnswer(selected = "") {
        if (selected === current.answer) {
          scoreManager.increment();
        }
        document.getElementById("score").textContent = scoreManager.getScore();
        currentIndex++;
        showQuestion();
      }.bind(null, opt); // bind selected value
      optionsBox.appendChild(btn);
    });
  }

  // Next button (works only if user skips)
  document.getElementById("nextBtn").addEventListener("click", function () {
    currentIndex++;
    showQuestion();
  });

  // Start quiz
  showQuestion();
}

๐Ÿ” Concepts Recap

ConceptWhere Used
ClosuresscoreManager keeps score private & tracks it
Rest ParametersgetQuestions(...questions) accepts any number of questions
Default ParametersUsed in handleAnswer(selected = "")
Function HoistingsetupQuiz() is called at top before it's defined

๐Ÿ’ก Bonus Extensions

  • โœ… Add "Restart Quiz" button

  • โœ… Save score in localStorage

  • โœ… Show correct answer when user clicks wrong one


๐Ÿง‘โ€๐Ÿซ Why this project helps learners:

  • Combines function concepts into a real app

  • Mimics real-world quiz logic

  • Can easily be extended in React later

  • Strengthens modular JS thinking

    ๐Ÿ”” Stay Connected

    If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Javascript notes, tutorials, and project ideas โ€”
    ๐Ÿ“ฉ Subscribe to our newsletter by entering your email below.

    And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment,
    ๐ŸŽฅ Donโ€™t forget to subscribe to my YouTube channel โ€“ Knowledge Factory 22 โ€“ for regular content on tech concepts, career tips, and coding insights!

    Stay curious. Keep building. ๐Ÿš€

0
Subscribe to my newsletter

Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Porwal
Payal Porwal

Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: ๐Ÿš€ In-depth explorations of emerging technologies ๐Ÿ’ก Practical tutorials and how-to guides ๐Ÿ”งInsights on software development best practices ๐Ÿš€Reviews of the latest tools and frameworks ๐Ÿ’ก Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Letโ€™s connect and grow together! ๐ŸŒŸ