Doing some refactoring, I noticed an unusual pattern I’m not familiar with. Properties and variables that do not yet have a value are initiated with undefined
declared explicitly, despite the fact that value-less variables and object properties would evaluate to undefined
anyways:
var foo = undefined;
this.prop = undefined;
Is there a reason to do this?
12
It’s possible the author came from an environment where all variables were required to be initialized when declared. Some code-checking tools will also complain if variables are not initialized before they are used (even if the first use is to assign a value).
3
Given your two examples, I always do the second one, but never the first.
function Foo() {
this.bar = undefined;
....
}
This creates an explicit list of properties available at a glance for maintenance purposes.1 It’s equivalent to declaring public members in class-based object oriented languages:
class Foo:
def __init__(self):
self.bar = null;
Relying on the default undefined
in Javascript is similar to using setattr
to create dynamic properties in Python – you can do it, and it’s the right solution in some rare cases, but it’s not going to help the maintainers.
1I don’t use null
for this, because sometimes null
is a valid value – checking if a property is null
or undefined
tells me if it got initialized at all before being used somewhere.
2