[Javascript]Function Expression vs Function Declaration

Suyeon·2020년 8월 19일
0

Javascript

목록 보기
1/31
post-thumbnail

❗️ Defferences

Function Declaration

  • A Function Declaration can be called earlier than it is defined.
  • When JavaScript prepares to run the script, it first looks for global Function Declarations in it and creates the functions - hoisting
sayHi("John"); // Hello, John 

function sayHi(name) {
  alert( `Hello, ${name}` );
}
  • When a Function Declaration is within a code block, it’s visible everywhere inside that block. But not outside of it - Block Scope
let age = prompt("What is your age?", 18);

// conditionally declare a function
if (age < 18) {

  function welcome() {
    alert("Hello!");
  }

} else {

  function welcome() {
    alert("Greetings!");
  }
}

// ...use it later
welcome(); // Error: welcome is not defined

Function Expresstion

  • A Function Expression is created when the execution reaches it - Prevent to pollute the global scope
sayHi("John"); // error!

let sayHi = function(name) {  // (*) no magic any more
  alert( `Hello, ${name}` );
};
profile
Hello World.

0개의 댓글