0

I am a javascript beginner and I would like to create a function named swap that swaps the variables that were passed in:

function swap(a, b){
    var t = a;
    a = b;
    b = t;
}
var x = 3;
var y = 4;
swap (x, y);
console.log(x + " " + y);

and the output should be 4 3

but I can't figure out how to make this function work, because in C++ we would just pass the reference swap(&a, &b). How to pass reference in JS?

Pranjal
  • 5
  • 2
Seikomega
  • 1
  • 1
  • 4
    Since you can't pass a reference to the variables in: no. – Quentin Jan 27 '21 at 10:50
  • 1
    no, you can't, because there is no eqivalent for the `&` in `swap(&a, &b)` – Thomas Jan 27 '21 at 10:50
  • C and javascript have different architecture. You should understand callback in javascript. C runs commands one by one. But javascript runs codes in bulk mode. The result can be caught by callback. Or you can use async and await mode in javascript. –  Jan 27 '21 at 10:57
  • function swap(a, b, callback){ var t = a; a = b; b = t; callback(a, b); } var x = 3; var y = 4; swap (x, y, function(x, y){ console.log(x + " " + y); }) –  Jan 27 '21 at 11:02

0 Answers0