1

I'd like to get an error message when I misspell a variable name or an object property. Strict mode helps with local variables but what if I read a property? e.g.

var vector = {x: 2, y: 3}
var length = Math.sqrt(vector.x*vector.c + vector.y*vector.y)

length will be NaN. I don't want to get difficult to find bugs in my code just because of a typo. What's the best way to deal with that? I could add a get function to the prototype of Object and then write e.g. vector.get("x") instead of vector.x. But I want the undefined checks to be done only in the debugging phase and automatically removed in the finished code.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Tesseract
  • 8,049
  • 2
  • 20
  • 37
  • 1
    Not typoing would be a good start :p Kidding, everyone makes typos. However, I don't think it's worth completely rewriting how JavaScript works just to catch them more easily. – Niet the Dark Absol Jan 19 '13 at 06:26
  • try asserts start here (http://stackoverflow.com/questions/6693405/assertive-programming-with-javascript), so you can write methods like get() and use asserts inside them – zb' Jan 19 '13 at 06:26
  • Why don't you use typeof function. Check against undefined. – Murtaza Khursheed Hussain Jan 19 '13 at 06:30
  • `try{...}catch(err){...}`?? – Derek 朕會功夫 Jan 19 '13 at 06:31
  • I don't want to manually add a typeof check everytime I read a property. Isn't there some browser plugin that can help me? For setting properties there is Object.seal which in combination with "use strict" gives me an error if I accidentially try to change a non existing property, but there is no corresponding functionality for getting undefined properties. – Tesseract Jan 19 '13 at 07:13
  • What you seek is called [unit testing](http://en.wikipedia.org/wiki/Unit_testing). In this case, you would test that you get a valid (i.e. correct or expected) value for `length` for all possible values of `x` and `y`. It's impossible to prevent coding errors and still have a usefully functioning environment. – RobG Jan 19 '13 at 07:31

0 Answers0