React - help with this toggle function

I am doing this React course where we are doing a movie app, we have an object with dummy info representing the movies database.

The instructor created a toggle function to change the state of a like button. But because the function does not have an if statement, I am failing to see how this function is toggling the class. This is how the function looks like:

handleLike = (movie)  => {
    const movies = [...this.state.movies]
    const index = movies.indexOf(movie)
    movies[index] = {...movies[index]}
    // I understand everything until this point
    // How is this toggling anything?
    movies[index].liked = !movies[index].liked
    this.setState({ movies })

To give you more context, the liked key is originally undefined in each object, you can see that here:

{ => (
              <tr key={movie._id}>
                  <Like liked={movie.liked} onToggleClass={() => this.handleLike(movie)} />
                  <button onClick={() => this.handleDelete(movie)} className="btn btn-danger btn-sm">

So with the toggle function all I see is that the liked key is being set to true with the ! operator. But when I click again, how does it go back to be undefined so it can be false?

The Like component looks like this just in case you need it for more context:

const Like = (props) => {
  let classes ="btn fa fa-heart";
  if(!props.liked) classes += "-o";
  return (
    <i onClick={() => props.onToggleClass(}

Umm I think I understand now, with a much simpler example

const obj = [
  	title: 'Terminator',
    liked: undefined

document.querySelector('.btn').addEventListener('click', () => {
  obj.liked = !obj.liked

Basically what’s going here is that since the value of the liked key is originally a falsy value, by using the ! operator we change the liked key to a truthy value, and then when it’s true and we click again, it turns into a falsy value again due to the ! operator, and so on and so forth.

Looks like I answered my own question. Please feel free to correct me if I’m wrong here or if I’m missing something.

1 Like