Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.
Three ways to define a function — pick by hoisting and this
PHP named functions, anonymous closures, and PHP 7.4 arrow functions map cleanly to JavaScript declarations, expressions, and arrows.
PHP habit
<?php
function greet(string $name): string {
return "Hello, $name";
}
$multiply = function (int $a, int $b): int {
return $a * $b;
};
$double = fn(int $n) => $n * 2;
JavaScript equivalent
function greet(name) {
return `Hello, ${name}`;
}
const multiply = function (a, b) {
return a * b;
};
const double = (n) => n * 2;
| Form | Hoisted? | Typical use |
|---|---|---|
function name() {} |
Yes | Top-level helpers, utilities |
const fn = function() {} |
No | Assign to variable, pass as value |
const fn = () => {} |
No | Callbacks, short transforms |
Hoisting in practice
console.log(add(2, 3)); // 5 — declaration exists before its line
function add(a, b) {
return a + b;
}
// console.log(multiply(2, 3)); // ReferenceError
const multiply = (a, b) => a * b;
Declarations behave like PHP functions defined in a file before use. Expressions and arrows follow const rules — define before call.
Arrow bodies: expression vs block
const square = (n) => n * n;
const clamp = (value, min, max) => {
if (value < min) return min;
if (value > max) return max;
return value;
};
One expression after => returns automatically. Use { } when you need multiple statements.
this preview — arrows inherit, functions bind
Arrow functions do not get their own this. Regular functions do. That matters for object methods and DOM handlers later; for now, default to arrows in callbacks and declarations for named top-level functions.
Try it
Use the amber Try it panel below. Click Run.
function formatPrice(amount, currency = 'GBP') {
return new Intl.NumberFormat('en-GB', { style: 'currency', currency }).format(amount);
}
const applyDiscount = (price, percent) => price * (1 - percent / 100);
console.log(formatPrice(49.99));
console.log(applyDiscount(100, 10));
Same layering you use in PHP: a named function for a clear entry point, a short closure for a one-off transform.
From PHP to JavaScript — JavaScript Syntax Foundations for PHP Devs