Skip to content

Latest commit

 

History

History
62 lines (45 loc) · 928 Bytes

67.if.md

File metadata and controls

62 lines (45 loc) · 928 Bytes

67. if

Problem

https://bigfrontend.dev/quiz/if

Problem Description

What does the code snippet below output by console.log?

if (true) {
  function foo() {
    console.log('BFE');
  }
}
if (false) {
  function bar() {
    console.log('dev');
  }
}

foo();
bar();

Answer

if (true) {
  function foo() {
    console.log('BFE');
  }
}
if (false) {
  function bar() {
    console.log('dev');
  }
}

// In Chrome and Firefox:
foo(); // 'BFE'
bar(); // Error

// In Safari:
foo(); // 'BFE'
bar(); // 'dev'

Explanation

When we define a function within an if statement, the result varies on browsers. In Chrome and Firefox, only the name of the function is hoisted, whereas in Safari, the function is hoisted.

Reference

Conditionally created functions