Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript variable empty declaration or object

I know i'm most probably nitpicking but... i have the following code:

var book;
var i=0;

i = 300;    
book = new CBook();
book.Title = "blahblah";
book.Contents = "lalalala";


function CBook() {
    this.Title = "";
    this.Contents = "";
}

now my question is:

would it be better to have

var book = {};

instead of

var book;

in the first version typeof(book) returns undefined before the assignment book = new CBook();

thanks in advance

like image 911
MirrorMirror Avatar asked Jan 28 '26 12:01

MirrorMirror


2 Answers

would it be better to have

var book = {};

No, for a couple of reasons:

  1. You'd be creating an object just to throw it away when you did book = new Book(...) later. (Of course, a really good JavaScript engine might realize that and optimize it out. But still...)

  2. If you use lint tools, you'd be actively preventing them from warning you that you attempt to use book before you (properly) initialize it.

  3. If for some reason you had logic in your code that needed to check whether you'd assigned a book yet, you'd lose the ability to do that. By leaving the variable with its default undefined value, that check can be if (!book) { /* Not assigned yet */ }. (Of course, naive lint tools may warn you about that, too.)

#2 goes for the = 0 in var i = 0; as well.

But if you feel strongly about initializing book at the declaration, null would probably be a better choice.

like image 189
T.J. Crowder Avatar answered Jan 31 '26 02:01

T.J. Crowder


A variable should be declared closest to its first use. So, if I were you, I would change to:

var book = new CBook();

Also, I would pass parameters to CBook and use it as a constructor:

var book = new CBook("blahblah", "lalalala");

function CBook(title, contents) {
   this.title = title;
   this.contents = contents;
}
like image 24
Wand Maker Avatar answered Jan 31 '26 03:01

Wand Maker