1

So I am basically trying to change the variable "status" when I execute the code below.

const Ship = (length) => {
  let status = "good"
  let array = []

  for (let i = 1; i <= length; i++) {
    array.push(i)
  }

  const hit = (number) => {
    if (!number) {
      return array
    }
    array[number - 1] = number + 10
    status = "bad"
  }

  return {
    length,
    hit,
    array,
    status
  }
}

const ships = Ship(2)

console.log(ships.status) //initial status
console.log(ships.array) //initial array
ships.hit(1)
console.log(ships.array) //modified array
console.log(ships.status) //not modified status

It should work,since the array gets modified, but for some reason it doesn't. I want to know WHY it doesn't work, not a work around.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 1
    Changing the local variable `status` won't change the `status` property on the object. The [value of the variable will be used](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) when making the object, not a reference to it. You need to construct the object and change the property of it in `hit` or make `hit` a normal function and change `this.status`. This might even be a good use for a `class`. – VLAZ Aug 01 '21 at 16:05

2 Answers2

0

You declare the hit function but didn't run it,

  const hit = (number) => {
    if (!number) {
      return array
    }
    array[number - 1] = number + 10
    status = "bad"
  }
  
  hit(number)   <---
Mike
  • 56
  • 1
  • 9
0

You're getting a copy of the status variable in function scope via closure. I would suggest using class semantics for your usecase

class Ship {
    constructor(length) {
        this.array = []
        this.status = "good"
        
        for (let i = 1; i <= length; i++) {
            this.array.push(i)
        }
    }

    hit = (number) => {
        if (!number) {
          return this.array
        }
        this.array[number - 1] = number + 10
        this.status = "bad"
    }
}
hmble
  • 16
  • 3