Popular Searches
Popular Course Categories
Popular Courses

Functions & scope

Functions & scope

25 mins JavaScript Fundamentals

Functions & scope in React JS

Course: React JS Training

Topic: Functions & scope

Course Link: React JS Training

Demo Link: Register for a Course Demo


1. Why Functions Matter

Imagine writing an online store where the price-calculation code is copied and pasted on ten different pages. One day the tax rule changes, and you have to find and fix the same logic in ten places — and you will almost certainly miss one. Functions exist to solve exactly this problem.

A function lets you write a piece of logic once, give it a name, and run it whenever you need it. This idea is so central that the rest of your journey depends on it:

  • In plain JavaScript, every interaction you code — a button click, a form check, a data fetch — is handled by a function.
  • In React, which this course builds towards, a component is itself a function that returns the UI to display, and hooks such as useState are functions too.
  • Functions keep code DRY — "Don't Repeat Yourself": one definition, many uses.

If variables are the nouns of JavaScript, functions are the verbs. This page explains functions and the rules that decide which variables a function can see — a concept called scope.


2. What Is a Function? The Definition in Simple Words

A function is a named block of reusable code that performs one specific task. Two parts of that sentence deserve attention:

  • Named and reusable: you define the block once and refer to it by name as many times as you like.
  • Runs only when called: writing a function does not execute it. The code inside stays idle until something calls the function.

Think of a function like a mixer grinder in the kitchen. You put ingredients in (inputs), the machine does its defined job, and you get a result (output). The machine sits quietly on the shelf until you switch it on — just as function code sits idle until the function is called.


3. Key Terms at a Glance

You will meet these words on this page and throughout the course, so here they are in one place:

TermPlain meaning
Function declarationCreating the function and giving it a name
Call (invoke)Asking the function to run, using its name with parentheses
ParameterA placeholder variable listed in the function definition
ArgumentThe actual value supplied when the function is called
Return valueThe result the function hands back to the caller
ScopeThe region of code where a variable is visible
HoistingJavaScript's behaviour of making declarations usable before their line appears

4. Function Syntax and Structure

The most common way to create a function is the function declaration. Here is its full anatomy:

// keyword   name          parameters
function greetStudent(name, topic) {
  // body: the code that runs when the function is called
  return "Welcome " + name + ", today we study " + topic;
}

Every function declaration has the same four parts:

  • The function keyword, which tells JavaScript you are declaring a function.
  • A name you choose, written in camelCase, that describes the action — greetStudent, calculateTotal, isValidEmail.
  • Parameters inside round brackets (), separated by commas. A function may have zero parameters, in which case the brackets stay empty.
  • The body inside curly brackets {}, which holds the statements to run.

Names should read like actions: calculateBill is better than bill, because a name that starts with a verb says what the function does.


5. How a Function Call Works, Step by Step

function addNumbers(a, b) {
  return a + b;
}

let total = addNumbers(4, 6);
console.log(total); // 10
  1. JavaScript reads the declaration and remembers the name — no code inside runs yet.
  2. The line addNumbers(4, 6) calls the function, and execution jumps into the body.
  3. The arguments 4 and 6 are copied into the parameters a and b.
  4. The body runs: return a + b; produces 10.
  5. The return statement sends 10 back to the calling line, and execution resumes there.
  6. The returned value is stored in total.

A mental picture helps: the program takes a small "trip" into the function and comes back carrying the return value. Nothing after return inside the body runs, and nothing outside the function can see its parameters — both facts are explained in the sections below.


6. Parameters and Arguments

Beginners often use these two words interchangeably. They are related but different:

ParameterArgument
Placeholder in the function definitionActual value in the function call
Listed in the first set of parenthesesListed in the parentheses of the call
Like a labelled empty boxLike the item you place into the box
function multiply(x, y) { // x and y are parameters
  return x * y;
}

multiply(3, 5); // 3 and 5 are arguments

Multiple parameters

Separate parameters with commas and pass arguments in the same order. The first argument fills the first parameter, the second fills the second, and so on — the position matters, not the name.

Default parameters

A parameter can be given a fallback value that is used when the caller supplies nothing:

function greetUser(name = "friend") {
  return "Hello, " + name + "!";
}

console.log(greetUser());        // Hello, friend!
console.log(greetUser("Priya")); // Hello, Priya!

Default parameters make functions safer to call, because a missing argument no longer slips undefined into your output.


7. The return Statement

The return statement does two jobs at once: it ends the function, and it hands a value back to whoever called it.

Sending a result back

function square(n) {
  return n * n;
}

let result = square(7);
console.log(result); // 49

Without return, the calculation would happen and then vanish — the caller would receive nothing usable.

A function without return gives undefined

function logSum(a, b) {
  console.log(a + b); // prints 9, but returns nothing
}

let x = logSum(4, 5);
console.log(x); // undefined

Printing a value and returning it are different actions. console.log shows a value on the screen; return gives the value to the calling code. A function that ends without a return always evaluates to undefined.

return ends the function immediately

function checkAge(age) {
  if (age < 18) {
    return "Sorry, not allowed";
  }
  return "Welcome aboard";
}

The moment return runs, the function stops — even if more lines follow. This is often used as an "early exit" to handle invalid input first.

A realistic example: calculating a bill

function calculateBill(amount, gstRate = 18) {
  let gst = (amount * gstRate) / 100;
  let total = amount + gst;
  return Math.round(total);
}

let payable = calculateBill(1200);          // uses the default 18% rate
let servicePayable = calculateBill(850, 5); // custom rate

console.log(payable);        // 1416
console.log(servicePayable); // 893

The second call shows the real power of functions: the same logic works for any amount and any rate, and the default keeps the common case short.


8. Function Expressions: Storing a Function in a Variable

Functions are values in JavaScript, so a function can be stored in a variable. This form is called a function expression:

let sayBye = function () {
  console.log("Bye!");
};

sayBye(); // Bye!

Here the function has no name of its own — it is an anonymous function — and the variable sayBye is how you call it.

Declaration vs expression

Function declarationFunction expression
Starts with the function keyword and a nameA function value assigned with let or const
Can be called before it is defined (see hoisting below)Cannot be used before the line that defines it
Best for standalone, top-level helpersCommon when passing functions around

A note on arrow functions

Modern JavaScript also offers a shorter "arrow" syntax for the same idea:

const sayBye = () => {
  console.log("Bye!");
};

Arrow functions are extremely common in React code and have their own rules about this. They get a full treatment later in the Modern JavaScript (ES6+) module, so for now the regular declaration is the safest form to practise.


9. What Is Scope?

Scope is the region of your program where a variable exists and can be used. A variable is not visible everywhere; it is visible only inside the block, function or file where it was created.

Think of a house. Items kept in the kitchen — the mixer, the spice box — are reachable when you are in the kitchen. Items kept in the common hall are reachable from every room. Scope works the same way: variables declared in a wide area are visible in narrower areas inside it, but not the other way around.

Scope matters because it lets two different functions use the same variable name without colliding, and it prevents outside code from accidentally changing values that belong inside a function.


10. Global Scope

A variable declared outside every function sits in the global scope. It is visible everywhere in the program — inside every function, at every level.

let courseName = "React JS Training"; // global variable

function showCourse() {
  console.log(courseName); // reading a global: allowed
}

function showCourseUpper() {
  console.log(courseName.toUpperCase());
}

showCourse();       // React JS Training
showCourseUpper(); // REACT JS TRAINING

Reading globals is easy; writing to them from many functions is where trouble starts.

The danger of overusing globals

  • Any function can change a global, so a bug in one place can silently break another.
  • Global names can collide as a program grows — two sections of code may want the same name.
  • Code that depends on many globals is hard to read, because a variable's value may have been changed anywhere.

Best practice: keep variables in the narrowest scope that works, and pass values into functions as parameters instead of reading them from the global level.


11. Local (Function) Scope

A variable declared inside a function is local to that function. It is created when the function runs and disappears when the function finishes. No code outside can see it.

function setTopic() {
  let topic = "Functions and scope"; // local variable
  console.log(topic); // works: inside the function
}

setTopic(); // Functions and scope

console.log(topic); // ReferenceError: topic is not defined

The second console.log throws a ReferenceError, because topic was born inside setTopic and disappeared when that call ended.

Two functions, same name, no clash

function firstLesson() {
  let title = "Functions";
  console.log(title);
}

function secondLesson() {
  let title = "Scope"; // a different variable, in a different scope
  console.log(title);
}

firstLesson();  // Functions
secondLesson(); // Scope

Each title lives inside its own function, so there is no conflict. This is exactly why local scope keeps large programs manageable.

Parameters are local too

Parameters behave like local variables: the name in greetUser(name) exists only inside that function's body. Also note that a variable declared with let or const inside any block — such as an if block — is visible only within that block, which is the same "narrowest scope" idea applied one level down.


12. Nested Functions and the Scope Chain

A function can be declared inside another function. The inner function can read the variables of the outer function, but the outer function cannot read the variables of the inner one.

function outer() {
  let outerVar = "I belong to outer";

  function inner() {
    let innerVar = "I belong to inner";
    console.log(outerVar); // found one level up
    console.log(innerVar); // found locally
  }

  inner();
  // console.log(innerVar); // ReferenceError if uncommented
}

outer();

When inner looks up outerVar, JavaScript follows a simple rule called the scope chain:

  1. Look in the current function's own scope.
  2. If not found, look in the enclosing (outer) function's scope.
  3. Keep moving outward until the global scope is reached.
  4. If the name is still not found, a ReferenceError is thrown.

The lookup always travels outward, never inward. This one-way visibility is why inner functions can use outer data safely. When an inner function keeps access to outer variables even after the outer call has finished, that is called a closure — an important idea that gets its own detailed page later in the Modern JavaScript module.


13. Hoisting and Functions

Hoisting is JavaScript's behaviour of processing declarations before the code runs. For functions, this has a practical consequence: a function declaration can be called before the line where it is written.

sayHello(); // Hello! — works, even though it is defined below

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

This works because the declaration is fully processed before execution begins. Function expressions behave differently, because the function value is created only when the assignment line runs:

greet(); // ReferenceError: Cannot access 'greet' before initialization

let greet = function () {
  console.log("Hi!");
};

With let and const, the variable exists but is unusable until its line runs, so calling early throws an error instead of failing silently.

Summary of the difference

Function declarationFunction expression
Hoisted completely — callable before its definitionThe variable is hoisted, the function value is not
Safe to call from anywhere in the scopeCallable only after the assignment line has run

Many teams simply follow one convention to stay safe: declare functions before the code that calls them, and prefer const with function expressions so the binding cannot be reassigned by mistake.

14. Functions as Values: Callbacks in the Real World

Part 1 showed that a function can be stored in a variable. The next step follows naturally: because functions are values, they can be passed into other functions as arguments. A function passed this way is called a callback — the receiving function "calls it back" when it needs it.

function calculate(a, b, operation) {
  return operation(a, b); // operation is a function passed in
}

function add(x, y) {
  return x + y;
}

function multiply(x, y) {
  return x * y;
}

console.log(calculate(6, 3, add));      // 9
console.log(calculate(6, 3, multiply)); // 18

Here calculate does not know in advance whether it will add or multiply. It simply calls whatever function it receives. This makes code flexible: new operations can be added without touching calculate at all.

Callbacks are everywhere in real browser code. The built-in setTimeout function, which runs code after a delay, takes a callback:

function remindMe() {
  console.log("Time to drink water!");
}

setTimeout(remindMe, 3000); // runs remindMe after 3000 ms

Notice that we pass remindMe itself, not remindMe(). When you click a button on a web page, the function that responds to the click is also a callback — you will use this constantly in the DOM module and in React, where event handlers are functions passed to components.


15. Pure Functions: The Habit React Expects

A pure function satisfies two rules:

  • Given the same inputs, it always returns the same output.
  • It changes nothing outside itself — no editing of global variables, no printing as a side effect that other code depends on.
// Pure: output depends only on the inputs
function finalPrice(price, discountPercent) {
  return price - (price * discountPercent) / 100;
}

let discountRate = 10; // outside state

// Impure: the result depends on an outside variable
function discountedPrice(price) {
  return price - (price * discountRate) / 100;
}

If discountRate changes, discountedPrice(1000) suddenly returns a different answer for the same input — that unpredictability is what purity avoids. Pure functions are also easy to test: call them with known inputs and check the outputs.

This matters beyond plain JavaScript. React is built around the idea that the UI is the output of functions: a component receives data and returns the interface to show, and React expects components to be pure — the same data in, the same UI out. Practising pure, small functions now builds the exact habit you will need later in the course.


16. Variable Shadowing: When the Same Name Appears Twice

Part 1 showed that a local variable and a global variable can safely share a name. When an inner scope declares a variable with the same name as one in an outer scope, the inner declaration is said to shadow the outer one. Inside the inner scope, the name refers to the inner variable; the outer one is untouched.

let city = "Pune";

function showCity() {
  let city = "Mumbai"; // shadows the outer city inside this function only
  console.log(city);   // Mumbai
}

showCity();
console.log(city); // Pune — the outer variable was never changed

Shadowing is legal JavaScript, but it confuses readers: while reading the function body, they may believe they are looking at the outer variable. As a habit, give variables in different scopes different, descriptive names unless there is a strong reason not to.


17. Common Mistakes and the Correct Way

Forgetting the parentheses when calling

Without parentheses, you get the function itself, not its result:

function greet() {
  return "Hello!";
}

console.log(greet); // prints the function source, not "Hello!"
console.log(greet()); // Hello! — parentheses actually run it

The same trap appears with callbacks. setTimeout(greet(), 2000) runs greet immediately and passes its result; the correct form is setTimeout(greet, 2000), which passes the function to run later.

Printing instead of returning

// Wrong: the result is shown but never handed back
function double(n) {
  console.log(n * 2);
}

let result = double(5); // result is undefined

// Correct: return, and let the caller decide what to do
function double(n) {
  return n * 2;
}

let result = double(5); // 10

A function that prints can only talk to the screen. A function that returns can be used in further calculations, stored, tested, and passed on. Prefer returning; print at the outermost layer of your program.

Creating an accidental global by forgetting let or const

// Wrong: total has no declaration, so it leaks into the global scope
function countItems() {
  total = 10;
  return total;
}

// Correct: declare it, keeping it local
function countItems() {
  let total = 10;
  return total;
}

An undeclared assignment quietly creates a global variable, which can then be overwritten by any other code. Always declare variables with let or const, even inside small functions.

Expecting a function to change the caller's variable

// Wrong expectation: score stays 10
let score = 10;

function addBonus(points) {
  points = points + 5; // only changes the local copy
}

addBonus(score);
console.log(score); // 10

// Correct: return the new value and assign it
function addBonus(points) {
  return points + 5;
}

let score = 10;
score = addBonus(score);
console.log(score); // 15

Arguments are copied into the parameters, so reassigning a parameter inside the function affects only that local copy. If you need the new value outside, return it and store it.

Mismatched or wrongly cased names

JavaScript is case-sensitive: a function declared as sayHello cannot be called as sayhello() or SayHello() — the call fails with a ReferenceError. Copy the exact name, and let consistent camelCase reduce this risk.


18. Best Practices for Functions and Scope

  • One function, one task. If a function's name needs the word "and" to describe it, split it into two functions.
  • Keep functions short. A function that fits on one screen is easier to read, test and fix.
  • Pass data in, return data out. Use parameters instead of reading global variables, and return results instead of printing them deep inside your code.
  • Use the narrowest scope that works. Declare a variable inside the function or block where it is needed, not at the global level.
  • Declare before you call. Hoisting makes declarations callable early, but reading code top-to-bottom is easier when definitions come first.
  • Prefer const for function expressions. This stops the variable from being reassigned by accident.
  • Avoid shadowing. Distinct names across scopes prevent subtle reading errors.
  • Use default parameters. Give sensible fallbacks instead of letting undefined flow through your logic.
Instead of…Do this…
One large function doing everythingSeveral small functions, each with a single purpose
Reading and writing global variablesParameters in, return values out
console.log inside a calculation functionreturn the result; log at the top level
Relying on hoisting to call earlyDeclaring functions before the code that uses them
Reusing the same name in nested scopesUnique, descriptive names per scope
Rule of thumb: a well-written function reads like a sentence — calculateBill(1200, 18) should do exactly what it says, need nothing it was not given, and hand back a result.

19. Practical Project: The Bill Splitter

This small project uses everything from both parts: declarations, parameters, defaults, return values, scope discipline and a callback. It splits a restaurant bill — with tip — among friends.

Step 1: Create the files

Make a folder called bill-splitter containing two files: index.html and script.js.

Step 2: Write the HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Bill Splitter</title>
</head>
<body>
  <h1>Bill Splitter</h1>

  <label>Bill amount:
    <input type="number" id="bill" value="1200">
  </label>

  <label>Tip percent:
    <input type="number" id="tip" value="10">
  </label>

  <label>Number of people:
    <input type="number" id="people" value="4">
  </label>

  <button id="splitBtn">Split the bill</button>
  <p id="result"></p>

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

Step 3: Write the calculation functions

Each function does exactly one job and returns its result — no printing inside:

function getTip(amount, tipPercent) {
  return (amount * tipPercent) / 100;
}

function getTotal(amount, tipPercent) {
  return amount + getTip(amount, tipPercent);
}

function getPerPerson(total, people) {
  return total / people;
}

Note how getTotal reuses getTip — small functions compose into bigger ones.

Step 4: Write the event-handler function

function splitBill() {
  let amount = Number(document.getElementById("bill").value);
  let tipPercent = Number(document.getElementById("tip").value);
  let people = Number(document.getElementById("people").value);

  if (people <= 0) {
    document.getElementById("result").textContent =
      "At least one person is needed.";
    return; // early exit for invalid input
  }

  let total = getTotal(amount, tipPercent);
  let each = getPerPerson(total, people);

  document.getElementById("result").textContent =
    "Total with tip: Rs. " + total.toFixed(2) +
    " — each person pays Rs. " + each.toFixed(2);
}

document.getElementById("splitBtn").addEventListener("click", splitBill);

The last line passes splitBill as a callback to addEventListener, which runs it whenever the button is clicked. (Events are covered in depth in the DOM module; here it simply shows a real callback in action.) All variables are local to splitBill — nothing leaks into the global scope.

Step 5: Run and verify

  1. Open index.html in your browser.
  2. Keep the default values: bill 1200, tip 10%, 4 people.
  3. Click Split the bill.
  4. Expected output: tip is 120, total is 1320.00, so the message reads Total with tip: Rs. 1320.00 — each person pays Rs. 330.00.
  5. Enter 0 for people and click again: the guard clause message appears, and no calculation runs.

Step 6: Extend it

  • Add a formatMoney function that takes a number and returns it with the currency prefix, then use it in the message.
  • Give tipPercent a default value inside getTotal and test the call getTotal(1200).

20. Practice Exercises

  1. Write a function isEven(number) that returns true when the number is even and false otherwise. Test it with 4 and 7.
  2. Write celsiusToFahrenheit(c) using the formula c * 9 / 5 + 32. Verify that celsiusToFahrenheit(100) returns 212.
  3. Write makeGreeting(name = "guest") that returns "Welcome, " + name + "!", and call it once with an argument and once without.
  4. Rewrite a function that prints its result with console.log so that it returns the result instead; print only at the call site.
  5. Predict the output of the snippet below, then run it to check yourself:
let level = 1;

function increaseLevel() {
  let level = 10; // shadows the outer level
  return level;
}

console.log(increaseLevel());
console.log(level);
  1. Write applyDiscount(price, percent) and finalBill(price, percent, gstPercent), where finalBill reuses applyDiscount and then adds GST — practising function composition.

21. Interview Questions and Answers

What is a function in JavaScript?

A function is a named, reusable block of code that performs a specific task. It is defined once and runs only when it is called, optionally accepting inputs through parameters and handing back a result with return.

What is the difference between a parameter and an argument?

A parameter is the placeholder variable listed in the function definition; an argument is the actual value supplied in the call. In function add(a, b), a and b are parameters; in add(4, 6), the values 4 and 6 are arguments.

What is scope, and which types exist in JavaScript?

Scope is the region of a program where a variable is visible. The main levels are global scope, for variables declared outside all functions, and local scope, for variables declared inside a function. Variables declared with let and const are also block-scoped, meaning they are visible only within the block that declares them.

What happens when two functions declare a variable with the same name?

Nothing breaks. Each variable lives in its own function's scope, so they are entirely separate. This is one of the main benefits of local scope — names in different functions never collide.

What is the scope chain?

When code uses a variable, JavaScript looks for it in the current scope first, then in each enclosing function's scope, moving outward until the global scope. If the name is found nowhere, a ReferenceError is thrown. The lookup travels outward only — inner scopes can see outer variables, never the reverse.

What is hoisting, and how does it treat function declarations and expressions differently?

Hoisting is JavaScript's behaviour of processing declarations before execution. A function declaration is fully hoisted, so it can be called before the line where it is written. A function expression creates its function value only when its assignment line runs, so calling it earlier fails with a ReferenceError when declared with let or const.

What does a function return if it has no return statement?

It returns undefined. Writing let x = logSum(4, 5); for a function that only logs gives x the value undefined, because nothing was explicitly sent back.

What is the difference between a function declaration and a function expression?

A declaration starts with the function keyword and a name and is hoisted completely. An expression is a function value assigned to a variable, often anonymous, and is usable only after its assignment line executes. Expressions are common when functions are passed around as values.

What is variable shadowing?

Shadowing occurs when an inner scope declares a variable with the same name as one in an outer scope. Inside the inner scope the name refers to the inner variable, while the outer variable remains unchanged and hidden. It is legal but best avoided for readability.

What is a callback function?

A callback is a function passed as an argument to another function, to be run by that function at the right time. Examples include the handler given to addEventListener, the function given to setTimeout, and the operation functions passed to a custom calculate(a, b, operation).

What is a pure function, and why does React care about purity?

A pure function always produces the same output for the same inputs and changes nothing outside itself. React treats the UI as the output of functions: components receive data and return the interface, and they are expected to be pure so the same data always produces the same UI. Writing pure utility functions in plain JavaScript builds this habit early.

Why should a program avoid too many global variables?

Globals can be read and changed by any code, so a bug in one function can silently corrupt data used elsewhere, names can collide as the program grows, and readers cannot tell where a value was last modified. Passing parameters and returning values keeps each function's data self-contained.


22. Quick Revision Checklist

  • A function is defined once, named clearly, and runs only when called with parentheses.
  • Parameters are placeholders in the definition; arguments are the real values in the call; default parameters cover missing arguments.
  • return ends the function immediately and hands a value back; a function without return gives undefined.
  • Functions are values: they can be stored in variables (function expressions) and passed to other functions (callbacks).
  • Global scope is visible everywhere; local scope is visible only inside its function; the scope chain searches outward only.
  • Shadowing hides an outer name behind an inner declaration; avoid it for clarity.
  • Function declarations are hoisted and callable early; function expressions are usable only after their assignment line.
  • Missing let/const creates accidental globals — always declare variables.
  • Pure functions: same inputs, same output, no side effects — the habit React expects.

23. Official Documentation and Further Reading


Conclusion

Functions turn scattered instructions into named, reusable building blocks, and scope decides exactly where each variable lives and who may see it. Together they give you the two discipline habits every larger topic in this course depends on: passing data in and returning results out, and keeping variables in the narrowest scope that works. The same patterns — small single-purpose functions, callbacks, purity — reappear in the DOM module as event handlers and later in React as components and hooks, so the effort you invest in this page pays off for the rest of your learning.

Learn more in the React JS Training course, or register for a course demo.

Previous Next
whatsapp