Why is the if-else branch not firing correctly?

  • 0
    I can't understand why else in this code is triggered first, and then if?
    JavaScript Anonymous, Apr 30, 2020

  • 4 Answers
  • 0
    Because you compare the entered name with each of the array and at each iteration if the name does not match, print a message.

  • 0
    Well, for example, I'm Brad Pitt. I enter this means: 'Pitt'. The following happens in the code:

    - 'Pitt' === 'Kutcher'?

    - No. alert ('No results found for your request')

    - 'Pitt' === 'Pitt'?

    - Yes. alert ('with a bunch of uninteresting information')
    Ruby Jefferson

  • 0
    Because your else block is triggered at each iteration of the loop.


  • 0
    const data = [
    firstName: 'Ashton',
    lastName: 'Kutcher',
    age: 40
    firstName: 'Bredley',
    lastName: 'Pitt',
    age: 54
    firstName: 'Hannah',
    lastName: 'Dakota',
    age: 24

    let pr = prompt('Пользователь, введи свою фамилию!');
    let result = pr.slice(0, 1).toUpperCase() + pr.slice(1).toLowerCase();
    const user = data.find(user => result === user.lastName)
    alert(user != null ? `User name: ${user.firstName} ${user.lastName}`:`No results found for your request`)
    Myles Woods

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!