Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

boolean does not change in function JavaScript

I have the following code:

const ships = (length) => {
  isSunk = false
  console.log('BEFORE: ' + isSunk)
  const shipSize = length
  let hits = []
  const hitLocation = location => {
    hits.push(location);
    isSunk = true;
    console.log('INSIDE: ' + isSunk)
  }
  console.log('AFTER: ' + isSunk)
  return {
    isSunk,
    hitLocation,
    hits,
    shipSize
  }
}

const two = ships(2)
two.hitLocation(1)
two.hitLocation(2)
console.log('FINAL: ' + two.isSunk)
console.log('HITS: ' + two.hits)

Is there a reason why isSunk is not saved as true when I call it in the end?

Is it due to the nested functions?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you set the boolean into the object, it is that value. It is not a reference to the variable. So when you change the variable, the value you saved inside of the object that you returned is not updated.

You can use a function to get the value

const ships = (length) => {
  isSunk = false
  console.log('BEFORE: ' + isSunk)
  const shipSize = length
  let hits = []
  const hitLocation = location => {
    hits.push(location);
    isSunk = true;
    console.log('INSIDE: ' + isSunk)
  }
  console.log('AFTER: ' + isSunk)
  return {
    isSunk: () => isSunk,
    hitLocation,
    hits,
    shipSize
  }
}

const two = ships(2)
two.hitLocation(1)
two.hitLocation(2)
console.log('FINAL: ' + two.isSunk())

Other option is to use a class.

class Ship {

    hits = [];
    
    constructor(length) {
        this.shipSize = length;
    }
    
    get isSunk() {
        return this.hits.length === this.shipSize;
    }
    
    hitLocation (location) {
      this.hits.push(location);
      console.log('INSIDE: ' + this.isSunk)
    }
    
}


const two = new Ship(2)
two.hitLocation(1)
two.hitLocation(2)
console.log('FINAL: ' + two.isSunk)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading