Name a Reusable Task

Name a Reusable Task

A function accepts inputs through parameters and gives a result back with return. A pass rule can be reused by different reports without duplicating its threshold. Returning a value is different from printing it.

Before this topic, review Make Strict-Mode Errors Visible if its terms are unfamiliar.

What you’ll learn

  • Explain name a reusable task through the school example.
  • Trace the shown operations and distinguish their result from displayed output.
  • Make the practice change and explain its consequence: The function compares the supplied 40 with the same pass threshold.

Work through the school example

This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.

JavaScript · school.js · complete example

function passed(marks) {
  return marks >= 50;
}
console.log(passed(72));

Expected output

true
Run in JavaScript compiler →

Introduction to JavaScript Functions

In JavaScript, functions are reusable blocks of code designed to perform a specific task. They're the building blocks of any application – small or large. Functions help break complex problems into manageable parts and make your code modular, readable, and reusable.

How to Define a Function in JavaScript

You can define a function using the function keyword followed by a name, parentheses (), and a block of code inside curly braces {}.

function greet() {
  console.log("Hello, welcome to JavaScript!");
}

How to Call a Function

After defining the function, you must call or invoke it using its name followed by parentheses.

function greet() {
  console.log("Hello, welcome to JavaScript!");
}

greet();
Hello, welcome to JavaScript!

Function Parameters and Arguments

You can pass data into functions through parameters, and use arguments when calling them.

function greetUser(name) {
  console.log("Hello, " + name + "!");
}

greetUser("Akira");
Hello, Akira!

Return Statement in Functions

The return keyword sends a value back to the place where the function was called.

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

let result = add(5, 3);
console.log(result);
8

Function Expression

Functions can be assigned to variables. These are called function expressions.

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

console.log(multiply(4, 2));
8

Arrow Functions (ES6)

Arrow functions provide a shorter syntax and lexically bind the this value.

const divide = (a, b) => {
  return a / b;
};

console.log(divide(10, 2));
5
5

When there's a single return statement, you can make it more concise:

const square = x => x * x;
console.log(square(6));
console.log(square(10));
36
100

Default Parameters

You can assign default values to parameters.

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

greet();       // Uses default
greet("Ravi"); // Uses given argument
Hello, Guest
Hello, Ravi

Rest Parameters

When you don't know how many arguments you'll receive, use the rest operator ....

function sum(...numbers) {
  return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3, 4));
10

Callback Functions

function process(callback) {
  console.log("Processing...");
  callback();
}

function done() {
  console.log("Done!");
}

process(done);
Processing...
Done!

Immediately Invoked Function Expression (IIFE)

IIFEs are functions that execute immediately after definition.

(function() {
  console.log("IIFE executed!");
})();
IIFE executed!

Understanding Scope in Functions

Functions define their own scope. Variables declared inside a function are local and not accessible outside.

function showScope() {
  let message = "Inside function";
  console.log(message);
}

showScope();
console.log(message); // Error
Inside function
ReferenceError: message is not defined

Closures in JavaScript

A closure gives you access to an outer function’s variables even after the outer function has finished executing.

function outer() {
  let count = 0;
  return function inner() {
    count++;
    console.log("Count: " + count);
  };
}

const counter = outer();
counter();
counter();
counter();
Count: 1
Count: 2
Count: 3

Pure vs Impure Functions

Pure functions always return the same output for the same input and have no side effects.

// Pure
function pureAdd(a, b) {
  return a + b;
}

Impure functions may change external state or depend on it.

// Impure
let counter = 0;
function impureAdd() {
  counter++;
  return counter;
}

Summary

  • Functions are core to writing reusable code in JavaScript.
  • There are multiple ways to declare functions: declarations, expressions, and arrow functions.
  • They support parameters, return values, rest arguments, and callbacks.
  • Closures and scopes are essential for managing variable access and function behavior.

Practice Challenge

Write a function called greetTime(name, time) that returns:

  • "Good morning, Alice" if time = "morning"
  • "Good evening, Alice" if time = "evening"
  • etc.

This will help you practice if-else and string concatenation inside a function!

Recognize the important boundary

A function without an explicit returned value returns undefined. Returning ends that invocation; statements afterward do not execute.

Try a small variation

JavaScript · original source for practice

function passed(marks) {
  return marks >= 50;
}
console.log(passed(72));

Your task: Replace passed(72) with passed(40). Predict the result before running the edited program.

The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.

Worked answer and reasoning

The function compares the supplied 40 with the same pass threshold.

JavaScript · complete worked variation

function passed(marks) {
  return marks >= 50;
}
console.log(passed(40));

Expected output

false
Run in JavaScript compiler →

Predict the original program

JavaScript · original program for this question

function passed(marks) {
  return marks >= 50;
}
console.log(passed(72));
What does the original JavaScript program display, in order?
Choose one answer. You can try again.

Answer and explanation

true

A function accepts inputs through parameters and gives a result back with return. A pass rule can be reused by different reports without duplicating its threshold. Returning a value is different from printing it. A function without an explicit returned value returns undefined. Returning ends that invocation; statements afterward do not execute.

Keep the useful idea

A function accepts inputs through parameters and gives a result back with return. A pass rule can be reused by different reports without duplicating its threshold. Returning a value is different from printing it.

Check your variation against this explanation: The function compares the supplied 40 with the same pass threshold.

Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Store a Function as a Value →