LearningJavaScript TutorialFunctions & Scope
CHAPTER 7 · REUSABLE LOGIC

JavaScript Functions & Scope

Functions reusable blocks of logic banati hain, aur scope decide karta hai ki variable ko code ke kis part se access kiya ja sakta hai. Ye dono concepts JavaScript structure samajhne ke liye bahut important hain.

English + Hinglish36 min readPractice included

What is a function?

A function is a reusable block of code designed to perform a task. Instead of repeating the same logic, you can define it once and call it whenever needed.

function.jsJS
function greet() {
  console.log("Hello, BrounStack!");
}

greet();
greet();
Hinglish Explanation

Function ko reusable machine samjho. Machine ek baar define hoti hai; jab bhi uska naam call karte ho, uska code run hota hai.

Function declaration

A function declaration uses the function keyword, a name, parentheses and a block.

declaration.jsJS
function showCourse() {
  console.log("JavaScript");
}

showCourse();

The function body does not run when the function is defined. It runs when the function is called.

Parameters and arguments

Parameters are names listed in the function definition. Arguments are the actual values passed when calling the function.

parameters.jsJS
function greetStudent(name) {
  console.log("Hello, " + name);
}

greetStudent("Aman");
greetStudent("Riya");
Remember: name parameter hai; "Aman" aur "Riya" arguments hain.

Multiple parameters

A function can accept more than one parameter.

multiple.jsJS
function add(a, b) {
  console.log(a + b);
}

add(10, 5);

Argument order matters because the first argument maps to the first parameter.

Returning a value

return sends a value back to the code that called the function and ends that function call.

return.jsJS
function add(a, b) {
  return a + b;
}

const total = add(10, 5);
console.log(total); // 15
console.log vs return

console.log() value ko console me dikhata hai. return value ko function ke bahar wapas bhejta hai taaki us value ko store, compare ya reuse kiya ja sake.

Early return

A function can return early when a condition is met. This often reduces deep nesting.

early-return.jsJS
function getAccessMessage(isLoggedIn) {
  if (!isLoggedIn) {
    return "Please sign in";
  }

  return "Welcome to the course";
}

Default parameters

Default parameters provide a fallback when an argument is missing or explicitly undefined.

defaults.jsJS
function greet(name = "Student") {
  return "Hello, " + name;
}

console.log(greet());
console.log(greet("Aman"));

Function expressions

A function can also be stored in a variable.

expression.jsJS
const multiply = function (a, b) {
  return a * b;
};

console.log(multiply(4, 3));

Here the function value is assigned to the multiply binding.

Arrow functions

Arrow functions provide a shorter function syntax and are common in modern JavaScript.

arrow.jsJS
const subtract = (a, b) => {
  return a - b;
};

console.log(subtract(10, 4));

For a single expression, an arrow function can use implicit return.

implicit-return.jsJS
const square = number => number * number;

console.log(square(5)); // 25
Important: Arrow functions are not just shorter syntax in every situation. Their this behavior differs from regular functions; we will revisit that later when objects and classes are covered.

Functions as values and callbacks

Functions are values in JavaScript. That means they can be stored in variables and passed to other functions. A function passed for later use is commonly called a callback.

callback-preview.jsJS
function runTask(task) {
  task();
}

function sayReady() {
  console.log("Ready");
}

runTask(sayReady);

This idea becomes especially useful with arrays, events and asynchronous JavaScript.

What is scope?

Scope defines where a variable or function name can be accessed.

Simple idea

Variable har jagah automatically available nahi hota. Jis area me variable defined hai, uske rules decide karte hain ki usko kaha use kar sakte ho.

Global scope

A variable declared outside functions and blocks can be available to a wider part of the script.

global.jsJS
const courseName = "JavaScript";

function showName() {
  console.log(courseName);
}

showName();

Too many global variables can make larger programs harder to maintain, so keep scope as small as practical.

Function scope

Variables declared inside a function are normally available only inside that function.

function-scope.jsJS
function showScore() {
  const score = 90;
  console.log(score);
}

showScore();
// console.log(score); // ReferenceError

Block scope

let and const are block-scoped. A block is commonly created with curly braces in conditions and loops.

block-scope.jsJS
if (true) {
  const message = "Inside block";
  let count = 1;
  console.log(message, count);
}

// console.log(message); // ReferenceError
Contrast: var is not block-scoped in the same way; its older scoping rules are one reason modern code commonly prefers let and const.

Lexical scope

Inner functions can access variables from their surrounding outer scope. Which scope is available is determined by where functions are written.

lexical.jsJS
function outer() {
  const topic = "Scope";

  function inner() {
    console.log(topic);
  }

  inner();
}

outer();

The inner function can read topic because it is defined inside the outer function's scope.

Variable shadowing

An inner scope can declare a variable with the same name as an outer scope. The inner variable temporarily shadows the outer one.

shadowing.jsJS
const status = "global";

function checkStatus() {
  const status = "local";
  console.log(status); // local
}

checkStatus();
console.log(status); // global

Shadowing is valid, but too much same-name reuse can reduce readability.

Function hoisting basics

Function declarations can often be called before their declaration appears in the source because declarations are processed during setup of the scope.

hoisting.jsJS
sayHello();

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

Function expressions and arrow functions stored in const or let do not behave the same way before initialization.

Beginner habit: Hoisting ko trick ki tarah use mat karo. Functions ko logically organize karo so code reading natural rahe.

Closure basics

A closure happens when a function keeps access to variables from the lexical scope where it was created, even after the outer function has finished running.

closure.jsJS
function createCounter() {
  let count = 0;

  return function () {
    count++;
    return count;
  };
}

const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
Closure ko simple tarike se

Returned inner function outer function ke count variable ko “remember” karta hai. Isliye har call par same private count update hota rehta hai.

Keep functions focused

Functions are easier to test and reuse when each function has one clear responsibility and uses inputs/returns instead of depending on many unrelated global variables.

focused.jsJS
function calculatePercentage(score, total) {
  return (score / total) * 100;
}

const percentage = calculatePercentage(45, 50);
console.log(percentage);

Common beginner mistakes

  • Function define karke call karna bhool jana.
  • console.log() aur return ko same samajhna.
  • Arguments wrong order me pass karna.
  • return ke baad same function me code run hone ki expectation rakhna.
  • Local variable ko function ke bahar access karna.
  • let/const block scope ignore karna.
  • Arrow function ke advanced this behavior ko regular function jaisa assume karna.
  • Too many global variables banana.
  • Same variable names se unnecessary shadowing create karna.

Beginner best practices

  • Function names ko action-oriented aur meaningful rakho: calculateTotal, showMessage.
  • Ek function ko ek clear job do.
  • Reusable result ke liye return prefer karo.
  • Default to const for function expressions; reassignment needed ho tab let.
  • Scope ko jitna possible ho utna narrow rakho.
  • Deep nesting aur unnecessary global state avoid karo.
  • Simple code ko clever one-liners se zyada preference do while learning.

Chapter checklist

  • Function declare aur call kar sakte ho?
  • Parameters aur arguments ka difference clear hai?
  • return value ko reuse kar sakte ho?
  • Function declaration, expression aur arrow syntax recognize kar sakte ho?
  • Global, function aur block scope ka basic difference clear hai?
  • Lexical scope aur closure ka beginner-level idea samajh aaya?

Practice Task — Function & Scope Lab

Browser Console me ye exercises khud type karo.

  1. greet() function banao jo ek message print kare.
  2. greetStudent(name) banao aur three different names pass karo.
  3. add(a, b) function banao jo result return kare.
  4. getResult(score) function me condition use karke Pass/Fail return karo.
  5. Default parameter wala greet(name = "Student") function banao.
  6. Ek function expression se multiplication karo.
  7. Arrow function se square calculate karo.
  8. Global variable aur function-local variable ka access compare karo.
  9. if block ke andar const declare karke bahar access karne ki error observe karo.
  10. Simple createCounter() closure example khud type karke 3 calls ka output dekho.