What is the difference between a function expression vs declaration in JavaScript? -
this question has answer here:
what difference between following lines of code?
//function declaration function foo() { return 5; } //anonymous function expression var foo = function() { return 5; } //named function expression var foo = function foo() { return 5; } - what named/anonymous function expression?
- what declared function?
- how browsers deal these constructs differently?
what responses similar question (var functionname = function() {} vs function functionname() {}) not right?
they're similar. how call them same.the difference lies in how browser loads them execution context.
function declarations load before code executed.
function expressions load when interpreter reaches line of code.
so if try call function expression before it's loaded, you'll error! if call function declaration instead, it'll work, because no code can called until declarations loaded.
example: function expression
alert(foo()); // error! foo wasn't loaded yet var foo = function() { return 5; } example: function declaration
alert(foo()); // alerts 5. declarations loaded before code can run. function foo() { return 5; }
second part of question:
var foo = function foo() { return 5; } same other two. it's line of code used cause error in safari, though no longer does.
Comments
Post a Comment