1

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?

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
leo_00
  • 13
  • 4

1 Answers1

2

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;
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
  • I got that we cannot change var to let in same scope but somehow this is possible if let and var are in different scopes. Like this one : var a = 1; var b = 2; if (a === 1) { var a = 11; // the scope is global let b = 22; // the scope is inside the if-block console.log(a); // 11 console.log(b); // 22 } How is this possible? – leo_00 Feb 20 '23 at 10:19
  • @leo_00 `var` variables in JavaScript are function-scoped, not block-scoped. – RoToRa Feb 20 '23 at 11:30