2

Can you explain this?

var guessWhat = function(){ console.log('Print this!!!'); };
function guessWhat(){ console.log('Print that???'); }
guessWhat();

// output: Print this!!!

Both are declared on the global scope. Why is the the second line not overriding the first? Is the second function lost in limbo?

Orr Siloni
  • 1,268
  • 10
  • 21

1 Answers1

4
function guessWhat(){ console.log('Print that???'); } // declaration

This is a function declaration, it is defined before any code is executed.

var guessWhat = function(){ console.log('Print this!!!'); }; // literal

This is a function literal, it is defined at run-time.

so, the function definition gets loaded first (before any code), and the function literal afterwards, which overrides the first definition, hence this behaviour.

Read more here.

Community
  • 1
  • 1
Akshay Arora
  • 1,953
  • 1
  • 14
  • 30