Use multiple names with distinct functions in one variable

3

See these variable declarations:

var level = 0;
var atual_sequence = 0;

Could I put them together like this?:

var level, atual_sequence = 0;

Would one affect the functionality of the other?

    
asked by anonymous 06.04.2015 / 20:43

2 answers

3

The first question you should ask yourself is: what advantage does it take to take a variable name to do two different things?

In general the answer is none or else it is just to type a few characters less, which would be a very questionable advantage. So it's always better to give more readability, make clear what the intent of each variable is. Not only do you use separate names for each thing, it's giving meaningful names to what you're saving in it.

If the question is whether to declare the variables (in plurarl) on the same line or not, it depends a lot on the case, it's usually a style question but in general it's best to have each statement on each line:

var var1 = 0;
var var2 = 1;

It's not so much better then

var var1 = 0, var2 = 1;

But in longer names, in larger lists, it may become less readable. You can also do this:

var var1 = 0,
    var2 = 1;

But there is not much gain. And there can be drawbacks if you need to change the list of variables later as it creates an exception in the syntax linearity.

Care should be taken especially when both have the same value. There is a temptation to do this:

var var1 = var2 = 0;

This probably does not do what is expected. The variable var1 will have local scope and will be worth 0. The variable var2 will also be worth 0 but its scope will be global and not local, as many may assume.

You should also be careful if you do

var var1, var2 = 0;

Only var2 will have value 0, var1 will not have value set.

So it would affect functionality and even if it's what you want, which is unlikely, it's not recommended because it does not give clear indication of intent.

Documentation .

    
06.04.2015 / 21:10
2

No , the comma ( , ) does not join the variables, this is just a way of defining them without writing as much, using var x, y; and var x; var y; / p>

For example:

var x = 1, y =2;
console.log(x, y);//Vai mostrar duas variáveis do tipo 'integer' assim: "1, 2"

The situation with line break:

var x = 1,
    y =2;

console.log(x, y);//Vai mostrar duas variáveis do tipo 'int' assim: "1, 2"

The isolated situation, ie each variable with its own var :

var x = 1;
var y =2;

console.log(x, y);//Vai imprimir isto "1, 2"

In all cases we will have the same result, if you want two variables together in a string, you will have to do something like:

var x = 1, y =2;

var z = '' + x + '' + y;
console.log(z);//Vai mostrar uma variável do tipo 'string' assim: "12"

You can also use array to have all data in a "local" (it will depend on your need) and after that use join :

var x = [1, 2];

console.log(x.join(""));//Vai imprimir isto "12"
    
06.04.2015 / 21:13