JS Functions
A function is a reusable block of code. Three syntaxes get you almost everywhere: declarations, expressions, and arrow functions.
Three flavours
JS
// 1. Function declaration — hoisted, can be called above its definition
function greet(name) {
return `Hello, ${name}!`;
}
// 2. Function expression — assigned to a variable
const greet2 = function (name) {
return `Hello, ${name}!`;
};
// 3. Arrow function — concise, no own `this`
const greet3 = (name) => `Hello, ${name}!`;
Differences worth knowing
| Declaration | Arrow | |
|---|---|---|
| Hoisted? | Yes — full hoisting | No — only the variable name |
Own this? | Yes | No — inherits from enclosing scope |
Own arguments? | Yes | No |
| Usable as constructor? | Yes (new) | No |
| Best for | Top-level reusable functions | Callbacks, one-liners, methods that don't need their own this |
Parameters
JS
// Default values
function multiply(a, b = 1) { return a * b; }
// Rest parameters — collect remaining args into an array
function sum(...nums) { return nums.reduce((t, n) => t + n, 0); }
// Destructuring — pull values out of an object
function order({ id, qty = 1, gift = false }) { /* … */ }
Tip: Default to arrow functions for callbacks (
map, filter, event handlers). Use function declarations at the top level when you want hoisting or self-references via the name.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
function add(a, b) { return a + b; }
document.getElementById("out").textContent = "2 + 3 = " + add(2, 3);
</script>
</body>
</html>
Try it Yourself »
Exercise
Write an arrow function that doubles a number.
const double = (n)
n * 2;
The arrow itself — two characters.
Discussion
Loading…