2

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

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

... and also loose a simple way to check, if the book object exists before it's created.
2

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;
}

9 Comments

Not necessary at all, all variable declarations are hoisted. Hence if you do this in the middle of the code, var book; is executed at the beginning of the code anayway.
Hoisting happens within JS engine, the recommendation is for code readability.
i like declaring all variables in the beginning of every function
@WandMaker I think recommendations depend on the recommendator ; ).
@WandMaker: Indeed. Such as putting all variable declarations at the beginning of the scope in which they're used. See? Your "readable" and my "readable" don't match. :-) Of course, in practice, functions should be so short that "at the beginning of the function" is "close to first use" and the issue goes away. (Along with a lot of other ones.)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.