3 ms·
At first I thought maybe this was showing that I'm way less good at JS than I thought I was. But after thinking about it some more, I'm still fine at JS. All my
by onychomys 2y ago
At first I thought maybe this was showing that I'm way less good at JS than I thought I was. But after thinking about it some more, I'm still fine at JS. All my sites work just fine. My clients are seemingly happy with them and I get paid for it. Instead, I'm just not good at the weird edge cases that nobody actually ever hits, which is what all these questions are!
(that being said, I do roll my eyes every time I have to clear out an array by doing myarray.length = 0 instead of myarray = []. JS is such a silly language sometimes.)
- Stratoscope 2y ago> I do roll my eyes every time I have to clear out an array by doing myarray.length = 0 instead of myarray = []. JS is such a silly language sometimes. In your example, if myarray was the only reference to your array, it would likely not matter which way you do it. Clear the original array, or reassign the variable to point to a new empty array. It becomes important when you have another reference to the same array. That's not just a JavaScript thing. Any language where [] creates a new array/list, and the = operator copies a reference will have the same behavior. Take Python for example: >>> a = [3,2,1] >>> b = a >>> a [3, 2, 1] >>> b [3, 2, 1] >>> a = [] >>> a [] >>> b [3, 2, 1] >>> >>> a = [3,2,1] >>> b = a >>> a [3, 2, 1] >>> b [3, 2, 1] >>> a.clear() >>> a [] >>> b [] >>> Or Ruby: irb(main):001:0> a = [3,2,1] => [3, 2, 1] irb(main):002:0> b = a => [3, 2, 1] irb(main):003:0> a => [3, 2, 1] irb(main):004:0> b => [3, 2, 1] irb(main):005:0> a = [] => [] irb(main):006:0> a => [] irb(main):007:0> b => [3, 2, 1] irb(main):008:0> irb(main):009:0> a = [3,2,1] => [3, 2, 1] irb(main):010:0> b = a => [3, 2, 1] irb(main):011:0> a => [3, 2, 1] irb(main):012:0> b => [3, 2, 1] irb(main):013:0> a.clear() => [] irb(main):014:0> a => [] irb(main):015:0> b => [] irb(main):016:0> And JavaScript to compare with the other two: > a = [3,2,1] (3) [3, 2, 1] > b = a (3) [3, 2, 1] > a = [] [] > a [] > b (3) [3, 2, 1] > a = [3,2,1] (3) [3, 2, 1] > b = a (3) [3, 2, 1] > a.length = 0 0 > a [] > b [] Python and Ruby do have that nice clear() method instead of having to set .length to 0, but the underlying semantics are the same in all three languages.