3

I think Javascript is trying to kill me. Errors that would be caught by a compiler in any statically-typed language including FORTRAN, or turn into a run-time exception in any decent dynamically-typed language are swallowed silently by Javascript, patiently waiting to manifest as a bug elsewhere.

Whenever we write Frontend code (nowadays with Angular), we spend most of our time hunting down mistakes such as writing $scope.result = data.results instead of data.result . While some tools help, it still requires an astonishing amount of work.

Is there a way to cause the Javascript environment (in a browser) to log a warning whenever someone tries to read a non-existing object property? I don't want to change the language's semantics - accessing data.results should still returned undefined, I just want to see a warning on the console saying "Non-existing property accessed, file ... line ...".

zmbq
  • 38,013
  • 14
  • 101
  • 171

3 Answers3

2

This is a duplicate of this question I think : Force JavaScript exception/error when reading an undefined object property?

In short : no satisfying solution for your use case, but if you all use firefox you can use javascript.options.strict set to true to have warning in such cases :)

Community
  • 1
  • 1
Mijamo
  • 3,436
  • 1
  • 21
  • 21
1

In ECMAScript 2015 you can use Proxy to do this, for example:

function createObject(obj) {
    const handler = {
        get: function(target, name){
            if (name in target) {
                return target[name];
            } else {
                console.warn("accessing undefined object property: " + name);
                return undefined;
            }
        }
    };
    return new Proxy(obj, handler);
}


let a = createObject({
    b: 1,
    c: undefined
});

a.b;
a.c;
a.d; // accessing not existing object property: d
madox2
  • 49,493
  • 17
  • 99
  • 99
  • So I'll need to wrap each object (some are created by external code such as Angular) with this proxy. This is not bad! I'll try the Firefox setting first, if it works its the simplest solution. – zmbq Jan 31 '16 at 21:17
0

This might seem amateurish, but you might be able to store all of your variables in a loop able object like an array or object and then loop through them to check if any of them are undefined, then print the results of that. You might be able to use a dictionary with key:value pairs. Not ideal, though.

kairocks2002
  • 436
  • 1
  • 3
  • 15