-3

So heres my code,how are variables being updated as it is not working.What am i doing here?

var myNum = 0;

function upVar(eletoup) 
{

    this.eletoup = eletoup;

    this.updateValue=function updateValue(newValue) {
        this.eletoup += newValue;
    }}

upVar(myNum).updateValue(1000);

console.log(myNum)

Any help would be appreciated

Mohhamad Hasham
  • 1,750
  • 1
  • 15
  • 18
Ayad Hussein
  • 11
  • 1
  • 2

1 Answers1

1

JavaScript is pass-by-value. That means that when you do this:

upVar(myNum).updateValue(1000);

upVar receives the value that myNum contains at that moment, not some kind of reference to myNum. There is nothing that upVar can do with the parameter it receives that value in (eletoup) that will change the value of the upVar variable. There's simply no connection between them at all.

Instead, the usual thing to do is to have a function that needs to provide an updated value return the value, and have the call receive the update from the function. Simpler example:

function updateValue(value, update) {
    return value + update;
}
var myNum = 0;
myNum = updateValue(myNum, 1000);
console.log(myNum);
myNum = updateValue(myNum, 1000);
console.log(myNum);

You seem to want to use an object in your code, though. Note that the this value that upVar receives when you call it the way you are will be the default this value. In "loose" (aka "sloppy") mode, that default value is a reference to the global object (also available as window on browsers). In "strict" mode, it's undefined.

You can certainly create an object, initialize a property on it from myNum, and then update that property. Here's one way to do that:

function upVar(initialValue) {
    return {
        value: initialValue,
        updateValue: function(update) {
            this.value += update;
        }
    };
}

var myNum = 0;
var obj = upVar(myNum);
obj.updateValue(1000);
console.log("obj.value", obj.value);
obj.updateValue(1000);
console.log("obj.value", obj.value);

// Note that myNum isn't changed
console.log("myNum", myNum);

There are situations where functions can update variables not by receiving them as parameters, but because they close over the variable. Those functions are called "closures."

I suggest working through some basic JavaScript tutorials and/or a solid "Beginning JavaScript" book to get a good foundation in how the language works.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875