I
I
ikislov2020-04-28 19:22:15
JavaScript
ikislov, 2020-04-28 19:22:15

Easy. How does the above code work?

spoiler
function checkAge(age) {
  if (age > 18) {
    return true;
  } else {
    return confirm('А родители разрешили?');
  }
}

let age = prompt('Сколько вам лет?', 18);

if ( checkAge(age) ) {
  alert( 'Доступ получен' );
} else {
  alert( 'Доступ закрыт' );
}

Please explain step by step, I'm completely confused.

1. As I understand it, the first thing that the code executes is line 9 with the declaration of the variable and the prompt call.

2. Then the 11th line if is triggered, this is where the function is called, do I understand correctly?

3 . Next, the function is executed - if the value of the variable age > 18 returns true, the function jumps back to alert on line 12 - "Access granted"

4 . If the function gets false from the age variable, it returns confirm. And here I did not understand how the result of confirm is tied to lines 11-15? How does the if "block" get the value from this confirm to issue the desired alert? Well, in general, did I understand the general principle of work correctly?

PS It feels like I'm making it too difficult for myself to understand the issue, or I'm just stupid and it's really hard to understand. Newbie.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2020-04-28
@ikislov

Can you elaborate a little more:

function checkAge(age) {
  var result; // объявили переменную внутри функции
  if (age > 18) {
    result = true;
  } else {
    result = confirm('А родители разрешили?'); // confirm() вернёт true или false
    // в переменной result теперь либо true либо false
  }

  return result; // в любом случае функция вернёт true или false
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question