1

I am writing a program where one is supposed to answer questions. The number of correct answers is held by a variable called:

correctAnswers

But as the case is now, I can change the value of

correctAnswers

by simply typing in

correctAnswers = (new Value)

in the console. I don't want this to be possible, is there a way I can disable the possibility to alter a variables value through the console?

PandaDeTapas
  • 516
  • 1
  • 7
  • 16
  • 1
    This question was previously answered here: http://stackoverflow.com/questions/1535631/static-variables-in-javascript - the short answer is that JavaScript does not have static variables like, for instance, PHP, however, you could create an object property that will give you mostly the same result. – zfrisch Apr 13 '15 at 16:50
  • You can make it *slightly* more inconvenient by making sure `correctAnswers` isn't global. Wrap your code all inside a [IIFE](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression): `(function(){ }());`. – gen_Eric Apr 13 '15 at 16:50
  • You could try [disabling the console](http://stackoverflow.com/a/21693931/382456), which still seems to be working for me on Chrome 43. – Scott Apr 13 '15 at 17:15

2 Answers2

2

There is no possible way to stop someone from changing the variable value, you can only make it harder. For start, put the variable in function so you can't access it outside the function like this: (function(){}());

Another option you have is to encrypt the code but I'm not sure how much it's effective, never tried that. Any way all these options just make it harder but not impossible, you always need to confirm the data in the server-side.

TL;DR: You can't do it on the client side.

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
yotamN
  • 711
  • 2
  • 9
  • 22
2

Try using closure.

var Test = (function(){
    var correctAnswers=0;

    return {
        getCorrectAnswers: function(){ return correctAnswers; }
    }
})();

// Enter the following in console
correctAnswers = 2;
Test.getCorrectAnswers(); // will always return 0;
Hoyen
  • 2,511
  • 1
  • 12
  • 13
  • Now, I just need to modify a different variable via the console: `var Test = (function() { var correctAnswers=100; return { ... } })();` – Blazemonger Apr 13 '15 at 16:54
  • This may make it harder but not impossible because eventually every code you write is running by your own computer, which you can access and edit. – yotamN Apr 13 '15 at 16:54