SemicolonExpected SemicolonExpected -4 years ago 114
Javascript Question

Putting conditional statement in class constructor

I'm trying to make a class that has an optional parameter.

Is it possible to add a conditional such as

if(!(degrees === undefined)) {this._items.degree = degrees}


When I try to do this, I get the error "SyntaxError: Unexpected identifier" upon declaring/creating the object.




var element = {
degree = 0;
}

var Radial = function(items, degrees) {
this._items = itemsfunction(); //_items is an element structure the function makes and returns the element
if(!(degrees===undefined)){ //where the error occurs
for(int i = 0; i<this._items.length; i++){
if(!(degrees[i]===undefined)){
this._items[i].degree = degrees[i];
}
else{
this._items[i].degree = 0;
}
}
}
};


The above is my constructor

I declare it as so
radial = new Radial(item, degrees);
and
radial = new Radial(item);
and both return the same error of Unexpected identifier in the console, and the Radial object is not created. When I take out the if conditional, everything works.

What am I doing wrong? I'm new to javascript classes.

Answer Source

Your problem is not with the conditional, it's with the line below:

for(int i = 0; i<this._items.length; i++){
//  ^^^

That needs to be var. Also, the object literal should be

… {
    degree: 0
}; //     ^^^^
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download