Created
May 17, 2013 17:01
-
-
Save cod3beat/5600464 to your computer and use it in GitHub Desktop.
Perbedaan antara function expression dan function declaration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// *********************** 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great