Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the function argument not overwritten on creating variable of same name inside the function?

var a = 'why is this not undefined?';
function checkScope(a) {
    var a;
    console.log(a);
}
checkScope(a);

Javascript is functional scope language, right? When I declare a new variable just inside the function that uses the same name as the functional argument, why does the newly defined variable still hold the same data as the argument?

I thought it should be undefined?

like image 425
user3932668 Avatar asked Jan 15 '15 12:01

user3932668


People also ask

Can variables be overwritten?

Because variables in Java do not follow polymorphism and overriding is only applicable to methods but not to variables. And when an instance variable in a child class has the same name as an instance variable in a parent class, then the instance variable is chosen from the reference type.

What does it mean if the value in a variable has been overwritten?

If you replace the old value of a variable with a new one, then the old value will be overwritten because a variable, during its life, does not move in memory. If you don't want to change the value, simply don't write code that changes it.

What happens when a variable defined outside a function has the same name as a local variable inside a function?

Answer. When a parameter has the same name as a variable defined outside, instead of the function using the variable defined outside, it will only reference the value that was passed to the parameter. So, parameters will be used over variables of the same name within a function.

Can arguments and parameters have the same name?

From syntax perspective, there is nothing wrong with 1 example. Python follows LEGB rule when it tries to get variable value, so when you use bar as an argument, you rewrite global bar in scope of foo function. Show activity on this post. You can keep the same name, it doesn't matter.

What happens when you call a function with two arguments?

Since we have called this function with two arguments, it runs smoothly and we do not get any error. If we call it with a different number of arguments, the interpreter will show an error message.

What is the difference between a parameter and an argument?

The terms parameter and argument can be used for the same thing: information that are passed into a function. A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that are sent to the function when it is called. By default, a function must be called with the correct number of arguments.

How do you define a function in Python with arguments?

Python Function Arguments. In Python, you can define a function that takes variable number of arguments. You will learn to define such functions using default, keyword and arbitrary arguments in this article. In user-defined function topic, we learned about defining a function and calling it. Otherwise, the function call will result into an error.

How do you pass information to a function as an argument?

Arguments. Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The following example has a function with one argument (fname).


3 Answers

var a; is actually a variable declaration statement. When the function is defined, all the variables declared in it, are processed before the code execution and so you can use the variables even before the actual declaration line is executed at runtime. This is called var hoisting. So, no matter how many times you declare a variable, the variable is actually declared only once.

In your case, you have defined a as one of the parameters to the function, which is scoped to the current function. And then you are declaring a variable with the same name. Since a is already declared in the function, as one of the parameters, the var a; declaration will be ignored.

That is why you are getting why is this not undefined? in the console.

Instead of var a;, lets say you had var a = 1;, in this case, the variable is already declared but the assignment expression will be evaluated at runtime and the value 1 will be assigned to a. So, the console.log will print 1.


This behaviour is explained in the ECMA Script 5.1 Specification, under the section 10.5 Declaration Binding Instantiation,

  1. If code is function code, then

    a. Let func be the function whose [[Call]] internal method initiated execution of code. Let names be the value of func’s [[FormalParameters]] internal property.

    b. Let argCount be the number of elements in args.

    c. Let n be the number 0.

    d. For each String argName in names, in list order do

          i. Let n be the current value of n plus 1.

          ii. If n is greater than argCount, let v be undefined otherwise let v be the value of the n’th element of args.

          iii. Let argAlreadyDeclared be the result of calling env’s HasBinding concrete method passing argName as the argument.

          iv. If argAlreadyDeclared is false, call env’s CreateMutableBinding concrete method passing argName as the argument.

          v. Call env’s SetMutableBinding concrete method passing argName, v, and strict as the arguments.

....

  1. For each VariableDeclaration and VariableDeclarationNoIn d in code, in source text order do

    a. Let dn be the Identifier in d.

    b. Let varAlreadyDeclared be the result of calling env’s HasBinding concrete method passing dn as the argument.

    c. If varAlreadyDeclared is false, then

          i. Call env’s CreateMutableBinding concrete method passing dn and configurableBindings as the arguments.

          ii. Call env’s SetMutableBinding concrete method passing dn, undefined, and strict as the arguments.

As we see in the specification, the arguments and the variables declared in the function, all are actually defined in the execution environment corresponding to the function in which they are defined. So, if the arguments and the variables have the same name, the variable is actually defined only once and the second declaration is ignored.

like image 194
thefourtheye Avatar answered Oct 27 '22 09:10

thefourtheye


The parameter is still defined inside the function, becase the var a; is ignored when the variable is already defined inside the same scope.

A statement like var a; doesn't mean that the variable is created at that point in the code. All variable declarations are hoisted to the top of the scope, so you can redeclare them as many times you want in the scope, and they are still only created once.

If a declaration has an assignment though, like var a = 2;, the assignment happens where the statement is in the code, regardless if the declaration is ignored or not.

Example:

function check(a) {
  // both a and b exist here
  document.write('a = ' + a + ', b = ' + b + '<br>');
  var b = 1;
  document.write('a = ' + a + ', b = ' + b + '<br>');
  var a = 2; // not recreated, but assigned
  document.write('a = ' + a + ', b = ' + b + '<br>');
}

check(42);
like image 4
Guffa Avatar answered Oct 27 '22 08:10

Guffa


  1. you are passing the variable a to the function check as a parameter.function checkScope(a) {

  2. inside the function you are again trying to declare var a, var a;

Both of these are within the same scope, right? i.e both inside the function check();

And according to docs, that var a inside the function is same variable which you passed as parameter and you are just using it before declaration... you can do it with JS

So the code you have written is equuivalent to

var a = 'why is this not undefined?';
function checkScope(a) {

    console.log(a);
}
checkScope(a);

i.e the var a is just ignored.

And what you expect that var a should return undefined then the code would be like this

var a = 'why is this not undefined?';
function checkScope() {
   var a
    console.log(a);
}
checkScope();

This time we are not passing the parameter a to the function and a new variable var a is created within the function scope, thus becomes undefined

like image 4
Naeem Shaikh Avatar answered Oct 27 '22 07:10

Naeem Shaikh