Reputation: 9
I am trying to use conditional logic inside a JavaScript class constructor.
Context: I am creating a 2d grid in a double for loop, with each cell having a property of North, South, East, and West. To keep in bounds of the 2d Grid, I am trying to only create a cell that has N,S,E properties, if that cell lay on the edge with col equal to 0.
For a 4x4 grid, I try to build this item and I keep getting the error, "Uncaught SyntaxError: Unexpected token '!='". So I believe the issue is just with my poor knowledge of Javascript Syntax. Any Suggestions?
class Cell {
constructor(row,col){
this.visited = false;
this.row = row;
this.col = col;
this.edges = {
if(row!=0){
north:1,
},
if(row!=3)){
south:1,
},
if(col!=0)){
west:1,
},
if(col!=3)){
east:1,
},
}
}
}
Upvotes: 1
Views: 3003
Reputation: 9135
This syntax wont work. Create an empty object and add property afterwards.
class Cell {
constructor(row,col){
this.visited = false;
this.row = row;
this.col = col;
this.edges = {};
if(row!=0){
this.edges.north = 1;
}
if(row!=3)){
this.edges.south = 1;
}
if(col!=0)){
this.edges.west = 1;
}
if(col!=3)){
this.edges.east = 1;
}
}
}
Upvotes: 1
Reputation: 83547
You cannot use if
statements inside of an object literal. Instead, you should use the if statement to assign to the field of the object directly:
this.edges = {};
if (row != 0) {
this.edges.north = 1;
}
// etc.
Upvotes: 1
Reputation: 17654
You can use the ternary operator
class Cell {
constructor(row, col) {
this.visited = false;
this.row = row;
this.col = col;
this.edges = {
north: row !== 0 ? 1 : null,
south: row !== 3 ? 1 : null,
west: col !== 0 ? 1 : null,
east: col !== 3 ? 1 : null
};
}
}
Upvotes: 1
Reputation: 15166
I would use with ternary operators instead of if
statements there. About Conditional (ternary) operator please read as below:
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.
For example this one is a good syntax for your case:
const row = 2;
const col = 3;
const edges = {
north: row != 0 ? 1 : 0,
south: row != 3 ? 1 : 0,
west: col != 0 ? 1 : 0,
east: col != 3 ? 1 : 0
};
console.log(edges);
I hope that helps!
Upvotes: 2