-1

My issue is that logging exactly the same variable value, but accessing it in a different way, yields two different results.

console.log(car[1].wheels.radius)

logs the integer 20 to the console, since 20 is the value assigned to car[1].wheels.radius.

Now, if I log the whole object:

console.log(car[1])

and access the element radius manually in the console, I can see that its value is 'NaN'.

Same happens when I use car[1].wheels.radius in a calculation, for instance 3.14*car[1].wheels.radius returns NaN, even though this is a multiplication of 3.14, a number, and car[1].wheels.radius, also a number, so it should return a number.

Anyone knows what the issue might be?

bkr879
  • 2,035
  • 2
  • 15
  • 23
  • We need to see more of your code. – jmar777 Oct 31 '14 at 14:01
  • 2
    Post your actual code – tymeJV Oct 31 '14 at 14:02
  • 4
    im guessing you print the `car[1].wheels.radius` first which results in the expected out put 20. But you then perform some calculation on it (which fails in some way and produces NaN), now when you log the object you are not seeing the object at the time you logged but the object at the time you inspect it in the console which can account for the difference – Quince Oct 31 '14 at 14:05
  • In addition to Quince's comment you might want to look at http://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays for more details on the matter – k-nut Oct 31 '14 at 14:07

1 Answers1

1

OK to actually answer the question in the title about why you get different results when logging a variable -

If a primitive is sent to the log then it is immediately displayed with the value so in this case when you send car[1].wheels.radius it does have the value 20.

However when you log an object,car[1], the values for the attributes are not actually shown until you inspect the object in the console (if you are using chrome there is a little blue (i) which explains this). Think of it like you are logging the reference, the actually objects state will not be shown until you expand/inspect that reference.

So you are performing some calculation on car[1].wheels.radius which changes it from 20 to NaN at some point which explains the difference.

The cause of that problem is unknown from the amount of code you have shown. Use the debugger to step through your code and look to see when this value changes.

Quince
  • 14,790
  • 6
  • 60
  • 69