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

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
Concept | Purpose | Real-world Use Example |
Closures | Inner function remembers outer scope | Counters, personalization, state |
Rest Parameters | Accept unlimited arguments as array | Billing, filters, string join |
Default Parameters | Set fallback values for missing arguments | Greeting, quantity, role-based display |
Function Hoisting | Call function before it's declared | Utility 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
โ structurestyle.css
โ minimal stylingscript.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
Concept | Where Used |
Closures | scoreManager keeps score private & tracks it |
Rest Parameters | getQuestions(...questions) accepts any number of questions |
Default Parameters | Used in handleAnswer(selected = "") |
Function Hoisting | setupQuiz() 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. ๐
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! ๐