0

I am currently writing a libary of sorting algorithms. I have noticed that inorder for my code to not break, I need to make all values immutable if they are being used by another function. Such as this:

function quickSort(randomArray) {
    if(randomArray!=undefined&&randomArray.length > 1){
        const partitionValue = randomArray.pop()
        const halves = getHalves(partitionValue,randomArray)
        return mergeArrays(quickSort(halves[0]),partitionValue,quickSort(halves[1]))
    }
    return randomArray
}

The none working code is as follows:

function quickSort(randomArray) {
    if(randomArray!=undefined&&randomArray.length > 1){
        partitionValue = randomArray.pop()
        halves = getHalves(partitionValue,randomArray)
        return mergeArrays(quickSort(halves[0]),partitionValue,quickSort(halves[1]))
    }
    return randomArray
}

The script does not throw an error with no tag, or with a "var" tag.

The code breaks if I declared either "partitionValue" or "halves" without the const tag. This is confusing to me. A quick google search tells me that javascript functions are pass by value. And the two variables mentioned are not being modified in any way later on. Why do I need to declare it as immutable if its not being changed?

  • Always use strict mode to avoid these sorts of bugs. You're creating global variables, shared among all calls of `quickSort` – CertainPerformance Apr 18 '20 at 02:35
  • Ah, I didn't know that. As a curiosity, is there a way to make a call specific variable but have it mutable? basically declaring the two variables such that I can still modify it in the future. – Thomas Shih Apr 18 '20 at 02:37
  • Non-primitives can almost always be mutated regardless. Primitives can never be mutated regardless. If you want to allow *reassignment*, which is something completely different, use `let` instead of `const` – CertainPerformance Apr 18 '20 at 02:39

0 Answers0