Q:

How to refer a undefined parameter in global scope

var a = 2;
function f(a) {return a;}
console.log(f(1));// return 1
console.log(f());// return undefined, but I want to make it return 2...

f() returns undefined, but I want to it refer the variable a in global scope. How could I achieve that?

A:

var a = 2;
function f(b) {
    return b || a;
}

You need to use a different name for the function argument, else it's going to shadow the outer a and won't give you any chance to return it. Then it's a simple matter of deciding which value to return. Here I'm using a simple falsey check, you may or may not want to use something more detailed like typeof b === 'undefined' or such.

A:

Use arguments.length to test if a parameter was passed to the function:

var a = 2;
function f(b) {
  if(arguments.length===1) return b;
  return a;
}

console.log(f(3));          //3
console.log(f(undefined));  //undefined
console.log(f(0));          //0
console.log(f());           //2

