

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Is JavaScript a pass-by-reference or pass-by-value language?
Javascript is a pass by value language. But for objects, the value is their reference. So for example, if you pass an int to a function as parameter and increment its value in the function, its value will not be updated in the caller's context −
Example
let i = 0; function increment(x) { x = x + 1 console.log(x) } increment(i) console.log(i)
Output
1 0
When you pass an object and update that object's reference in the function's context, that won't affect the object. But if you mutate the object's internals, that'll reflect in the object.
Example
let obj = {'foo': 'bar'}; function updateRef(x) { // x's local ref gets updates, doesn't affect obj x = {} } function addHelloWorld(y) { // Add new prop to object referenced by y y['hello'] = 'world'; } console.log(obj) updateRef(obj) console.log(obj) addHelloWorld(obj) console.log(obj)
Output
{ foo: 'bar' } { foo: 'bar' } { foo: 'bar', hello: 'world' }
Note that the object reference change did not affect the object. The local variable x was reassigned. In second function however, y was referencing the obj object and mutated the internal state of that object. This caused the change in the original object.
- Related Questions & Answers
- Is java pass by reference or pass by value?
- Describe pass by value and pass by reference in JavaScript?
- Pass by reference vs Pass by Value in java
- What is Pass By Reference and Pass By Value in PHP?
- Which one is better in between pass by value or pass by reference in C++?
- What is pass by reference in C language?
- Differences between pass by value and pass by reference in C++
- Pass by reference vs value in Python
- Explain javascript pass by reference in javascript?
- What is pass by value in C language?
- Explain javascript pass by value in javascript?
- Pass an integer by reference in Java
- How is Java strictly pass by value?
- What is the difference between pass by value and reference parameters in C#?
- How to pass arguments by reference in a Python function?
Advertisements