WBxs
Jan 15, 2018

Welcome to our tutorial, now I am going to explain the fastest way to declare javascript array as well using related basic properties.

protect your javascript code

By the end of this tutorial you will be aware of:

How to Declare a Javascript Array ?


There are two different syntax to create a new empty array as follow:
var array_name = [item1, item2, ...];

//OR


var array_name = new Array(item1, item2, ...);

Spaces and line breaks does not affect the syntax, where a declaration can span multiple lines.

Fastest Way to Declare Javascript Array


The two examples above do exactly the same, but the first one "[] method" is the fastest shorthand form.
var array_name = [item1, item2, ...];

How to Add New Element to a Javascript Array ?


In JavaScript you could add a new element to an array by simply using the "push" method, like this:
arrayname.push("Element 1");
arrayname.push("Element 2");

This allows you to add items to an array without knowing the number of items.
Alternatively, if you wish to know the element index yourself and place them in specific index, you can use syntax such as this:
arrayname[0] = "Element 1";
arrayname[1] = "Element 2";

Know how Many Elements Are in a Javascript Array ?


When you want to know how many elements are in an array, you can use the "length" property, like this:
document.write(arrayname.length);

Example on a Javascript Array


Next, will show you an example for a simple script that creates an array, adds to it some values, and then displays them.
<script>
//Creating, adding to, and printing an array

var numbers = [];
numbers.push("One");
numbers.push("Two");
numbers.push("Three");
for (i = 0 ; i < numbers.length ; ++i)
document.write("Element " + i + " = " + numbers[i] + "<br />");
</script>

The output from this script is:
Element 0 = One
Element 1 = Two
Element 2 = Three

Try WhiteBoxes JavaScript Obfuscator >>

Thank you for reading the above article. Please let us know your comments below.

References:
  • Practical Experience
About the author

Adam Hassan

Adam is a freelance web designer, recreational software developer, author and CEO of infoapper.com . Also, has passion to learn and transfer the know-how of every valuable thing.
Views: 286
× Close
Results:
Want to Enable Key Features? Create a Free Account.