Furman Furman - 4 months ago 10
Javascript Question

Values concatenating inside if condition

Edit: For the sake of simplicity, consider following code:

var z = {x: 1, y: 1};

console.log(z.x+5 + ' ' + z.y+5);


Why output is (6,15) instead of (6,6)?

Before edit: I have following function:

function findPath(startX, startY, goalX, goalY){
var queue = [],
candidates = [],
path = [];

queue.push({x: startX, y: startY, searchDistance: 0, hasBeenSearched: true});

fillQueue();

function fillQueue(){
setInnerHTML(queue[0].x, queue[0].y, '.');
for(var i=-1; i<=1; i++){
if(queue[0].x + i < 0 || queue[0].x + i > boardHeight - 1){
continue;
}

for(var j=-1; j<=1; j++){

if(queue[0].y + j < 0 || queue[0].y + j > boardWidth - 1){
continue;
}
if(i == 0 && j == 0){
continue;
}
if(cells[queue[0].x + i][queue[0].y + j].type.blockMovement == true || findCell(queue[0].x + i, queue[0].y + j).hasBeenSearched == true){
console.log(queue[0].x + i + ' ' + queue[0].y + j)
continue;
}

if((queue[0].x + i == goalX) && (queue[0].y + j == goalY)){
setInnerHTML(queue[0].x + i, queue[0].y + j, '.');
candidates.push(queue[0]);
candidates.push({x: queue[0].x + i, y: queue[0].y + j, searchDistance: queue[0].searchDistance + 1, hasBeenSearched: true});
//fillPath();
return path;
}

queue.push({x: queue[0].x + i, y: queue[0].y + j, searchDistance: queue[0].searchDistance + 1, hasBeenSearched: true});

}
}

candidates.push(queue.shift());

if(queue.length > 0){
setTimeout(fillQueue, 0);
}else{
return 'no path found';
}

function findCell(x,y){
for(var i=0; i<queue.length; i++){
if(queue[i].x == x && queue[i].y == y){
return queue[i];
}else if(i == queue.length - 1 && (queue[i].x != x || queue[i].y != y)){
return {hasBeenSearched: false};
}
}
}
}
}


It is part of pathfinding algorithm I've been rewriting lately and I have following problem. Inside inner for loop, when this condition
findCell(queue[0].x + i, queue[0].y + j).hasBeenSearched == true
is being checked, values of second parameter
queue[0].y
and
j
are concatenated instead of just being added, while same condition for first parameter works correctly (values there are added). I'm trying to figure that out for several hours now and I have no idea what is going on. Both values
queue[0].y
and
j
are numbers(I checked it by console logging
typeof
them), and should be added just like similiar values in first paremeter. Any help with pointing me out what I did wrong will be appreciated. Thank you in advance.

Codepen link: http://codepen.io/Furmanus/pen/LkXVwO/?editors=0011

Answer

JS expressions are evaluated left-to-right. By the time it reaches that last +, it's evaluating ('6 1' + 5).

Put the last part in parentheses to force it to be evaluated separately: console.log(z.x+5 + ' ' + (z.y+5)).

You can also log multiple things using parentheses, which will avoid this problem: console.log(z.x+5, z.y+5).