The Javascript weird world... lol

Another weird question ! lol

In java, it is impossible to create a variable or a method outside the class declaration.

But in Javascript, it is quite possible. I just spent a lot of time looking for the origin of a very strange bug and ended up realizing… that I had misspelled the name of a variable somewhere in my code (apart from a class declaration), which, instead of updating this variable, was creating a new one with the wrong name in the concerned classes.

So, I wonder if there is a way in Javascript to detect the creation of new variables (or methods) in a class during the operation of the program and how to do it?

Maybe we could list the methods and variables present in the constructor and check during the execution of the program that there are no new ones?

something which could be applied in all constructors and be undone (when debugging is finished)

Is it possible?
What do you think about it?

:slight_smile:

In Java requires all variables have to be declared before assigning a value to it so in Java we have

int n; // declaration
n = 42;// assignment 

in JavaScript we don’t need to declare the variable so

n = 42;

is perfectly acceptable and will assign the value 42 to the variable n. If the variable doesn’t exist then it will create it.

It is a similar when creating classes if a method has the statement

this.n = 42;

will create a class field n even if it doesn’t exist.

So a few typos in naming your variables can create a multitude of logical errors that will melt the brain trying to fix.

A logical error is one that

  • does not generate a compiler / interpreter warning, or
  • does not causing the program to halt unexpectedly

Logical errors are the hardest to find and fix :frowning:

The solution is not to find the unexpectedly created variables at runtime but prevent them in the first place.

You might try strict mode to help prevent this.

For large projects that make extensive use of classes I would recommend Typescript, I used this when creating the canvasGUI library.

1 Like

Inside a class block, all code is already in “strict mode”:

Meaning all variables have to be declared before usage.

Moreover inside a class, we can’t declare global variables anyways.
Therefore, if we mistype a global variable name inside a class, the code should just crash!

For regular JS files, always place “use strict” as their 1st statement, so as to force variables to be declared 1st.

1 Like