iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

DeclarationArrow
Hoisted?Yes — full hoistingNo — only the variable name
Own this?YesNo — inherits from enclosing scope
Own arguments?YesNo
Usable as constructor?Yes (new)No
Best forTop-level reusable functionsCallbacks, 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;

Test yourself

Q1. Which form is hoisted (can be called above its definition)?
Q2. Arrow functions differ from regular functions because they…
Q3. Collect remaining arguments with…

Discussion

Loading…