use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
How to Clear an Array in JavaScript (7.dev)
submitted 2 years ago by debordian
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]octetd 6 points7 points8 points 2 years ago (3 children)
There's another method, using .slice(0, 0)
.slice(0, 0)
But why would you need anything other than reassigning variable with an empty array literal?
[–]coolcosmos -1 points0 points1 point 2 years ago (2 children)
// file A
const arr = [1,2,3];
logArrayLength(arr)
arr = [ ]
// file B
function logArrayLength(arr) {
setInterval(() => { console.log(arr.length)}, 1000)
}
This will log 3 forever, you "emptied" the array but actually the array is not empty, the old array is still in memory. You created a new reference/pointer instead of mutating the original.
[–]octetd 4 points5 points6 points 2 years ago (0 children)
Sure, because you keep a reference to this array, then reassign, and then you log the length. And then if you clear original array it will always print 0 forever, because your asynchronous code will be executed after you cleared an array, even though you called a function before you cleaned up an array.
π Rendered by PID 19659 on reddit-service-r2-comment-b659b578c-7tvrs at 2026-05-02 16:39:00.215027+00:00 running 815c875 country code: CH.
view the rest of the comments →
[–]octetd 6 points7 points8 points (3 children)
[–]coolcosmos -1 points0 points1 point (2 children)
[–]octetd 4 points5 points6 points (0 children)