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

Redefining a local variable with var in JavaScript - Stack Overflow

programmeradmin5浏览0评论

I have a rather general question regarding JavaScript and local variables. My question is what is the difference between the following and if there is any:

function bla
{
    var a = 2;   // local variable
    a = 3;       // the local variable a gets a new value

    // Would do the following line anything different 
    // (than simply asigning this value?)
    var a = 4;
}

I suppose I won't get two local variables named a. In other languages this is even an error. So is there any use for this?

I have a rather general question regarding JavaScript and local variables. My question is what is the difference between the following and if there is any:

function bla
{
    var a = 2;   // local variable
    a = 3;       // the local variable a gets a new value

    // Would do the following line anything different 
    // (than simply asigning this value?)
    var a = 4;
}

I suppose I won't get two local variables named a. In other languages this is even an error. So is there any use for this?

Share Improve this question asked Feb 16, 2012 at 12:47 SentropieSentropie 2591 gold badge4 silver badges14 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 18

Any use of var within a function is hoisted. Subsequent uses on the same variable in the same scope have no effect.

It has exactly the same meaning as a = 4; alone.

发布评论

评论列表(0)

  1. 暂无评论