A function is a named block of code that can be called whenever it is needed, with different inputs.
Defining and Calling Functions
A function declaration has the keyword function, a name, parameters in brackets and a body: function area(l, w) { return l w; }. It is called by name with arguments: area(5, 3). The return statement sends a value back; without it, the function returns undefined. Parameters may have default values: function greet(name = "Guest"). Functions declared this way are hoisted*, so they can be called before they appear in the code.
Definition: Function. A reusable block of code, defined once with a name and parameters, that performs a task and may return a value when it is called with arguments.
Function Expressions and Arrow Functions
A function can be stored in a variable, as a function expression: const square = function (x) { return x x; };. Arrow functions (ES6) give a short form: const square = x => x x;. With one expression, the result is returned automatically. Arrow functions are widely used as callbacks, functions passed to other functions, such as event handlers and array methods.
Scope
A variable declared inside a function is local to it. One declared outside all functions is global and visible everywhere. With let and const, a variable declared in a block {} is visible only in that block. Too many global variables cause name clashes, so code is kept inside functions.
Built-in Functions
JavaScript provides global functions such as parseInt(), parseFloat(), Number(), isNaN(), setTimeout() (run a function once after a delay) and setInterval() (run it repeatedly). The Math object gives Math.round(), Math.floor(), Math.ceil(), Math.max(), Math.min(), Math.sqrt(), Math.pow() and Math.random().
A Simple Calculator
Functions are the natural way to organise a calculator: one function for each operation, and one that chooses the operation and handles division by zero.
Table 3.3: Ways to write functions
| Form | Example | Note |
|---|---|---|
| Declaration | function add(a, b) { return a + b; } | Hoisted |
| Expression | const add = function (a, b) { ... }; | Not hoisted |
| Arrow | const add = (a, b) => a + b; | Short, used as callbacks |
Example 3.3: A calculator function
Problem: Write a function calculate(a, b, op) that adds, subtracts, multiplies or divides according to op, using switch, and reports division by zero.
Solution:
- Use switch (op) with cases "+", "-", "*" and "/".
- In the "/" case, check b === 0 and return an error message.
- Return the result of the chosen operation.
Result: calculate(12, 4, "/") gives 3, and calculate(5, 0, "/") reports an error.
function calculate(a, b, op) {
switch (op) {
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/": return b === 0 ? "Error: division by zero" : a / b;
default: return "Unknown operator";
}
}
const square = x => x * x;
for (const op of ["+", "-", "*", "/"])
console.log(`12 ${op} 4 =`, calculate(12, 4, op));
console.log("5 / 0 =", calculate(5, 0, "/"));
console.log("square(9) =", square(9), " max:", Math.max(3, 17, 8));
Output
12 + 4 = 16
12 - 4 = 8
12 * 4 = 48
12 / 4 = 3
5 / 0 = Error: division by zero
square(9) = 81 max: 17
Common mistakes
- Forgetting return, so that the function gives undefined.
- Confusing parameters (in the definition) with arguments (in the call).
- Calling a function expression before the line where it is defined.
Key takeaways
- Functions are declared with function or written as arrow functions.
- Parameters receive arguments; return sends back a value.
- Variables inside a function are local.
- Math and global functions give ready tools.
Practice questions
- What is an arrow function?
- What does a function return if it has no return statement?
- What is a callback?
Answers to the practice questions
- A short form of function expression, such as const sq = x => x * x;.
- undefined.
- A function passed to another function to be called later.
Sources
- Official BCA syllabus Web Technologies, course code 25BCA402SEC02, Unit III
