Make a parameter change the value of the variable with pointer

Asked

Viewed 210 times

2

It is possible to work with pointers in JS, if yes, how do I do this?

In the example below the goal is to make the variable str stay with the value: "worked :D"

var str = "teste";

function ponteiro(texto){
   texto = "funcionou :D"
}

ponteiro(str);
  • just have to say that str = "funcionou :D"

1 answer

5


I imagine you are talking about pointer or reference, that is, you want to be able to change the variable within the function and the value is reflected in the original variable used as argument of the function. This is not possible directly in JS and in general it doesn’t make sense something like this because you can return this value in the function and then change the value in the calling function:

function apontador(texto) {
   return "funcionou :D";
}
var str = "teste";
str = apontador(str);
console.log(str);

If you have to return more than one thing and so are wanting to do something of the kind then the ideal would be to return more than one data encapsulated in an object:

function apontador(texto) {
   return ["funcionou :D", "Outro texto " + texto];
}
var str = "teste";
var objeto = apontador(str);
console.log(objeto[0]);

You could use a name on array instead of using the numeric index if you think it’s important.

If you still want to insist on this, you can encapsulate the variable in an object that is by reference and then get the result you want:

function apontador(objeto) {
   objeto[0] = "funcionou :D";
}
var str = "teste";
var objeto = [str];
apontador(objeto);
console.log(objeto[0]);

I put in the Github for future reference.

Again, unnecessary.

Technically a string is a reference, but it has value semantics so it does not do what it expects automatically, it needs an auxiliary structure by Javascript not to have a syntax that gives the reference semantics in a natural way.

  • Thank you Maniero for the reply! I’m looking to better understand the functioning of the pointers to be able to apply to another function I’m creating, in this other one it makes more sense to use yes :D pointers

  • JS has no apparent pointers so you can’t learn to use pointer in JS.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.