Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.
Defaults and rest collect what callers pass in
PHP and JavaScript both let you define default parameter values and gather extra arguments. The ... token does two jobs: rest in a parameter list, spread when calling or building arrays.
PHP habit
<?php
function greet(string $name = 'Guest'): string {
return "Hello, $name";
}
function sum(int ...$numbers): int {
return array_sum($numbers);
}
$values = [1, 5, 3];
echo max(...$values);
JavaScript equivalent
function greet(name = 'Guest') {
return `Hello, ${name}`;
}
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
const values = [1, 5, 3];
console.log(Math.max(...values));
Where you write ... |
Name | PHP parallel |
|---|---|---|
| Last parameter | Rest | function f(int ...$args) |
| In a function call | Spread | max(...$nums) |
In [...a, x] or {...obj} |
Spread | array_merge, merged arrays |
Defaults: undefined vs null
function tag(label, value = 'unknown') {
return `${label}: ${value}`;
}
console.log(tag('name', undefined)); // uses default
console.log(tag('name', null)); // keeps null
PHP defaults behave similarly for null passed explicitly.
Rest must be last
function log(level, ...messages) {
for (const msg of messages) {
console.log(`[${level}]`, msg);
}
}
Same rule as PHP variadic parameters at the end of the list.
Try it
Use the amber Try it panel below. Click Run.
function buildLabel(prefix, ...parts) {
return [prefix, ...parts].filter(Boolean).join(' · ');
}
console.log(greet());
console.log(sum(1, 2, 3, 4));
console.log(buildLabel('Order', 'paid', 'shipped'));
You should see a default greeting, 10, and a joined label string.
From PHP to JavaScript — Control Flow, Functions, and Scope