justZito
justZito

Reputation: 559

In javascript do you have to init a variable?

Is it require, good practice or a waste of time to initialize a variable? Take a look at instance in this code, is this correct?

var instance = ''
var myArgs = require('optimist').argv,

switch (myArgs._[0]) {
    case 'insult':
        var instance = 'insult'
        console.log(myArgs.n || myArgs.name, 'smells quite badly.');
        break;
    case 'compliment':
        var instance = 'compliment'
        console.log(myArgs.n || myArgs.name, 'is really cool.');
        break;
    default:
        console.log(help);
 }

Upvotes: 0

Views: 70

Answers (3)

Quentin
Quentin

Reputation: 944441

Assigning

If you try to assign to an uninitialised variable then you will create a global. This is bad, don't do this.

If you have enabled strict mode, then you will throw a reference error. This is bad, don't do this.

Reading

If you try to read from an uninitialised variable, you will throw a reference error. This is bad, don't do this.

In short

Always initialise your variables.

Note that JavaScript scope is handled at the function level, not the block level and var statements are hoisted.

It is generally considered good practise to declare your variables only once, and at the top of the function. Remove the var from your instance except for the one you have at the top of your function.

Upvotes: 2

Vinz243
Vinz243

Reputation: 9958

You should not put var twice. Javascript is a dynamic language, so you can create a var with first an int, then a string and then a function. You don't have to say int before.

In your example :

var instance = ''
var myArgs = require('optimist').argv,

switch (myArgs._[0]) {
 case 'insult':
     instance = 'insult'
     console.log(myArgs.n || myArgs.name, 'smells quite badly.');
     break;
 case 'compliment':
     instance = 'compliment'
     console.log(myArgs.n || myArgs.name, 'is really cool.');
     break;
 default:
     console.log(help);

}

Of course, if you want to ensure that your var is a string use typeof. Example:

if(typeof instance !== 'string'){
   alert('should be a string')
}

Upvotes: 0

R. Barzell
R. Barzell

Reputation: 674

In programming languages in general, it's often recommended that you initialize variables so they are set to a known state. This can often help you catch errors.

Having said that, in Javascript, uninitialized variables have the value undefined, which you can check for, so it's doubtful if you will gain much by this -- unless there is a useful default value for that variable.

Upvotes: 0

Related Questions