Welcome to WebmasterWorld Guest from 50.19.34.234

Forum Moderators: open

Message Too Old, No Replies

Question - declaring and initializing a set of variables all at once.

     

nelsonm

3:31 pm on Sep 18, 2012 (gmt 0)

5+ Year Member



hi all,

In example 1, I know i can declare and initialize a set of variables like this:
var SubTotal = 0.00, Tax = 0.00, SurCharge = 0.00, Total = 0.00;

In example 2, I know this works at initializing the same set all at once:
var SubTotal = TaxRate = SalesTax = SurCharge = SalesTotal = 0.00;


Questions:
1. Am i correct in that while example 2 is initializing all variables at once, only the first variable is being declared and not all?
2. Is Example 1 the only proper way to declare and initialize all at once?

thanks.

Fotiman

5:09 pm on Sep 18, 2012 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



Example 2 is not declaring TaxRate, SalesTax, SurCharge, or SalesTotal, so those will all implicitly be declared in the global scope (generally best to avoid doing that).
Example 1 is generally going to be a better way, and in fact you could always do something like this:


var SubTotal = 0.00, // COMMENT ABOUT SUBTOTAL
TaxRate = 0.00, // COMMENT ABOUT TAXRATE
SalesTax = 0.00, // COMMENT ABOUT SALESTAX
SurCharge = 0.00, // COMMENT ABOUT SURCHARGE
SalesTotal = 0.00; // COMMENT ABOUT SALESTOTAL

The benefit to this layout is that it's more obvious what each is being initialized to. In addition, you can include comments about each variable.

Fotiman

5:11 pm on Sep 18, 2012 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



Note that if you wanted to, you could do something like this, though it's longer, and I think less obvious so I wouldn't recommend it:

var SubTotal = 0.00, // COMMENT ABOUT SUBTOTAL
TaxRate = SubTotal, // COMMENT ABOUT TAXRATE
SalesTax = TaxRate, // COMMENT ABOUT SALESTAX
SurCharge = SalesTax, // COMMENT ABOUT SURCHARGE
SalesTotal = SurCharge; // COMMENT ABOUT SALESTOTAL

nelsonm

5:47 pm on Sep 18, 2012 (gmt 0)

5+ Year Member



thanks Fotiman...

I'll stick with example 1. Btw, i already use your example to allow for comments.
 

Featured Threads

Hot Threads This Week

Hot Threads This Month