0

I am using JSHint and I have a global variable (test) declared using the predef options. However in my code I can just override the global variable using

var test = 4;

Is there anyway to prevent this? I want to use my global variable without being able to override it in any way.

  • 3
    Use `const` instead of `var`.If your variable is a primitive, like number or string, it can't be overriden. – HynekS Nov 09 '18 at 13:07
  • @HynekS It can't be overridden directly, but could still be overridden in scope, which I think the op might be trying to prevent. eg. `const x = 1; { let x = 2; console.log(x); }` will still return 2. – Keith Nov 09 '18 at 13:19
  • I think you have to refer this [stackoverflow](https://stackoverflow.com/questions/21237105/const-in-javascript-when-to-use-it-and-is-it-necessary)! – melvil james Nov 09 '18 at 13:20
  • @Keith Well, but it's not the same x! (It's its evil twin brother..) – HynekS Nov 09 '18 at 14:01
  • @HynekS, Yea Keith was right, I am aware how const works, but using const or var, my global variable test still gets overridden in the scope and I lose all previous data :( – Wouter Klene Nov 10 '18 at 14:26
  • Ah, sorry, I misunderstood you. Well, as far as I know, you can't prevent overriding a variable in an enclosed scope (which is a function, try-catch-finally block or a literal block). – HynekS Nov 10 '18 at 16:26

0 Answers0