Мои задачи по Javascript
Случайная задача
Список всех задач

Задача 33

console.log(typeof f);

if (true) {
 console.log(typeof f);
 function f() { }
 console.log(typeof f);
}

console.log( typeof f );
Что выведет консоль?
1
2
3
4
5
6
7
← Задача 32Задача 34 →
Пояснение Современные браузеры выводят: undefined, function, function, function.

Казалось бы, здесь обычное объявление функции (Function Declaration), но hoisting (поднятие) не происходит выше if-условия.

Даже MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function) не рекомендует объявлять функции внутри if, потому что поведение браузеров может разниться:
Functions can be conditionally declared, that is, a function statement can be nested within an if statement, however the results are inconsistent across implementations and therefore this pattern should not be used in production code. For conditional function creation, use function expressions instead.

Кстати, любопытный факт: старая Opera Presto выводит function, function, function, function.



Написать сообщение - отзыв, пожелание и т.п.