Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect use of invalid properties in javascript?

Tags:

javascript

I'm learning Javascript and I wrote the following code:

if (mystring.len > 0) {
    // do stuff
}

I accidentally used .len instead of .length. To my surprise, no error was raised. mystring.len returned undefined and this made the comparison fail but the code kept right on running. I would prefer an actual error to be raised so I can fix the code. Adding "use strict" didn't help, nor did jslint.

I know there are ways to actively check whether or not a property exists, but that's not what I'm looking for. I want Javascript to tell me when I've made a typo in a property name.

Is there a way to cause Javascript to give an error in this case?

like image 362
Graeme Perrow Avatar asked Jan 07 '23 12:01

Graeme Perrow


2 Answers

Nope - that is how JavaScript works and it's incredibly useful. Who is to say that checking len is something that needs fixing? Consider:

if(mystring.len === undefined) {
   mystring.len = "Test";
}

The best you can do is to simply check that the thing is defined before using it:

if(mystring.len !== undefined) {
}

I appreciate the strangeness, and how it doesn't feel robust (having originally come from a C# background) but there isn't a lot you can do unfortunately. The fact that JavaScript is case sensitive makes this even more frustrating. You will learn to live with it though!

If you really really wanted to run some static analysis then you could considering creating a transpiler (e.g. Babel) extension to run this sort of analysis - but it would get really difficult if you ever expected something to be undefined which I find is common place.

edit

Here's a real example that I'd use where undefined is useful. I'm working with a library that needs to move stuff from one location to another. It can't do that unless the original location has been specified, so I might write something like the following, initializing values if I don't have them for some reason:

function update(node) {
   if(node.x === undefined) { node.x = 0; }    
   node.y = node.y || 0; // This is the shorthand way I'd actually write it

   // Do some other stuff
};
like image 192
Ian Avatar answered Jan 26 '23 23:01

Ian


"use strict" (in my experience) is used so that variables that aren't explicitly declared/instantiated that are then referenced will throw errors (else, JS would just make a new var on the fly). So that wouldn't help here.

This sounds like an error that would typically be picked up by a compiler in other languages, but since JS is interpreted, you won't have that kind of explicit error checking unless you're in a beefy IDE. Are you using a text editor or something to write JS?

like image 45
sup bro Avatar answered Jan 26 '23 23:01

sup bro