Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Do I need to use 'var' when reassigning a variable defined in the function's parameters?

Tags:

javascript

I've found many definitions of the 'var' statement but most of them are incomplete (usually from introductory guides/tutorials). Should I use 'var' if the variable & scope has been declared in the params list?

someFunc = function(someVar)
{
   // Is it considered good practice to use 'var', even if it is redundant? 

   var someVar = cheese;
};
like image 731
John Himmelman Avatar asked Mar 22 '10 19:03

John Himmelman


4 Answers

The answer is no, you shouldn’t be doing this. This is actually considered a bad practice!

JS Lint throws the following error when analyzing your code example:

Problem at line 5 character 16: someVar is already defined.

like image 183
Mathias Bynens Avatar answered Sep 22 '22 03:09

Mathias Bynens


"I've found many definitions of the 'var' statement but most of them are incomplete."

Try this (a bit stuffy but hopefully complete :-) ): The var keyword declares a new variable, binds it to the current lexical scope, & hoists it to the top of said scope. In other words, the variable will not exist outside of the function that declares it & will be declared before any statements are executed inside the function. Function parameters are implicitly bound to that function's scope so do not require the var keyword.

like image 35
plodder Avatar answered Sep 22 '22 03:09

plodder


Nope, the order in which names are defined when entering an execution scope is as follows:

  1. function parameters (with value passed or undefined)
  2. special name arguments (with value of arguments if doesn't exist)
  3. function declarations (with body brought along)
  4. variable declarations (with undefined if doesn't exist)
  5. name of current function (with body brought along, if doesn't exist)

This means that in this code, foo refers to the function parameter (which could easily be changed):

function foo(foo) {
  var foo;
  alert(foo);
}
foo(1); // 1

If you're using a function declaration inside for foo, that body will override all others. Also, note that this means that you can do this:

function foo(arguments) {
    alert(arguments);
}
foo(); // undefined
foo(1); // 1

Don't do that.

like image 29
bcherry Avatar answered Sep 21 '22 03:09

bcherry


No. In Javascript, you can mess with the function argument all you want.

Consider this code, which you see all over the Web and which is used to make code work in standard and IE event models:

function someEventHandler(event) {
  event= (event) ? event : window.event;
  // statements
}
like image 35
Robusto Avatar answered Sep 21 '22 03:09

Robusto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!