JS-Dev-101 practice question 21 of 25

Refer to the code below: 01 function changeValue(param) { 02 param = 5; 03 } 04 let a = 10; 05 let b = a; 06 07 changeValue(b); 08 const result = a + ' - ' + b; What is the value of result when the code executes?

Full set: 148 questions
Answer options
A: 5-5
B: 5-10
C: 10-5
D: 10-10 Correct answer
Correct Answer:
D. 10-10
Explanation

JavaScript passes primitive types, such as Number, by value. When changeValue(b) is called, a copy of the value of b (which is 10) is passed to the function's param parameter. Inside the function, only this local copy (param) is reassigned to 5. The original variable b in the outer scope remains unchanged and its value is still 10. Consequently, the result is the concatenation of a (10), the string ' - ', and b (10), resulting in "10 - 10".

Why Incorrect

A. This assumes both a and b were changed to 5, which is incorrect. a was never modified, and b was not changed by the function.
B. This assumes a was changed to 5 and b remained 10. a was never passed to the function.
C. This assumes b was changed to 5. The function only changes its local parameter, not the original variable b, due to pass-by-value.

References

1. Mozilla Developer Network (MDN). (2023). Functions - Function parameters. "Primitive parameters (such as a number) are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function."

2. University of California, Berkeley, CS 61A. Lecture 6: Higher-Order Functions. Course materials often cover the distinction between pass-by-value (for primitives) and pass-by-reference (for objects) in languages like JavaScript.

3. Salesforce Lightning Web Components Dev Guide. Pass Data Between Components. While discussing component communication, the guide relies on the fundamental JavaScript principle of passing primitive data by value.

Scroll to Top