Access array data with index problem

Tell us what’s happening:
What am I doing wrong?

Your code so far


var myArray = [50,60,70];
array[0];
var myData=[0];

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15

Challenge: Access Array Data with Indexes

Link to the challenge:

ive also changed the myData bracket to 1 and thats also results in an error

your code should look like this

var myArray = [50,60,70];
var myData = myArray[0];

That’s becuase you are creating a variable (var myData) and setting myData to equal the first value of myArray (50) by using bracket notation ( myArray[0] ).

Since computers start counting at 0, myData will equal 50 when you use var myData = myArray[0]; the created variable will now equal the first value of myArray.

I hope that didn’t sound too confusing. I am just trying to explain it to the best of my knowledge.

2 Likes

it worked, but im curious why in the example it had array in the middle if I was supposed to equal it to my data.

This line array[0]; is a syntax error as there is no variable named array that is an array. The fact that you have an unhandled error in your code I believe will prevent you from passing the test at all.

This line var myData=[0]; would be assigning myData to an array with one element, and that element would be 0.

myArray = [1,2,3];
console.log(myArray[0]) //1

//An array is accessed with bracket notation which is 
//why you use a bracket to get values out of it

If you are interested this is the docs on property accessors:

3 Likes

Hmm that is strange. When I got back to my lesson for “Access array data with index” is starts me off at var myArray = [50,60,70];

There is nothing else shown for me. That array in the middle may be the challenge you had to figure out? I dont really know though. Do you understand in general though on how to do this lesson now? Just makin sure because I know it’s hard when youre trying to figure it all out alone lol.

Actually, it’s not a syntax error, JS will execute it just fine, it’s just nonsensical since it doesn’t do anything. Usually you would either assign its value to a variable or assign a value to that index in the array. But you can indeed just have the line

array[0];

I’m not really sure what the point is of having that line in the example in the lesson. It seems to be confusing people more than helping to illustrate the point. Also, you would never do this.

3 Likes

I believe you may be confused as to what I am referring to. I am not referring to the example within the challenge, but the example above which the author presented.

Ahh, right you are. I was looking at the example in the lesson and didn’t look close enough at the OP’s code to see that it wasn’t the same. Sorry about that.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.