javascript - var functionName = function() {} vs function functionName() {} -
i've started maintaining else's javascript code. i'm fixing bugs, adding features , trying tidy code , make more consistent.
the previous developer uses 2 ways of declaring functions , can't work out if there reason behind or not.
the 2 ways are:
var functionone = function() { // code }; function functiontwo() { // code } what reasons using these 2 different methods , pros , cons of each? there can done 1 method can't done other?
the difference functionone function expression , defined when line reached, whereas functiontwo function declaration , defined surrounding function or script executed (due hoisting).
for example, function expression:
// typeerror: undefined not function functionone(); var functionone = function() { console.log("hello!"); }; and, function declaration:
// outputs: "hello!" functiontwo(); function functiontwo() { console.log("hello!"); } this means can't conditionally define functions using function declarations:
if (test) { // error or misbehavior function functionthree() { dosomething(); } } the above defines functionthree irrespective of test's value — unless use strict in effect, in case raises error.
Comments
Post a Comment