Skip to content

Instantly share code, notes, and snippets.

@cod3beat
Created May 17, 2013 17:01
Show Gist options
  • Save cod3beat/5600464 to your computer and use it in GitHub Desktop.
Save cod3beat/5600464 to your computer and use it in GitHub Desktop.
Perbedaan antara function expression dan function declaration
// *********************** SYNTAX *************************
/**
* Function Declaration.
*
* Nama pada tubuh fungsi itu wajib sifatnya
*/
function deklarasi(){
}
/**
* Function Expression
*
* Nama pada tubuh function itu sifatnya opsional.
*/
var ekspresi = function (){
}
// ini sama saja
var ekspresi2 = function ekspresi2(){
}
/**
* Bedanya?
* Function Expression itu adalah bagian dari sebuah `assignment`, sementara function declaration itu bukan.
*/
// ***************************** HOISTING ************************************
/**
* Declaration selalu di-parse terlebih dahulu bila dibandingkan dengan Expression.
*/
boo(); // BOOOO
function boo(){
console.log("BOOOO");
}
too(); // Exception: too is not a function
var too = function() {
console.log("TOOOO");
}
// ************************** SCOPE *****************************************
/**
* Pada function expression, nama dari fungsi yang berada pada tubuh fungsi, hanya dapat
* diakses di dalam fungsi, bukan di luar fungsi
*/
var satu = function one(){
console.log(typeof one); // -- bisa diakses dari dalam fungsi
}
console.log(typeof one); // undefined -- ketika hendak diakses diluar fungsi
satu(); // function -- `satu` bisa diakses diluar fungsi
/**
* Sementara function declaration tidak mengalami nasib seperti di atas
*/
console.log(typeof one); // function -- ingat tentang hoisting?
function one(){
console.log(typeof one);
}
one(); // function
@ahliwebcom
Copy link

Great

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment