Skip to main content

Declare Arrays in jQuery

By Sam Deering



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

Simple  JavaScript code snippets to delare an array. Like other JavaScript variables, you do not have to declare arrays before you can use them. I like to declare them just so I can easily read whats going on, it’s a good practice!

Example 1 – Array Constructor

// Declare an array (using the array constructor)
var arlene1 = new Array();
var arlene2 = new Array("First element", "Second", "Last");

Example 2 – Literal notatoin

// Declare an array (using literal notation)
var arlene1 = [];
var arlene2 = ["First element", "Second", "Last"];

Example 3 – Implicit Declaration

// Create an array from a method's return value
var carter = "I-learn-JavaScript";
var arlene3 = carter.split("-");

To avoid script errors, you should get into the habit of initializing an array when you declare it, like so:

// Declare an empty array using literal notation:
var arlene = [];
// The variable now contains an array of length zero

After checking my code on I found out it says declaring an array with an array constructor is seen as bad practise! It suggests using literal notation.

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn valuable skills with a practical introduction to Python programming!

Give yourself more options and write higher quality CSS with CSS Optimization Basics.