+ 2

A simple counter in javascript?

var points; function add() { points++; } add(); add(); alert(points); function add2(points) { points ++; } add2(points); add2(points); alert(points); Why does each alert output NaN? How do you make a counter in JavaScript? The scope is unlike other languages. I've heard of hoisting, but I'm not sure if I completely understand it.

24th Dec 2017, 5:09 PM
bornToCode()
bornToCode() - avatar
6 Réponses
+ 1
Yes that's correct...😂 Or undefined + number = undefined The point is that if you don't put a value to your variable, it automatically becomes undefined.
24th Dec 2017, 6:13 PM
Ledio Deda
Ledio Deda - avatar
+ 3
In the future, can you embed a code playground code to the question, making it easier for us to debug your code.
24th Dec 2017, 5:18 PM
eRosz
eRosz - avatar
+ 2
My apologies, here is an example: https://code.sololearn.com/W9O9il74I8kc/?ref=app
24th Dec 2017, 5:22 PM
bornToCode()
bornToCode() - avatar
+ 2
I see, so I just needed to initialize it. So I guess NaN + some number = NaN?
24th Dec 2017, 5:37 PM
bornToCode()
bornToCode() - avatar
+ 2
Thank you!
24th Dec 2017, 6:15 PM
bornToCode()
bornToCode() - avatar
+ 1
There it is. You should had initialized your variable points like in the code. https://code.sololearn.com/W3t2Pir9kXHK/?ref=app
24th Dec 2017, 5:26 PM
Ledio Deda
Ledio Deda - avatar