Arrays in JavaScript

in #javascript3 years ago (edited)

Today I got introduced to Arrays in JavaScript. Here is the tutorial that I used:

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];

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!


you're welcome )

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.

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

Posted using Partiko Android

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

for (var i in myArray) {

Thanks for advice!

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!