Can anyone help me understand this line of javasript code?

Asked

Viewed 46 times

-2

This algorithm is implemented in a book project Use your head! Javascript Programming, of chapter 8 created a naval battle.

Where I couldn’t understand this piece of code.

   if(hit && model.shipsSunk === model.numShips){
      view.displayMessage("you sank all my battkeships, in" + this.guesses + " guesses")
    }

hit:Is a variable that has a true or false value that is returned from a function.

model.shipsSunk: is a property of an object, it has a Number value and it is being incremented by other methods during code execution.

model.numShips: it has a Number value and it and a constant, it is also a property of the same object that shipsSunk is part of.

I don’t understand the logic of if
in comparing hit that is a boolean, Shipssunk and numShips that are Number.
I know we use && for Boolean values, && returns true if both operands are true ; otherwise, returns false.
In case if hit receive a value True as the logical operator && will return me a boolean value if shipShunk is a number and still compare if it is equal to numShips ?
in the book explain that:
-If the hit for true and shipSunk equals numShips the message of the view displayMessage(...) onscreen.
but I couldn’t understand the logic of how the if parole will do it.

  • 2

    model.shipsSunk === model.numShips is true if the numbers are equal, and false if they are different. So you have the operation && between two booleans. It became clearer?

1 answer

-3

The && operator returns true only if the given variables are both true. So he compares whether the hit and the sunken ships are true and then compares it to the number of ships. If everything is satisfied, your message will be printed on the screen

Browser other questions tagged

You are not signed in. Login or sign up in order to post.