Declare Arrays in jQuery

Sam Deering
Tweet

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 jslint.com I found out it says declaring an array with an array constructor is seen as bad practise! It suggests using literal notation.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Kars

    Hello JQuery4U. I like playing around with arrays. I just made my first 4 dimensional one :)
    Why would not declaringvar arlene = []; give script errors? Is that in case it would contain variables that could be empty? Like so: var arlene = var1,var2,var3];

  • Kars

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

  • DD

    fast question where is jquery in this examples?

    • http://jquery4u.com/ jQuery4u

      It’s plain JS

  • Naveen

    Thanks :-)

  • nikhiljoshi

    Hey thankas your Posts really helpus obn many ways to learn lost of stuff

  • Ben

    Hi. I have a 2D array, i want to assign it to a variable, such that,

    var test=arr[0][0];

    when i want to print out the value of test, it give me undefined value. where did i go wrong? thanks in advanced.

  • Kelly Clover

    For some reason I can’t get jQuery to download on my computer. I want to get rid of any and all plugins that use jQuery. Google Pagespeed Insights blames jQuery heavily for page speed problems.