Search code examples
javascriptarraysscopeglobal-variables

How to modify a global variable inside a function in javascript, i.e. modify variable in-place


So, below you can find my (very basic and unoptimized) solution to Leetcode's challenge 189 'Rotate Array'. The target of this challenge is posed as follows: Given an array, rotate the array to the right by k steps, where k is non-negative.

Now, my solution is not accepted as somehow the global variable nums remains unchanged after the function call. Why is that? Somehow nums is treated as local variable and doesn't change the passed-in global variable nums. I get that it's probably because of how javascript treats variable scopes but I don't seem to find resources that can help me understand this example.

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
    array2 = Array.from(nums)
    nums.map((num) => {
        array2[(nums.indexOf(num)+k)%nums.length] = num
    })
    nums = Array.from(array2)
    console.log(nums) // returns expected answer
};
Your input
[1,2,3,4,5,6,7]
3

Your stdout
[5,6,7,1,2,3,4]

Your answer
[1,2,3,4,5,6,7]

Expected answer
[5,6,7,1,2,3,4]


Solution

  • The map function does not modify the original array. Additionally, you seem to be using it incorrectly.

    You are using map to set the values of array2 and then setting nums to a copy of array2. This will not modify the original object contained in nums.

    Of course, if you log nums within the function, it will give you the updated value, but this value is scoped within the function and won't be accessible outside.

    Instead of array methods, for this type of impure programming, you should use a for loop.

    var rotate = function(nums, k) {
        array2 = Array.from(nums);
        for (const i in nums) nums[i] = array2[(i+k)%nums.length];
    };