Reputation: 1373
I'd like to know what kind of syntax the line below is called.
var that = {}, first, last;
Note: I found a post on this site about this question, but they said [ ] has to be added around the variables on the right handside to make it an array. But the code below does work.
Code:
var LinkedList = function(e){
var that = {}, first, last;
that.push = function(value){
var node = new Node(value);
if(first == null){
first = last = node;
}else{
last.next = node;
last = node;
}
};
that.pop = function(){
var value = first;
first = first.next;
return value;
};
that.remove = function(index) {
var i = 0;
var current = first, previous;
if(index === 0){
//handle special case - first node
first = current.next;
}else{
while(i++ < index){
//set previous to first node
previous = current;
//set current to the next one
current = current.next
}
//skip to the next node
previous.next = current.next;
}
return current.value;
};
var Node = function(value){
this.value = value;
var next = {};
};
return that;
};
Upvotes: 1
Views: 70
Reputation: 239693
var that = {}, first, last;
is similar to
var that = {};
var first;
var last;
We are initializing that
with an empty object, whereas first
and last
are uninitialized. So they will have the default value undefined
.
JavaScript assigns values to the variables declared in a single statement from left to right. So, the following
var that = {}, first, last = that;
console.log(that, first, last);
will print
{} undefined {}
where as
var that = last, first, last = 1;
console.log(that, first, last);
would print
undefined undefined 1
Because, by the time that
is assigned last
, the value of last
is not defined yet. So, it will be undefined
. That is why that
is undefined
.
Upvotes: 3
Reputation: 36458
It's just a shorthand way to create multiple variables. It might be more clear if written as:
var that = {},
first,
last;
And is equivalent to:
var that = {};
var first;
var last;
Upvotes: 1