最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Local variable vs parameter - Stack Overflow

programmeradmin1浏览0评论
function doIt(param) {
   var localVar = param;
   //do lots of stuff with localVar
}

function doIt(param) {
   //do lots of stuff with param
}

Is there any difference in terms of efficiency between the code above?

function doIt(param) {
   var localVar = param;
   //do lots of stuff with localVar
}

function doIt(param) {
   //do lots of stuff with param
}

Is there any difference in terms of efficiency between the code above?

Share Improve this question edited Jun 16, 2010 at 23:00 Daniel Vassallo 344k72 gold badges512 silver badges446 bronze badges asked Jun 16, 2010 at 22:52 DLSDLS 5,4918 gold badges39 silver badges52 bronze badges 1
  • Try this simple benchmark. If you find a difference (I get interesting results on Firefox and Opera) IMO it will be negligible anyway. – Christian C. Salvadó Commented Jun 16, 2010 at 23:11
Add a comment  | 

3 Answers 3

Reset to default 12

There is no difference. A parameter is just a local variable which is initialized with the passed argument at invokation time.

However, if you are going to change the value of your variable, it is often considered a good practice to leave parameter variables unaltered, simply for readability and maintainability reasons.

yes, there is one very significant difference if your parameter variable holds the value of an object. If your parameter variable holds the value of an object and then you modify your parameter variable objects anywhere in passed function then it's value will get changed everywhere because while passing object as a parameter in javascript it gets passed by reference and not by value.

Please look at following code snippet to understand what I mean

function someTask (paramter) {
    //some long task
    paramter.color = 'Red';
    //some other task
}

function main() {

    let fruit = {
        name: 'Mango',
        color: 'Yellow'
    }
    someTask(fruit)
    console.log(fruit)
}


main()

//Outputs: { name: 'Mango', color: 'Red' }

param variable is already a local variable so the only difference between those two code snippets is that the first one creates useless copy of param variable.

发布评论

评论列表(0)

  1. 暂无评论