1

How to create a global variable in Client side JS, where the variable should not be accessible from browser console ? I tried using let, it did not work (the code below is not in a function it is in a script file)

let data={
   "data-item":"Secure Data"
};

I also tried adding data in a class and using an instance of it but the instance is also accessible from console. The variable is an object and will be modified dynamically by user interaction, so cannot freeze the object either.

4
  • 2
    If it's global, it'll be accessible from the console. I'd give up on making it global. Commented Jan 18, 2021 at 6:38
  • @CertainPerformance but there are a lot of functions and event listeners that has to access this variable dynamically when user interacts. Commented Jan 18, 2021 at 6:40
  • That shouldn't make it an issue - just scope everything to some private closure. Commented Jan 18, 2021 at 6:41
  • @CertainPerformance can you show an example ? Commented Jan 18, 2021 at 6:43

1 Answer 1

4

If an identifier is global, it will be accessible from the console.

If you want something not to be accessible from the console, it will have to not be global. Easiest option would be to put everything into an IIFE. For example, turn this:

let data={
   "data-item":"Secure Data"
};
// lots and lots of functions and variables that reference data

into this:

(() => {
  let data={
     "data-item":"Secure Data"
  };
  // lots and lots of functions and variables that reference data
})();

and then data will be scoped only inside the IIFE, so it won't be accessible from the console, but everything that needs to access it will still be able to see it.

Sign up to request clarification or add additional context in comments.

1 Comment

It works and to access the functions inside this arrow function, I have to use addeventListener instead of onclick. and the whole thing should be inside window.onload event handler to get elements only after it is loaded

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.