0

about variable declarations in node /javascript: var, let const, ...

I experimented in a node script

that if one declares a variable without any statement (var, let const, ...)

x = "my new var";

then x will have a global scope and will be visible from all the modules of the node project

question

Is it correct to declare a variable like that? or is it deprecated / contrary to the rules of language?

Simone Bonelli
  • 411
  • 1
  • 5
  • 18

2 Answers2

2

It's allowed in normal mode (a.k.a. sloppy mode), but in ES5 strict mode, assignments to undeclared variables will throw an error, so it can be considered deprecated in some sense.

hectorct
  • 3,335
  • 1
  • 22
  • 40
0

It compiles fine, so it is not contrary to the rules of the language and is not deprecated as far as I know. It is considered bad practice, for the same reason global variables are considered bad practice in all languages. One example, especially with a generic name like x, is you might override it locally by mistake and get some unexpected results. There are plenty other of caveats.

It might be OK sometimes. One use case I can think of is if you want to use pi everywhere in your program, declaring it globally would make sense. Of course, it would be better to wrap it in a constants class, but for a single constant a class may be overkill, and I would define PI = 3.14 at the top of my program.

kabanus
  • 24,623
  • 6
  • 41
  • 74