'inverting object boolean property with ! vs =false , Is there any difference?
I am trying to make tic tac toe game in vanilla javascript. If I use ! to flip the value of object boolean property , it is changed to what it is defined in global memory object (as soon as it is out of its execution context), however If I flip by using = equal sign, it stays same. aren't they both doing same thing(flipping value)?? Any explanation would be appreciated. Here's my code.
// we need an object for storing the state of our game.
const game = {
xTurn: true,
xState: [],
oState: [],
winningStates: [
// Rows
['0', '1', '2'],
['3', '4', '5'],
['6', '7', '8'],
// Columns
['0', '3', '6'],
['1', '4', '7'],
['2', '5', '8'],
// Diagonal
['0', '4', '8'],
['2', '4', '6']
]
}
document.addEventListener('click',e=>{
const target = e.target;
console.log('initializing code')
const isCell = target.classList.contains('grid-cell')
const isDisabled = target.classList.contains('disabled');
if(isCell && !isDisabled){
const cellValue = target.dataset.value;
if(game.xTurn){
game.xState.push(cellValue)
}else{
game.oState.push(cellValue)
}
target.classList.add('disabled')
target.classList.add(game.xTurn ? 'x' : 'o')
// if(game.xTurn){
// target.classList.add('x')
// }else{
// target.classList.add('o')
// }
console.log(game.xTurn)
game.xTurn = !game.xTurn;
// game.xTurn = false;
console.log(game.xTurn)
}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|