Furman - 1 year ago 67

Javascript Question

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`

`queue[0].y`

`j`

`queue[0].y`

`j`

`typeof`

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

Answer Source

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)`

.