Arrays in JavaScript

avatar
(Edited)

Today I got introduced to Arrays in JavaScript. Here is the tutorial that I used:
https://www.learn-js.org/en/Arrays

In the exercise I had to define an array with the following three variables:

  1. A string which has the value of "What is the meaning of life?"
  2. A number which has a value of 42
  3. A boolean which has a value of true

After much trial and error I found this solution:

var myArray = ["What is the meaning of life?", 42, true];
console.log(myArray[0]);
console.log(myArray[1]);
console.log(myArray[2]);

Tomorrow I will pick up a book "JavaScript for Kids: A Playful Introduction to Programming", 2014 by Nick Morgan which I ordered from Amazon. Thank you @alexbiojs for recommending it!



0
0
0.000
6 comments
avatar

You can also loop over your array like so...

for (var i in myArray) {
    console.log(myArray[i]);
  }
0
0
0.000
avatar

What you did was the recommended way to assign values to array items. Now that you know howe to assign values to variables, another way to do the same task would be:

var anString = "Hello, World!";
var aNumber = 42;
var aBoolean = true;
var anArray = new Array();

anArray[0] = aString;
anArray[1] = aNumber;
anArray[2] = aBoolean;

But, as I said, your way is the best one, as JavaScript engine will create the Array object for you and assign the values.

Now you are using console.log to verify your results. Soon you will learn the best way is to use a debugger, as it helps you see what is happening on your code instead of seeing the results of it.

0
0
0.000
avatar

Thanks a lot! I'm a complete newbie at coding so this will take some time to sink in...

Posted using Partiko Android

0
0
0.000
avatar

Thank you so much for participating in the Partiko Delegation Plan Round 1! We really appreciate your support! As part of the delegation benefits, we just gave you a 3.00% upvote! Together, let’s change the world!

0
0
0.000