Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers in JavaScript?

Tags:

javascript

Can we pass a reference of a variable that is immutable as argument in a function?

Example:

var x = 0; function a(x) {     x++; } a(x); alert(x); //Here I want to have 1 instead of 0 
like image 640
user1342369 Avatar asked Apr 19 '12 15:04

user1342369


People also ask

Are there pointers in JavaScript?

I bet you didn't know that Javascript has pointers. Well, it does! Let's take a quick look at how they are implemented and how they work. We will also talk about possible reasons why pointers in Javascript are the way they are.

Why pointers are not used in JavaScript?

TL;DR: There are NO pointers in JavaScript and references work differently from what we would normally see in most other popular programming languages. In JavaScript, it's just NOT possible to have a reference from one variable to another variable. And, only compound values (Object, Array) can be assigned by reference.

What is the pointer used for?

Pointers are used extensively in both C and C++ for three main purposes: to allocate new objects on the heap, to pass functions to other functions. to iterate over elements in arrays or other data structures.

What are pointers in code?

A pointer is a variable that stores the memory address of another variable as its value. A pointer variable points to a data type (like int ) of the same type, and is created with the * operator.


2 Answers

Since JavaScript does not support passing parameters by reference, you'll need to make the variable an object instead:

var x = {Value: 0};    function a(obj)  {      obj.Value++;  }    a(x);  document.write(x.Value); //Here i want to have 1 instead of 0

In this case, x is a reference to an object. When x is passed to the function a, that reference is copied over to obj. Thus, obj and x refer to the same thing in memory. Changing the Value property of obj affects the Value property of x.

Javascript will always pass function parameters by value. That's simply a specification of the language. You could create x in a scope local to both functions, and not pass the variable at all.

like image 78
Mike Christensen Avatar answered Oct 03 '22 05:10

Mike Christensen


This question may help: How to pass variable by reference in javascript? Read data from ActiveX function which returns more than one value

To summarise, Javascript primitive types are always passed by value, whereas the values inside objects are passed by reference (thanks to commenters for pointing out my oversight). So to get round this, you have to put your integer inside an object:

var myobj = {x:0};    function a(obj)  {      obj.x++;  }    a(myobj);  alert(myobj.x); // returns 1      
like image 21
n00dle Avatar answered Oct 03 '22 03:10

n00dle