Array in Node.js #
Array is one of the important things in every computer language. Array can have unlimited number of elements.
Element is building block of the array. We will see the element later and get more idea about this.
var names = ; // declaring array with 0 elements var country = ["India", "Nepal"]; // declaring array with 2 elements
Array works on the basic on index number and in order to access any value. Counting number start with 1(one) but index number start with 0(zero).
To access the first element we need to ask for 0 element. Let me show you with demo and it will make more sense.
var country = ["India", "Nepal"]; console.log(country); // India console.log(country); // Nepal
Adding Element to Array; #
push method is used to append the element at the end of the array.
var names = ; names.push("User 1"); console.log(names);
Updating Element to Array; #
var names = ["User 1", "User 3"]; console.log(names); names = "User 2"; console.log(names);
Removing Element to Array; #
pop method is used to remove the last element of array.
var names = ["User 1", "User 3"]; console.log(names); names.pop(); console.log(names);
- Array is reference be default in nature and it refer to memory address.
- We can’t easily make copy the array to another variable.
var names1 = ["John", "Peter", "Kenny"]; var names2 = names1; names1 = "Random"; console.log(names1); // [ 'Random', 'Peter', 'Kenny' ] console.log(names2); // [ 'Random', 'Peter', 'Kenny' ]
In the above example we get some unexpected output. We were not expecting that names2 variable will also be updated.