Wednesday, March 28, 2018

Arrays declaration initialization add and replace

Things to remember :

          Generally we will go arrays for ordered collection or If you want to insert a property between existing ones. Object will not support in this case. So we are choosing array here.

Array elements are numbered, starting with zero.

How do we declare it ?

Below are two possible ways to declare array in javascript. Most of the time all developers preferring to use second syntax only. 


Syntax I:
let arr = new Array();

Syntax II:
let arr = [];

Below are main while using array in your project. So remember these all always.

1. Initialization
2. Get element based on index
3. Replace element
4. Add new element
5. Find length


//Array Initialization
let terms = ["Test", "Drive", "JavaScript"];

//Get elements by index number
alert( terms[0] ); // Test
alert( terms[1] ); // Drive
alert( terms[2] ); // JavaScript

//Replace an elements
terms[2] = 'Vechicle'; // now ["Test", "Drive", "Vechicle"]

// Adding new ones
terms[3] = 'Hero'; // now ["Test", "Drive", "Vechicle", "Hero"]

// Finding length or count
alert( terms.length ); // 4

Below is the style mostly developers choose for array. Its easy to understand and very clear.


let terms = [
  "Test",
  "Drive",
  "Vechicle",
]; 






No comments:

Post a Comment