What is the most efficient way to declare functions in Javascript?

后端 未结 3 1719
名媛妹妹
名媛妹妹 2021-02-14 15:25

I have always learned that to declare a function in javascript you should do something like:

function myfunction(fruit){
    alert(\'I like \' + fruit + \'!\');
         


        
3条回答
  •  耶瑟儿~
    2021-02-14 15:50

    Using const makes it so that function variable (or constant in this case) can't be re-assigned to something else. So the function can't be modified.

    Using let restricts the scope of the function to the block it was defined in, versus var which restricts the scope of the function to the execution context. As defined on MDN:

    The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.

    For example, using let inside a for loop would restrict that variable to the for loop.

    As for efficiency, I don't see how any of these could impact performance, but there could be nuances that I am unaware of. I doubt anyone would ever see any noticeable difference in performance.

提交回复
热议问题