Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.

Prefer returning new data over silently changing outer state

PHP services often return a result or mutate an object you pass in. JavaScript favours return values and immutable-style updates — especially with const bindings.

PHP habit: return vs in-place change

<?php
function withDiscount(float $price, float $percent): float {
    return $price * (1 - $percent / 100);
}

function addTag(array &$order, string $tag): void {
    $order['tags'][] = $tag;
}

$order = ['tags' => ['new']];
addTag($order, 'priority');

JavaScript equivalent

function withDiscount(price, percent) {
  return price * (1 - percent / 100);
}

function addTag(order, tag) {
  return { ...order, tags: [...order.tags, tag] };
}

const order = { tags: ['new'] };
const updated = addTag(order, 'priority');
PHP style JavaScript style Why
return $x return x Same — preferred for transforms
function f(array &$a) Return { ...a, key: val } Easier to trace data flow
Mutate shared object Mutate only when intentional Fewer surprise side effects

const does not mean immutable insides

const cart = { items: [] };
cart.items.push('book');     // allowed
// cart = {};                // TypeError — cannot reassign binding

Returning a new object avoids accidental shared mutation between callers.

When mutation is fine

Updating a DOM node, appending to a logger buffer, or pushing to an array you own inside one function — mutation is normal. The smell is a function that changes outer variables you did not pass in explicitly.

Try it

Use the amber Try it panel below. Click Run.

const base = { total: 100, tags: ['draft'] };

const priced = { ...base, total: withDiscount(base.total, 10) };
const tagged = addTag(priced, 'ready');

console.log('original tags', base.tags);
console.log('updated', tagged);

Original stays ['draft']; updated object has ready. That separation is the habit to practice.

From PHP to JavaScript — Control Flow, Functions, and Scope