4 ms·
I'm actually pretty fond of JavaScript, but here's a question that has caught me out in real code: const x = [1, 10, 2], y = x.sort(); Now: w
by gmac 5y ago
I'm actually pretty fond of JavaScript, but here's a question that has caught me out in real code:
const
x = [1, 10, 2],
y = x.sort();
Now: what is the value of x? (Edit: and y?)
- tinco 5y agoI've been using JavaScript for around 15 years, and I've never used a comma to separate expressions. And I'd still go to MDN to look up if sort() is in place or not :p
- gmac 5y agoThe comma is not material here: the answer is the same if we write `const x = ...; const y = ...`. And that's the first gotcha: sort() is in place.
- dahart 5y agoPretty sure I’ve actually tripped on sort() myself before by assuming it was a new array. It does make sense for performance though, creating a new array would be a bad default choice for performance, for the same reasons that forEach is generally faster than map all else being equal.
- gmac 5y agoTrue. I like Ruby's solution with exclamation marks, such as `sort!`, to make this kind of behaviour obvious.
- zodiakzz 5y agoIn JavaScript every possible value has a .toString() representation* so it makes the most sense that the untyped/mixed array .sort() does lexicographic sorting. If you need numeric sort, use a TypedArray or provide an explicit arrow function. * Except Object.create(null), which throws.
- gmac 5y agoYes, .sort((a, b) => b - a) is what I meant in this case. I think perhaps this "makes the most sense" from a language designer/implementor's perspective, but it also gives ample opportunity for WTF moments in actual use.
- colmvp 5y agoIs the y relevant? Sort is in place and without a comparator function, it's going to convert the numbers to strings, so the array will remain the same. If the question is about const, const with Arrays/Objects are by reference rather than value, nothing is stopping them from being modified later in the code.