Home  >  Q&A  >  body text

var and function keywords

var a = 1;

function a()
{
    console.log(a);
};
a();

These lines of JS code will report an error when running, but what is the reason? Ask God to explain

仅有的幸福仅有的幸福2711 days ago460

reply all(5)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-19 10:31:08

    Function is the first citizen of JavaScript, so there is function promotion here. The final implementation of the above code has the same effect as the following

    function a()
    {
        console.log(a);
    };
    var a = 1;
    a();
    

    This will cause the original function name to be overwritten.

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:31:08

    The identifier is repeated. You have declared a as a variable

    reply
    0
  • 高洛峰

    高洛峰2017-05-19 10:31:08

    First of all, let’s talk about js. When you see var a = 1, you need to parse it in two steps. First, raise var a to the top of the current scope, and then parse it downwards until a = 1 and start assigning values.

    This is the problem of variables and functions having the same name. Simply put, the js engine parsing order is as follows
    1. Variable and function declarations are promoted to the top of the current scope → var a ↑ and `function a()
    {

    console.log(a);

    }`
    2. Then parse the remaining code `a=1;
    a()`,

    reply
    0
  • 怪我咯

    怪我咯2017-05-19 10:31:08

    This is because the function declaration will be in advance

    var a = 1;
    function a()
    {
        console.log(a);
    };
    a();

    1) Function declaration will be at the top
    2) Variable declaration will also be at the top
    3) Function declaration will be at the top than variable declaration: (function is above the variable)
    4) Variables and assignment statements are written together. When parsed by the js engine, they will be It is divided into two parts: declaration and assignment. The declaration is placed at the top and the assignment is kept at the original position. 5) Declared variables will not be declared repeatedly.

    will be equivalent to the following

    var a = function ()
    {
        console.log(a);
    };
    var a = 1;
    
    a();
    Hope it helps you~

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-19 10:31:08

    Many people have mentioned that it is a problem of variable promotion, but the explanation is not quite right. varImprovement is done in parts, and functions are improved as a whole. FYI

    So it should look like this:

    var a;
    function a ()
    {
        console.log(a);
    };
    a = 1;
    a();

    reply
    0
  • Cancelreply