How to empty an array in JavaScript?

Four methods on how to empty an array in JavaScript with code examples
27 September 2017   2274

We've made a research and found out 4 different methods that will help you to empty an array in JavaScript.

As example, we will use array A = [1,2,3,4]; 

Method 1

A = [];

This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged.

Method 2

A.length = 0

This will clear the existing array by setting its length to 0. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.

Method 3

A.splice(0,A.length)

Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.

Method 4 

while(A.length > 0) {
    A.pop();
}

 

Frontend News Digest 3 -9.08

Learn this week's latest news and updates of JavaScript, CSS, PHP and related technologies
08 August 2019   577

Greetings! I hope your week went great! Here's new Frontend news digest.

In this digest, you will learn how to improve your procedural code, how to deploy apps to to IBM cloud with Tekton, how to use Immer to manage your React state and much more!

Guides

  • Trigger Firebase Storage Image Resize with Cloud Functions

Tutorial on creating an imager resizer triggered by Firebase Storage

  • Using pipe and compose to improve procedural code

According to the creator, this guide will sohw you how to use pipe and compose to improve the way we write procedural code.

  • Deploying Applications to IBM Cloud Kubernetes via Tekton

This article talks about Tekton, an open-source framework for creating CI/CD systems, and explains how to deploy and use it on the IBM Cloud Kubernetes service

  • Quick Gulp Cache Busting

This tips will allow you to improve your work with Gulp

  • Using Immer for React State Management

Learn how Immer can help you to operate React states

Article

  • Laravel Cloud Source Code on GitHub

Author believes that is a chance to get a glimpse of an application written by the creator of Laravel

Updates

  • Calendario

Library allowing to create flexible calendars

  • Symphony

According to the creators, 113 pull requests were merged (79 in code and 34 in docs) and 55 issues were closed (43 in code and 12 in docs)

Video

  • The Date Object - Getting, Setting & Formatting Dates in JavaScript - Tutorial

  • Simple Slide Show in JavaScript | JavaScript exercises