Is it bad javascript practice to not assign a newly created object to a variable if you\'re never going to access it?
For example:
for(var i=0;i
It seems like your constructor is doing something else besides creating/initializing an object.
It would be a cleaner solution to implement that extra functionality into a function or method.
Constructors should be used to create and initialize objects.
That’s absolutely fine if you don’t need to use it again. But we need to explain why.
An object can continue to do something, even if you don't have a reference to it (like other suggested, an animation, a listener, etc.)
Who think this is odd, should reflect on the alternatives before say this is not fine:
new objectName().start()
more clear? maybe. But if you always need to call start()
immediately after creation to make the object useful, it is better to include the start()
in the costructor. This way you can't forget to do it.A good Object name can clarify or suggest that the object will do something, after creation.
Examples:
new Baby() is supposed to start to cry, sometimes. And he will live even if you don't tell him to to something.
new AutoRegisteringListener(); Really need to explain what will happen when you create such object? are you really surprised that this listener will register itself to some events?
In my opinion, the point is to think in object-oriented way, instead of thinking only in functional way: objects can have behaviour. This is what they are designed for, among other things.
That’s absolutely fine if you don’t need to use it again.
If you're not accessing it but it's still useful, that suggests that the constructor itself has visible side effects. Generally speaking, that's a bad idea.
What would change if you didn't call the constructor at all?
If your constructor is doing something to the global state, that strikes me as very bad. On the other hand, you could be using it just for the sake of validation - i.e. if the constructor returns without throwing an exception, it's okay. That's not quite so bad, but a separate method for validation would make things a lot clearer if that's the case.
"Is it bad javascript practice to not assign a newly created object to a variable if you're never going to access it?"
I feel it is bad practice to make an assignment that is not needed, and, I would argue, not just for javascript but in general. If there are side-effects you want, getting them from the action of an assignment is bad practice for the simple reason that it would be fairly opaque from a maintenance point of view.
.