legend legend - 2 months ago 11
Javascript Question

What will happen if I defined more than one parameters but passing in only one parameter?

The function was defined as follow,but I don't know how does the function work if I passing in only one parameter even ignore the order.
Thanks~

function setCookie(name,value,path,expires){

value = escape(value);
if(!expires){
var now = new Date();
now.setMonth(now.getMonth() + 6);
expires = now.toUTCString();
}
if(path){
path = ";path = " + path;
}

document.cookie = name + "=" + value + ";expires = " + expires + path;
}

Answer

JavaScript has very loose rules when it comes to arguments. You can make input infinite arguments that the function doesn't list (though they have to be accessed through the built in arguments variable).

function showArguments() {
  for(var index = 0; arguments.length >= index; index++) {
    var argument = arguments[index];
    var p = document.createElement('p');
    p.textContent = argument;
    document.body.appendChild(p)
  }
}
showArguments('foo', 'test')

You can run a function asking for 10 arguments with 0, and only when you try to access a non-existent property will it error.

function foo(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) {
  console.log('no error, until you try to access something like length on the undefined argument');
  var length = arg1.length;
}
foo();

But because of this looseness, when you try to access arguments that should be there, undefined is returned. So in your case beside the first possible error of running escape on undefined, there should be no errors, and document.cookie will be equal to name + '=' + undefined + ';expires = ' + now.toUTCString() + undefined.

function setCookie(name,value,path,expires){

  value = escape(value);
  if(!expires){
    var now = new Date();
    now.setMonth(now.getMonth() + 6);
    expires = now.toUTCString();
  }
  if(path){
    path = ";path = " + path;
  }

  var cookie = name + "=" + value + ";expires = " + expires + path;
  var div = document.createElement('div');
  var p = document.createElement('p');
  var p2 = document.createElement('p');
  p.textContent = 'name + "=" + value + ";expires = " + expires + path: ' + cookie;
  p2.textContent = 'name + "=" + undefined + ";expires = " + now.toUTCString() + undefined: ' + name + "=" + undefined + ";expires = " + now.toUTCString() + undefined;
  div.appendChild(p);
  div.appendChild(p2);
  document.body.appendChild(div);
  return cookie
}

setCookie('foo');

To set a default for these undefined variables add var foo = foo || 'default'.

Comments