- Primitve parameters (numbers, strings, ...) are passed by value
-
<script type="text/javascript">
function DontChange(x) {
console.log("In DontChange(x), x = ", x);
x = "dog";
console.log("In DontChange after assignemt, x = ", x);
return;
}
let param = "hello";
console.log("param = ", param);
console.log("Calling DontChange(param)");
DontChange(param);
console.log("param = ", param);
param = 4;
console.log("param = ", param);
console.log("Calling DontChange(param)");
DontChange(param);
console.log("param = ", param);
</script>
- objects are passed by reference.
-
<script type="text/javascript">
function Change(x){
console.log("In Change(x), x = ", x);
x[1] = "dog";
console.log("In Change after assignemt, x = ", x);
return;
}
let param2 = [1,2,3];
console.log("param2 = ", param2);
console.log("Calling DontChange(param2)");
Change(param2);
console.log("param2 = ", param2);
</script>
- It is easy to pass functions as parameters
function Square(x) {
console.log("In Square");
return x * x;
}
function Twice(x) {
console.log("In Twice");
return x + x;
}
function RunFunc(x,y){
console.log("In RunFunc");
return x(y);
}
console.log(Square(4));
console.log(Twice(4));
console.log(RunFunc(Square, 4));
console.log(RunFunc(Twice, 4));