Search code examples
javascriptfunctionvararrow-functionslet

Re-declaring arrow function


tried to re-declare an arrow function-- (Check code)

Why is it giving error when var can be redeclared.

I made an arrow function using var then tried re-declaring it using let as var can be redeclared. But why is it giving error?


Solution

  • If you declare a variable with var, you can redeclare a variable with var as many times as you like, but it will error if you redeclare with let or const. With let and const, you can only declare a variable one.

    What you probably meant to do is reassign the variable, which you can do as many times as you want with var or let, just don't add var or let again.

    Redeclaring

    // valid, but not advised
    var cube = (num) => num * num * num;
    var cube = (num) => num * num * num;

    // invalid
    var cube = (num) => num * num * num;
    let cube = (num) => num * num * num;

    // invalid
    var cube = (num) => num * num * num;
    const cube = (num) => num * num * num;

    Reassigning

    // valid
    var cube = (num) => num * num * num;
    cube = (num) => num * num * num;

    // valid
    let cube = (num) => num * num * num;
    cube = (num) => num * num * num;

    // invalid - can't change a const
    const cube = (num) => num * num * num;
    cube = (num) => num * num * num;