Kishore Kumar Korada
Kishore Kumar Korada

Reputation: 1264

Why parameters in JavaScript functions doesn't need var as type?

I know it seems silly question but I'm actually confused with following scenario which as follows...
I understood that for every variable we need to specify datatype as var or though it's not a good practice we can go without var as well. For instance
We can either use

var name = "kishore";

or simply

name = "kishore";

But, when it comes to variables that we are passing as parameters in functions, Why doesn't they accept var? If I'm not wrong, I think those are just like other variable which has to store some value that can be accessible in that function. If I specify var it gives error. I just want to know what's going on there..?

Upvotes: 3

Views: 1737

Answers (3)

Hasan Al-Natour
Hasan Al-Natour

Reputation: 2066

The Parameters are already stored in the function scope in the arguments array , so you don't need to use var :

function fun(t){
  console.log(arguments)
};

fun('3');

Output is :

["3"]

Upvotes: 1

Guffa
Guffa

Reputation: 700262

The var keyword is for declaring new variables.

Parameters are different. They already exist when the function is called, the declaration in the function header just gives names to the already existing values.

The arguments collection contains the values that are passed to the function, and you can access the parameters there even if they are not declared as parameters in the function header.

Example:

function test1(a, b, c) {
  show(a);
  show(b);
  show(c);
}

function test2() {
  show(arguments[0]);
  show(arguments[1]);
  show(arguments[2]);
}

test1(1, 2, 3);
test2(1, 2, 3);


// show in Stackoverflow snipper
function show(n) { document.write(n + '<br>'); }

Upvotes: 1

JAAulde
JAAulde

Reputation: 19560

var is not a datatype, but a keyword/operator used to declare a variable in the appropriate scope. Function parameters are already scoped to the function for which they are parameters and there is no changing that. Thus the use of var would be redundant and was not required.

Some commented code samples:

// A globally accessible function
var f1 = function (p1) { // p1 automatically scoped to f1 and available to all inner functions (like f2 below)
    // A variable available in the scope of f1 and all inner functions (like f2 below)
    var v1;

    // f1, p1, v1, and f2 can be reached from here

    var f2 = function (p2) { // p2 automatically scoped to f2
        // A variable available in the scope of f2
        var v2;

        // f1, p1, v1, f2, p2, and v2 can be reached from here
    };
};

Upvotes: 8

Related Questions