0

Say I have a function dosomething and I call it sometimes with an argument, sometimes without.

I want to let the default value of the argument equals 5. So I have these two ways:

function dosomething(a) {
  if(!a) {
    a = 5;
  }
}

Or

function dosomething(a) {
  if(!a) {
    var a = 5;
  }
}

After testing I found they both work.

But do I have to use the var? What's the difference?

AGamePlayer
  • 7,404
  • 19
  • 62
  • 119
  • 2
    `var` declares a variable. Function arguments are already declared. See also... [_"Duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless another assignment is performed."_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#description) – Phil Jun 28 '21 at 03:09
  • 1
    using `var` will declare a new variable and sets the value of the new variable to `5` but using only `a` doesnt declare any new variable, it sets the value of the parameter to `5` – I_love_vegetables Jun 28 '21 at 03:10
  • 1
    As ESLint `[no-redeclare][1]` rule describes: ``` In JavaScript, it's possible to redeclare the same variable name using var. This can lead to confusion as to where the variable is actually declared and initialized. ``` So better declare var only one time for a specific variable. In ES6 u can do a default value like this: ``` function print (a = 10) { } ``` > Besides use `let` instead `var` in function [1]: https://eslint.org/docs/rules/no-redeclare – Kent Jun 28 '21 at 03:19

0 Answers0