Mohamed Hegazy
Mohamed Hegazy

Reputation: 273

what does it mean when a variable is declared with 3 different names separated by a comma in JavaScript?

I have come accross this code where a variable was declared like this

var ctr = arra1.length, temp, index; 

here is the full code if it helps:

function shuffle(arra1) {  
    var ctr = arra1.length, temp, index;  

// While there are elements in the array  
    while (ctr > 0) {  
// Pick a random index  
        index = Math.floor(Math.random() * ctr);  
// Decrease ctr by 1  
        ctr--;  
// And swap the last element with it  
        temp = arra1[ctr];  
        arra1[ctr] = arra1[index];  
        arra1[index] = temp;  
    }  
    return arra1;  
}  
var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];  
console.log(shuffle(myArray)); 

Upvotes: 1

Views: 110

Answers (3)

Dexter
Dexter

Reputation: 815

It's not three separate names, it's three separate variables. When doing variable declarations, it's proper to declare them in a single statement, for readability purposes. The two after the first are simply not being defined, so there's no equal sign, but you could define them there, too:

var a = 1, b = 2, c = 3;

Doing so in a function sets a local scope to prevent accessing global variables with the same name before they have been defined.

Upvotes: 1

j08691
j08691

Reputation: 207943

var ctr = arra1.length, temp, index;  

is equivalent to:

var ctr = arra1.length;
var temp;
var index;

It's just a way to consolidate the code. In this example, the ctr variable is being initialized with a value, in this case the length of arra1.

Upvotes: 2

Aracthor
Aracthor

Reputation: 5917

It is just another way to declare many variables, but initializing only one of them.

This code line is equivalent to the following:

var ctr = arra1.length;
var temp;
var index;  

Upvotes: 5

Related Questions