Code has been added to clipboard!

array.length

Reading time 1 min
Published Aug 10, 2017
Updated Oct 10, 2019

JavaScript Array Length: Main Tips

  • You can use the JavaScript length property to return the array length.
  • The length property sets the length of arrays as well.

Returning and Setting Array Length

The array.length property returns the length of array in JavaScript.

Example
function mySample() {
    var cars = ["Audi", "BMW", "Toyota", "Mercedes"];
    document.getElementById("demo").innerHTML = cars.length;
}

Tip: this property for getting array length in JavaScript can count not defined values.

The JavaScript length property can change the number of elements arrays have.

However, if you simply indicate that the array length shifts from 3 to 4, the property creates an extra non-iterable empty spot.

Follow this example to use JavaScript to set length of arrays:

Example
function mySample() {
    var cars = ["Audi", "BMW", "Toyota", "Mercedes"];
    cars.length = 7;
    document.getElementById("demo").innerHTML = cars.length;
}
What Is JavaScript Used For?
Tutorial
Introduction
Output
Syntax
Comment
Commands
Operators
Comparison and Logical Operators
Data Types
Math.random()
Type Conversion
Function Definitions
Events
Objects
Object Properties
Prototype
Array
Sorting Arrays
Strings
Numbers
Number Format
Math Object
Onclick Event
Date
Date Formats
Scope
Regular Expressions
Reserved Words
Common Mistakes
Performance
Forms
Form Validation
Window: The Browser Object Model
Popup Boxes
Cookies
JSON
AJAX Introduction
AJAX Form
Automatic File Download
Functions
Array Methods
String Methods
Date Methods
Timing Events
Cheat Sheet
JavaScript in HTML
HTML DOM Methods
HTML DOM Changing HTML
HTML DOM Animation
HTML DOM EventListener
HTML DOM Navigation
HTML DOM NodeList
HTML DOM Element Nodes
Array Functions
Boolean
Calling a Function
Date Functions
Global Objects
Input Text
Operator
Statements
String Functions
Math
Math.random
Number
RegEx
alert
array.filter
array.length
array.map
array.reduce
array.push
array.sort
break and continue
className
confirm
decodeURIComponent
for
forEach
if
indexOf
innerHTML
location.reload
number.toString
onclick
onload
parseInt
prompt
replace
setAttribute
setInterval
setTimeout
slice
splice
string.includes
string.indexOf
string.split
style.display
submit
substr
substring
switch
test
throw, try and catch
toLowerCase
toUpperCase
use strict
while
window.history
window.location
window.navigator
window.screen