0

I have been told that in JavaScript,if you assign a value to a variable that has not been declared it will automatically become a global variable, even if it present inside a function.

I have the code:

function helloWorld2(){
            greeting2 = "hello world 2";
}
document.write(greeting2);

But netbeans output the following error message:

Uncaught ReferenceError: greeting2 is not defined (15:58:36:083 | error, javascript)

Why is this happening?

halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137
  • 3
    But have you called `helloWorld2` function ? Try `helloWorld2()` before `document.write` – Rayon Jul 01 '16 at 06:02
  • @Rayon Thank you so much! It worked! So I guess I have to use the function first before the variable comes global. – Thor Jul 01 '16 at 06:04
  • 1
    Variable will become global only if function holding that variable is `invoked` – Rayon Jul 01 '16 at 06:05
  • @Rayon do you mind if I ask, why does javascript allow global variable declaration like this? Cause from my/javascript beginner's point of view, this can cause a lot of confusions. – Thor Jul 01 '16 at 06:06
  • 1
    Some [__Food__](http://stackoverflow.com/questions/1470488/what-is-the-function-of-the-var-keyword-and-when-to-use-it-or-omit-it) for you... – Rayon Jul 01 '16 at 06:08
  • @dzjustinli2: Because it was thought to be clever initially. It's disallowed in strict mode (and throws an exception) exactly because it causes too much confusion and lets slips go through unnoticed. – Bergi Jul 01 '16 at 08:27

0 Answers0