Why is my value value undefined?


I didn't want to post a link to the exercise, because I have finished it/passed it, I just have a question out of curiousty. Everytime it prints point[i] to the console log, it prints it as "undefined. Why is that?? Code below. The exercise is the Review of while loops.

/// Write your code below!
var point = 1
for(var i = 0; i < 27; i+=3){
    console.log("Counting your points...")}
while(point > 20){
    console.log("Your points are " + point[i])}



The Instructions:
To finish up and prove your loop mastery,
write three syntactically correct loops in the editor:
one for,
one while, and one do. Beware of infinite loops!

the for-loop:

the while-loop:

the do-while-loop:

Take care of infinite loop-conditions in your while and do-while loops...


I get what I had to do, and I did it. Almost. I wanted it to print out each point as a number value. Instead, it printed out each point from the for loop as "undefined". I'm trying to figure out why. Should I have used Math.floor instead?


Well you declared point to be 1:

var point = 1

As one is not an array or object (at least not obviously) why would you expect it to have a square bracket notation?


This assumes that point has properties of for example 0:value,3:value aso but as 1 is just a value and has no such properties you get the default undefined value of well undefined :slight_smile:

Hope this makes some sense.

PS: No Math.floor won't help you here. Better explain what you intended to do maybe we could help you fix it.


I wanted it to print points as numbers 1 to 27, counting by 3. Should I have just has console.log print out point without assuming var i is an object within an array?


You can write your for loop with point as your variable without declaring point as a variable in the line before the for loop. Then just have console.log print out point.


I had a feeling that might be why. Thank you!


:slight_smile: Have you ever used jsbin? It's an easy way to try code out and see what is syntactically correct.


Yes if you just want to print the values you could use console.log(i). Using the square bracket notation implies that the array/object has certain properties e.g. for arrays

var arr = [1,2,3,4,5,6]

arr is a container that stores 6 values which can be accessed by using arr[index] where index goes fro 0 to 5 e.g. arr[2] = 3. For objects its rather similar but the stuff inside the [] is no longer limited to numbers but could also include strings. So if you try to access a property which is no there you get the undefined value.

But as said if you're just interested in the value why not just use your counting variable i?


Just a beginner mistake, assuming I had to define said variable as point instead of just have it written out in a string:p


jsbin? I'll look into it, thanks!


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