How to verify for an empty array within a condition in JavaScript

I can't figure out why my conditional statement to handle the edge case of an empty input array is not working as expected. When I test it with my current example, it returns NaN (no clue why). However, if I change the conditional to if (array.length === 0), then my code works perfectly. But shouldn't [] be the correct way to represent an empty array?

function getAvg(array) {
  if (array === []) {
    return 0;
  }
  var sum     = 0;
  var average = 0;
  var length  = array.length;
  for (var i  = 0; i < length; i++) {
      sum += array[i];
  }
  average = sum / length;
  return average
}

var input  = [];
var result = getAvg(input);

console.log('should be 0:', result);

Answer №1

To determine if the array has a length greater than zero, you can use the following code:

 if(arr.length>0){}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting a JSON array into a single JSON object using Powershell

I need assistance converting a JSON array into a single JSON Object. I have provided the output screenshot for reference: https://i.sstatic.net/vT55z.png My desired output is shown in this screenshot: https://i.sstatic.net/rL8Yp.png This is the PowerShel ...

What is the best method for obtaining user data when additional custom data is stored in Cloud Firestore?

Storing the user's information such as email, name, age, phone number, and uid is essential. In the user.model.ts file: export interface User { uid: string, name: string, email: string, phoneNumber: string, age: string } In auth. ...

Is there any HTML code that is able to implement a currency format identical to the one we've customized in Google Sheets/Google Apps Script

I am currently working with a Google Sheet table that consists of 2 columns. The second column contains charges which can vary based on user input through a Google Form and are summed up using GAS. To view an example, click here. The data from this Googl ...

Tips on concealing and deactivating the fullscreen option in flowplayer

Could someone please assist me in resolving this issue? I've been attempting to hide the fullscreen button from the flowplayer, but so far, I haven't found a solution. Below is my JavaScript code: <script> $f("player", "flowplayer/flowpla ...

Showing a heading based on a value in Angular: A Complete Guide

I am attempting to dynamically change the title based on the item's _id value. I have stored the item in the component. Here is the HTML code I am using: <h1 mat-dialog-title>{{item._id ? "Update" : "Add"}} animal</h1> Below is my dialog ...

Text box content does not refresh unless the page is reloaded

My text box (tbAdresse) is initially empty. I'm using the following JavaScript code to set its value: origin = document.getElementById("tbAdresse").value; if (origin == "") origin = <%=this.GetFormatStringCoordonnees("Paris")% ...

Unable to receive data from jQuery AJAX request

I'm feeling a little puzzled at the moment. Whenever I run my ajax call, the error function is triggered every time. I am aware that the data is returning as JSON, and I have set the datatype as jsonp to enable cross-origin functionality. I am not sur ...

Preventing Event Bubbling in Polymer 1.5 for iOS When Using iron-pages

Our single-page app utilizes iron pages and express-router for navigation. While it functions flawlessly on browsers and Android devices, we've encountered a bug when using iOS. The issue arises when switching pages by clicking a button. If the button ...

Unable to retrieve custom date picker value with React Antd

I have implemented a custom datepicker for entering dates in the 'MMDD' or 'MMDDYY' format. The date value is stored in state and used in the datepicker component as a controlled component. However, upon form submission, the datepicker ...

Express.JS failing to save data to file when using NeDB

Currently, I am developing a bulk import feature for my personal password manager and I have encountered a problem. The issue arises when trying to import an array of passwords using the forEach() method to iterate through each one. After calling the inse ...

Is the input field not properly centered on the page?

Can someone explain why the input field is not aligning in the center? I am new to web development and need some assistance. <input type="text" id="search_bar" class="form-control" placeholder="Search" align="center"> In my CSS, I've ...

The reactivity of VUE 3 arrays is not being updated, but individual array elements accessed using array

Currently facing an issue while trying to connect a dynamically updating array of objects to a Konva circle. The circles are appearing as expected, but the problem arises within a for loop where I update player locations based on a "tick". While setting th ...

Explore the possibilities of using a unique custom theme with next.js, less, and ant design

Trying to customize the default theme in antdesign has been a challenge for me. I've switched from sass to less, but there seems to be something that just won't work. I've exhaustively searched online for solutions - from official nextjs ex ...

Issue with Highcharts failing to render points on regular intervals

I am facing an issue where the line graph in my frontend application using highcharts disappears or fails to draw to the next new data point every 30 seconds. Can anyone provide insight into why this might be happening? Check out the fiddle: http://jsfidd ...

Modifying content on the fly with a dropdownlist in Knockout framework

Currently experimenting with implementing inline editing through knockout. I stumbled upon this informative thread about Knockout Inline Edit Binding After some tweaks to introduce a "Select" for edit mode, the functionality seems to be working fine. Howe ...

Dynamically insert textboxes into a form by leveraging the power of the Jade template engine

Looking for a solution to a simple requirement that doesn't seem to have a clear answer online. I need a combobox on my jade page that accepts numbers as input. When the user selects a number, I want the page to refresh and display that many textboxes ...

Creating a dynamic JSTree that loads data on demand using Stored Procedures

Currently in my SQL Server database, I have two Stored Procedures that are responsible for extracting data from a tree structure: One procedure retrieves all nodes at a specific level based on the provided level number. The other procedure retrieves th ...

Creating a unique-looking visual representation of progress with arcs

Looking to create a circular progress bar (see image below), with loading starting from the left bottom side up to the right bottom side. The empty state should be light-blue (#E8F6FD) and the progress color strong blue (#1CADEB). https://i.sstatic.net/VZ ...

Discover and transform any strings that begin with http & https into clickable links

Can I use jQuery to search a paragraph for all strings that begin with http & https and turn them into clickable links? I have my Twitter feed displayed on my website, but any lines starting with http & https are shown as regular text. Is it feasible to t ...

Discovering feedback from JavaScript

I have been attempting to call JavaScript from a Visualforce page. The code snippet below shows a sample of the Visualforce page where I am trying to call a get method and am curious to see the response. Once I click on preview in the developer console, th ...