What is the difference between a parameter and a local variable?

Sorry for what must seem like a very silly question.

I am currently working through codecadamy and this throws me back:

 var greeting = function(name) {
    name = "sausage";
    console.log(name); 
};

greeting(name);

      

I understand what I will get sausage

Why don't I just write var name = "sausage";

? What is the difference?

+3


source to share


4 answers


name

in function(name)

is a parameter. That is, it is used to pass data to a function. But parameters are local variables. Assigning a value name

inside a function is a little weird. I would guess that you want to do something like this:

 var greeting = function(name) {         
     console.log(name); 
  };

  greeting("sausage");

      



In this version of the code, you are passing the value "sausage" to the function through a parameter name

. This is useful because you can call the function many times and each time the function may print a different value depending on what you pass in.

+5


source


In function definition:

function(name) {

      

the name has already been announced. This is the parameter for the function. If you want to change the name, you can, but you don't need to use var to declare it as a new variable.



On the other hand, if you want to add, say, flavor, you must use var, since it is not defined yet.

var flavor = 'savory';

      

In this case, flavor is a local variable and name is a parameter. A parameter is the type of the local variable declared with the function declaration, but the local variable is not necessarily a parameter as it can be declared elsewhere in the function.

+2


source


Technically, there is no real difference.

Without giving you a huge background here, you should understand that a special object is created in the subclass implementation (not a javascript object at the C / C ++ level) called an activation object (ES3) or lexical environment (ES5).

However, this hash / object structure is used to store

  • variables declared var

  • formal parameters
  • function declarations

As you can see, both variables and parameters var

are stored in this structure.

This construct is most likely used for multiple default values ​​that are not passed in arguments. In the real world it will probably be more like

var greeting = function( name ) {
    name = name || 'default';

    console.log( name );
};

greeting('john');  // 'john'
greeting();        // 'default'

      

+2


source


Parameters are a general programming construct and are necessary to do anything sane in world programming (considering masses of global variables is not normal.

var name

will declare a new variable in the function scope that will override the parameter value name

, so you can no longer use this parameter.

The CodeAcadamy example is a bit weird because you rarely want to override a parameter's value - especially before using it.

+2


source







All Articles