Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Working with arrays

From: JavaScript Essential Training

Video: Working with arrays

So we've seen how to create variables. We use the word var, we give it a name, and then we can use the equal sign to give it a value. That could be a number, that could be a string, that could be a Boolean. What we can also do is create arrays. An array is a single variable that holds multiple values. You create it quite similarly to creating a normal variable. I'm going to make one here called multipleValues. You can call it anything you'd like. But to tell JavaScript this is an array, there are a few ways to do it, but the easiest one is this: var multipleValues = opening square bracket, closing square bracket.

Working with arrays

So we've seen how to create variables. We use the word var, we give it a name, and then we can use the equal sign to give it a value. That could be a number, that could be a string, that could be a Boolean. What we can also do is create arrays. An array is a single variable that holds multiple values. You create it quite similarly to creating a normal variable. I'm going to make one here called multipleValues. You can call it anything you'd like. But to tell JavaScript this is an array, there are a few ways to do it, but the easiest one is this: var multipleValues = opening square bracket, closing square bracket.

And this is the indicator that we're dealing with an array. When you see the square brackets, it's a pretty good indicator you've got an array. This line simply creates a single variable called multipleValues that you can put several things inside. Well, how do you do that? Using the square brackets again. If we want this array to hold multiple values, we need to be able to say which one are we dealing with, so we use an index. And I'm saying here I want the index at 0 to be equal to the value 50.

I want the index at 1 to be equal to the value 60. I can say the index of 2 is equal to the value Mouse. And notice that what I can do is I can put in a number, I can put in a string, I could put in a Boolean; it doesn't matter what kind of data you're putting in at the different slots in the array, but all of them are accessed through the index. That's whether you're setting these values, that's whether you're getting these values. And arrays in JavaScript use what's called a zero-based index. The first entry is at position 0, not position 1.

And that's very common with most languages. What we can then do is use the same format to get to the contents of the array. So if I want to write out a console.log message, I want to get the value that's at position 2 in the array called multipleValues, I use the square brackets and it writes out the word Mouse. So if this is the way that we write arrays, it's okay. It's not too bad, but it would be nice if there was something a little quicker, and in fact there is. There is a shorthand method for doing it. We use the square brackets and we just load it up with those initial values, in this case, 50, 60, Mouse, inside double quotes.

And it will automatically put them in at position 0, position 1, and position 2. You could then come along and add on position 3, position 4, and so on, but it's always a zero-based index. Now, although this is my favorite way of saying to JavaScript, "Hey, I'm creating a variable that should be an array," there are actually multiple ways to write this, and there's multiple ways you'll see it when you're reading other people's code. An equivalent way is this: var multipleValues =. We use the word new and Array, Array with an uppercase A here.

Now for those of you coming from other languages, you might be familiar with this kind of format. That's because arrays are objects. They are a special kind of value that we're going to have a lot of dealings with shortly. And although this format saying = new Array will work, you don't have to even have the word new. You could just say this as well. All of these are exactly equivalent to each other. Now for those of you coming from other languages, you might be wondering what is the size of the array, how does JavaScript know how big this array is? Well, we can officially create it with a size/ In this case, I'm saying the array should have 5 slots, 0-4, but all arrays in JavaScript are dynamic.

They can be as big as you want them to be. If you want something to exist at position 5, you simply load it into position 5. If you want it to exist at position 100, you load it into position 100. While there is a theoretical fixed limit to the size that an array can get to, you're never going to run into to it. So my favorite way is just the square brackets by themselves. I think that's the most straightforward way of doing it. Now because arrays are objects, they have properties, and properties means information that we can get to about them.

So if I write a line of code that creates an array and loads it up with some initial values, as in this case, what I can actually do is use the name of the array-- in this case multipleValues--then a dot, and then I can access the length property-- it's information about the array. So in this case, I can write out a message that says the length of this array is 5. We have five elements in it. Now, the highest index might be 4. We're going to 0, 1, 2, 3, 4, but there are five elements in there. The length is 5.

And because arrays are objects, they also have methods. Now what does that mean? Well, we know how to call a function. We use the name of the function, we use the parentheses, and optionally pass in any parameters that function requires. Well, a method is a function that belongs to an object. So if we've created an array or created another kind of object, as we'll see shortly, we can use the name of that object, then a dot, then the name of the method to call a method. Here's an example.

So I create an array with five values in it. I've got this object and it's called multipleValues. What I can then do is say the name of the object, dot, and then the name of the method. It's like a function that belongs to it. Well, arrays have built-in methods. We've got reverse as one of them. In fact, when I call reverse on this array, what it's going to do is give me another array, and I can use the result of that to actually create a new variable, in this case var reversedValues, which is also an array.

So.reverse() is a method of the array object, as is.join(), which would join two together, as is.sort(), and I call them all using this dot operator. But by calling.reverse(), I have this new reversedValues array, and I could actually call the methods of it. So I could write out console.log ( reversedValues.join() ) which is a method of array, and that will actually join all the values in the array together and output them as a single string, in this case, writing the contents of it, which are the reversed values, back out.

These are obviously very simple examples. We'll actually see some practical ones as we go forward. But the fact that arrays are objects just means we can ask them to do things, and very useful things in a lot of cases. If you're new to programming, you might be tempted to think of arrays as being esoteric things you're not really going to use all that much. Well, arrays are everywhere in JavaScript. You won't be able to get away from them. You may create some yourself, but a lot of them you'll be given. You'll have to deal with them.

For example, you might at some point want to write a little line of JavaScript that says, "I want to know how many anchor tags exist on the page, how many links do I have, or how many paragraphs do I have, or how many h3s do I have?" Well, what we can do to get that is called the document.getElementsByTagName method. And we'll get into this a little later. We haven't seen it yet. But this is a built-in ability of JavaScript to scan through our HTML, grab, in this case, everything that has an a tag, an anchor tag, and return it to us.

I could also ask for all the paragraphs, so all the p tags, or all the h1 tags, or h2s, or h3s. And what I'll get when I call this is an array. So whether there are four links on the page or a dozen or a hundred, I'll have an array to deal with. So whether you're asking, give me all the links that exist on the page, or you're wanting to go through all the form fields that exist on a web form, arrays are going to be your friends. You are going to have to deal with these. They are zero-based in JavaScript.

They are dynamic, meaning that you can change them very easily. You don't have to use special code to do that. You're always going to see the square brackets to deal with them. That's always that identifier to you that you're dealing with an array.

Show transcript

This video is part of

Image for JavaScript Essential Training
JavaScript Essential Training

56 video lessons · 101381 viewers

Simon Allardice
Author

 
Expand all | Collapse all
  1. 3m 28s
    1. Welcome
      1m 1s
    2. What you should know
      1m 44s
    3. Using the exercise files
      43s
  2. 15m 41s
    1. Introduction to JavaScript
      8m 6s
    2. Creating your first JavaScript
      2m 13s
    3. Getting to know the tools and applications
      5m 22s
  3. 56m 8s
    1. Understanding the structure of JavaScript code
      7m 9s
    2. Where to write your JavaScript
      3m 56s
    3. Creating variables
      6m 21s
    4. Working with conditional code
      5m 44s
    5. Working with operators
      13m 28s
    6. Sending messages to the console
      2m 59s
    7. Working with loops
      8m 1s
    8. Creating functions
      8m 30s
  4. 36m 13s
    1. Working with arrays
      7m 57s
    2. Working with numbers
      6m 13s
    3. Working with strings
      8m 27s
    4. Working with dates
      5m 38s
    5. Working with objects
      7m 58s
  5. 9m 6s
    1. What is the DOM?
      5m 49s
    2. Working with nodes and elements
      3m 17s
  6. 25m 17s
    1. Accessing DOM elements
      11m 3s
    2. Changing DOM elements
      5m 42s
    3. Creating DOM elements
      8m 32s
  7. 24m 45s
    1. Introduction to JavaScript event handling
      8m 16s
    2. Working with onClick and onLoad events
      7m 36s
    3. Working with onBlur and onFocus events
      2m 36s
    4. Working with timers
      6m 17s
  8. 21m 41s
    1. Common JavaScript errors
      7m 14s
    2. Using Firebug
      4m 7s
    3. Going through a debugging session
      10m 20s
  9. 10m 13s
    1. Accessing form elements
      4m 20s
    2. Preventing a form from being submitted
      2m 36s
    3. Hiding and showing form sections
      3m 17s
  10. 9m 49s
    1. CSS and JavaScript
      3m 46s
    2. Removing and applying CSS classes
      2m 16s
    3. Changing inline styles
      3m 47s
  11. 19m 44s
    1. Understanding JavaScript style
      7m 39s
    2. Minifying your code
      4m 28s
    3. Using JavaScript code checkers
      7m 37s
  12. 22m 24s
    1. Introduction to JavaScript libraries
      3m 17s
    2. Linking to multiple JavaScript files
      2m 11s
    3. Introduction to jQuery
      12m 7s
    4. Using a content distribution network to deliver JavaScript files
      4m 49s
  13. 17m 35s
    1. JavaScript in HTML5
      9m 37s
    2. Using Modernizr
      3m 2s
    3. Using Strict Mode
      4m 56s
  14. 33m 3s
    1. Knowing the JavaScript to avoid
      6m 35s
    2. Introduction to regular expressions
      6m 56s
    3. Working with AJAX
      10m 44s
    4. Working with objects and prototypes
      8m 48s
  15. 21m 10s
    1. Example: Countdown
      8m 3s
    2. Example: Resize
      5m 47s
    3. Example: Accordion
      7m 20s
  16. 4m 58s
    1. Where to go from here
      4m 0s
    2. Goodbye
      58s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed JavaScript Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.