Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to not assign a new object to a variable?

Tags:

javascript

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<links.length;i++){
    new objectName(links[i]);
}

And again, I won't be accessing it, so there's no need for a variable to reference it.

like image 936
Jeff Avatar asked Apr 07 '10 17:04

Jeff


People also ask

What happens when you assign a value to a variable that has not been declared?

Repeated and Omitted Declarations If you assign a value to a variable that you have not declared with var , JavaScript implicitly declares that variable for you. Note, however, that implicitly declared variables are always created as global variables, even if they are used within the body of a function.

What happens when you assign a value to a variable that has not been declared it will automatically become a global variable?

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. This code example will declare a global variable carName , even if the value is assigned inside a function.

Can we create object without reference variable in Java?

Simply declaring a reference variable does not create an object. For that, you need to use the new operator , as described in the next section. You must assign an object to originOne before you use it in your code.

What happens when you assign an object to another object?

what happens when you assign one object to another object ?? It assigns the reference of the Object. In other words, both variables 'point' to the same Object. For example/ int [] a = new int[5]; int [] b = a; b and a now 'point' to the same array.


2 Answers

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.

like image 72
Jon Skeet Avatar answered Oct 22 '22 22:10

Jon Skeet


That’s absolutely fine if you don’t need to use it again.

like image 36
Gumbo Avatar answered Oct 23 '22 00:10

Gumbo