JavaScript question

what is the output of this code?

function doIt(param) {
param = 2;
}

var test = 1;
doIt(test);
console.log(test);

I’m learning about pass-by-value and I think its either two or twenty-one. Can someone let me know the correct answer. If it’s not one of the answers I have, could you explain?

Oh okay, that makes sense. Thanks!

should it not be console.log(dolt(test));

Also I wanted to point out that your doIt function does not return any value.

function doIt(param) {
param = 2;
}

var test = 1;
doIt(test);
console.log(test);

You are passing test(which has value of 1) into the function, the function is doing some work but not returning any value, and then you are printing test(still has the value of 1 as it was not changed) to the console.

1 Like

I believe the return is implicit, the javascript function returns the result of the last statement, in this case param = 2, or just return = 2.

EDIT:: I looked it up and it seems it with actually return “undefined” if no return statement is provided. I was thinking of Ruby which returns the result of the last statement executed in a function if no Return is explicitly provided. Hard to keep some details straight between different languages…

yeah that seem’s like a good idea as you would probably want to return the result of the function you just called.

but in this case you would get the result ‘undefined’ as the doIt function does not return any vaue.

1 Like

you were too fast for me! LOL

1 Like