Gregir
Gregir

Reputation: 1574

JavaScript: can a variable have multiple values?

I'm fairly new to JavaScript beyond jQuery, and I was reading up on randomization in a JavaScript array & the shortcomings of using the Array.sort method with a random number. I see the recommendation instead is to use the Fisher-Yates shuffle. In looking at the JavaScript code for this method:

Array.prototype.randomize = function()
{
    var i = this.length, j, temp;
    while ( --i )
    {
        j = Math.floor( Math.random() * (i - 1) );
        temp = this[i];
        this[i] = this[j];
        this[j] = temp;
    }
}

I'm struck by this line:

var i = this.length, j, temp;

What's going on here? Is a variable being given multiple values, or is this shorthand for something?

Upvotes: 1

Views: 1778

Answers (6)

Felix Kling
Felix Kling

Reputation: 816394

The specification defines the variables statement to be the var keyword, followed by a list of variables declarations, separated by a comma:

VariableStatement :
    var VariableDeclarationList ;

VariableDeclarationList :
    VariableDeclaration
    VariableDeclarationList , VariableDeclaration

Note the recursive definition of VariableDeclarationList. It means that an unlimited number of variables declarations can follow a var keyword.

Hence

var foo, bar;

is the same as

var foo;
var bar;

Related question: What is the advantage of initializing multiple javascript variables with the same var keyword?

Upvotes: 1

Lie Ryan
Lie Ryan

Reputation: 64837

It's just multiple declaration of variables in a single line. It's equivalent to this:

var i, j, temp;
i = this.length;

Which is equivalent to this:

var i;
var j;
var temp;
i = this.length;

Upvotes: 1

Geeky Guy
Geeky Guy

Reputation: 9399

You are creating three variables, and only the leftmost will be born with a value - in this case, whatever the value this.length is.

As pointed out by everyone else respondig to you question, it's the same as:

var i = this.length;
var j, temp;

Other languages like Java, C# and Visual Basic allow you to create variables with a similar syntax. I.E.:

I.e.:

// C# and Java
int i = this.length, j, temp;

// which is the same as:
int i = this.length;
int j, temp;

 

' Visual Basic
Dim i = this.length as Integer, j as Integer, temp as Integer

' Which is the same as:
Dim i = this.length as Integer
Dim j as Integer, temp as Integer

Upvotes: 1

user
user

Reputation: 719

No, it's the shorthand for: var i = this.length; var j; var temp;

Upvotes: 2

m_vdbeek
m_vdbeek

Reputation: 3774

var i = this.length, j, temp;

is the same as :

var i = this.length;
var j; // here the value is undefined
var temp; // same, temp has a an undefined value

Upvotes: 2

Jon
Jon

Reputation: 437366

A variable can never have multiple values at the same time.

The code you give is shorthand for

var i = this.length;
var j;
var temp;

Syntax like that above is legal in most programming languages.

Upvotes: 5

Related Questions