1
> var v = Math.random() // var means local variable
> v
0.012659968143515665
> w = Math.random()
0.055781313840123414

What is the key difference between the variable v and w? Scope? In other words, when should I use local variables and when I should not?

I am focused on MongoDB interactive shell environment and it's usage with Python too.

q0987
  • 34,938
  • 69
  • 242
  • 387

1 Answers1

1

The scoping rules in the mongo shell are the same as in any JavaScript environment, see What is the scope of variables in JavaScript?.

This means, for example, that any variable declared (or used the first time) without var will be put in the global scope.

If you're writing scripts to execute with the mongo shell (e.g. mongo path/to/script.js) there is almost no reason to ever declare a variable without var, but if you're just typing stuff into the shell it doesn't matter. Typing var is just extra work for no gain.

Community
  • 1
  • 1
Theo
  • 131,503
  • 21
  • 160
  • 205