Primitive and Non-Primitive (Object) Data Types:
-
JavaScript:
- Primitive Data Types: Number, String, Boolean, Null, Undefined, Symbol (added in ECMAScript 6).
- Object Data Type: Objects (including arrays and functions) are non-primitive.
-
PHP:
- Primitive Data Types: Integer, Float, String, Boolean, Null.
- Object Data Type: Objects (created from classes or built-in classes like stdClass).
Pass by Value vs. Pass by Reference:
-
JavaScript:
- Primitive Types: Passed by value. Changes inside a function do not affect the original value.
- Objects (Non-Primitive): Passed by reference. Changes inside a function affect the original object.
-
PHP:
- Primitive Types: Passed by value.
- Objects (Non-Primitive): Passed by reference. Changes inside a function affect the original object.
Comparison - JavaScript vs. PHP:
-
JavaScript:
- Syntax Example:
let primitiveValue = 5; let objectValue = { key: 'value' }; function modifyValues(a, b) { a = 10; b.key = 'modified'; } modifyValues(primitiveValue, objectValue); console.log(primitiveValue); // Output: 5 console.log(objectValue.key); // Output: 'modified'
-
PHP:
- Syntax Example:
$primitiveValue = 5; $objectValue = (object)['key' => 'value']; function modifyValues($a, $b) { $a = 10; $b->key = 'modified'; } modifyValues($primitiveValue, $objectValue); echo $primitiveValue; // Output: 5 echo $objectValue->key; // Output: 'modified'
In both languages, primitive types are passed by value, and objects (non-primitive) are passed by reference. The behavior ensures that changes made to objects inside a function are reflected outside the function.
Note: While objects in JavaScript are always passed by reference, primitive types are immutable, meaning their values cannot be changed. In PHP, it's possible to explicitly pass a variable by reference using the &
symbol in the function parameter list.
Top comments (0)