Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript Array Deep Dive: Reading and Assigning Values To Array

## Wednesday, December 29, 2021

JavaScript Array Deep Dive: Reading and Assigning Values To Array

In the previous post we created arrays of different types, in this post we are going to read the values from our arrays.

Let's work with the following arrays
1. var numbers = [1,2,3,4];
2. var stringArray = new Array("USA", "Canada","China");
3. var objectArray = [{firstName: "Jane", lastName:"Johnson", weight:"115lbs"},{firstName: "Jack", lastName:"Johnson", weight:"200lbs"}];

To get the second value of an array you would write the following code by using the :

console.log(numbers[1]);
console.log(stringArray[1]);
console.log(objectArray[1]);

The code above gets the second values of the second elements of each array.

When we assign values to an array that's when things starts to get interesting.  Since JavaScript arrays are dynamic and can shrink and grow as needed you can do some interesting things with it.

For instance you can dynamically create an element in the numbers array.  Let's say we want to have have the number 5 at the end of the array.  Now it other programming languages you have to go back and resize the array then create an element with the number 5.  But in JavaScript all you have to do is this

numbers[4] = 5;

Now the numbers array is 1,2,3,4,5  if console.log(numbers) you will see the following

As you can see now the fifth element has the value 5 that we just created.

Now let's do something that's even crazier,  let's assign one of the elements to be of type string

numbers[3] = "hola!";

Now the fourth element will have the string "hola!" instead of the number 4

So as you can see just because the array is named numbers it could strings in it, so be careful!

One final thing about JavaScript array, well there's a lot of things about JavaScript array but it's beyond the scope of this blog.  Sorry! I always wanted to say that. Can't help myself!

One other thing about JavaScript array is that you can assign an element with a name instead of the index.

For example we could assign an element call "employee" as an element in the numbers array

numbers["employee"] = "Jack";

If you console.log(numbers) you will see that the element "employee" was added to end of the array

You could also access the "employee" element directly with the code numbers["employee"], as you can see the "employee" element is an object.  So you will lose the ability to access the element with an index

Let's say you have the following

console.log(numbets["employee"]);
console.log(numbers[5]);

The first output would be "Jack" while the second output will be undefined