DEV Community 👩‍💻👨‍💻

Arya Krishna
Arya Krishna

Posted on

Arrays in Javascript

Let us see how we can do the following in javascript -

  • How to store collections of values in arrays

  • How to loop over anarray to apply repetitive code to each value in a collection

  • How to create and call functions to execute sequel blocks of code on demand

  • How to pass values into functions to create dynamic results

We have been storing one piece of data in variables

var name = "Arya";
var books = 4; 
var isStudent = true;
Enter fullscreen mode Exit fullscreen mode

Arrays are used to store groups of data in a single variable.

var names = ["Arya", "Krishna", "Manvi", "Amogh"];
Enter fullscreen mode Exit fullscreen mode

We name arrays in the same way as we did for a single variable. We name a variable, use the assignment operator and assign a value to the array list. The key syntax or the way we assign the value to an array is that we type a set of []as a value and with coma separating values we write each elements in an array list.

In the above example of var names, we have created a sequence collection of 4 string values inside square brackets.

Remember that arrays are an ordered list means all the elements are assigned a position.

Arrays are zero-indexed, so the index of first element in the array is 0.
That means when we are trying to assign a position in an array, we count up from zero.

If we have to go and access a specific value, then we will go ahead and use the variable name again and extending it with square brackets and using the index pointer to point towards a specific item in the array.
That means to log a single element, we use the name of the array with the index in brackets

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Life is too short to browse without dark mode