0

I need a way to pass a variable to a function and then add to that variable inside of the function. Here's an example of what I need:

let x = 0;

function addTo(num1, num2) {
  num1 += num2;
}

addTo(x, 5); // I want this function to add 5 to x
console.log(x); // should log 5 in the console

Here's another example of what I want to achieve in C++ code:

#include <iostream>

void addTo(int& num1, int num2) {
  num1 += num2;
}

int main() {
  int x = 0;

  addTo(x, 5);
  std::cout << x << std::endl; // outputs 5
}
2
  • JavaScript does not have pass-by-reference like C++. Either mutate an object, or return the result with return, for the caller to process. Commented Jul 7, 2023 at 22:07
  • You need use something like this. Commented Jul 7, 2023 at 22:10

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.