Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running function created with two ways in javascript

var a = function(){
    alert("2");
}

function a(){
    alert("1");
}

a();

As above, I declared two functions in different ways. When I run a(), I got 2. Why?

like image 795
mnbvxz Avatar asked Dec 19 '22 02:12

mnbvxz


1 Answers

When you declare a function or variable in JavaScript it gets "hoisted", meaning that the JavaScript interpreter pretends that the variable (a in your case) was declared at the top of the file scope.

When that declaration takes the form function a() ..., the definition of the function is hoisted along with the declaration.

Assignments like a = function ()... don't get hoisted, and so that assignment happens after the function a() ... piece and overrides it.

like image 91
RichieHindle Avatar answered Dec 24 '22 01:12

RichieHindle