📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    Consider the following code:     let data = [1,

    2, 3];     function modifyArray(arr) {         arr.push(4);         arr = [5, 6]; // Reassigns local 'arr'         return arr;     }     let result = modifyArray(data);     console.log(data);     console.log(result);     What will be the output?
    A [1, 2, 3] and [5, 6] Correct Answer Incorrect Answer
    B [1, 2, 3, 4] and [5, 6] Correct Answer Incorrect Answer
    C [1, 2, 3, 4] and [1, 2, 3, 4] Correct Answer Incorrect Answer
    D [5, 6] and [5, 6] Correct Answer Incorrect Answer
    E [1, 2, 3] and [1, 2, 3, 4] Correct Answer Incorrect Answer

    Solution

    1.  data is [1, 2, 3].     2.  modifyArray(data) is called. arr inside the function initially refers to the same array as data.     3.  arr.push(4) modifies the original array that data also points to. So, data is now [1, 2, 3, 4].     4.  arr = [5, 6] reassigns the local variable arr to a  new array [5, 6]. This does not affect the data variable in the global scope.     5.  The function returns the new array [5, 6], which is assigned to result.     Therefore, data is [1, 2, 3, 4] and result is [5, 6].

    Practice Next
    More IT Operating System Questions
    ask-question