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: 144
0 Comment Guest
Recommend 0
Sort by Newest
Be the first to say something...

Ask Community

Ask questions and Share knowledge with Community

Find below recent posts for automation solutions with questions and answers by community. You can search in past threads or post new question about your assignment with detailed description, and always could mark your question as request. Sharing knowledge are highly appreciated by answering on others questions, and in return awards will be decided.

#
Recent Questions
*
i need to know how to convert 723,413,000 sq mm into mm2.
109
1
0
*
How to convert kg/m3 to kn/m3
97
1
0

  View More

× Close
Results: