Search code examples
javascriptwith-statementscope-chain

To which variable object statements inside with are bind?


function buildUrl() {
  var qs = "?debug=true";
  with(location){
    var url = href + qs;
  }
  return url;
}
buildUrl(); // it will work. WHY?

I am working through a "Professional JavaScript for Web Developers" by N. Zakas, and I came across this snippet. From my understanding with is a statement that augments scope chain by pushing, in this case, location object to the front.

It seems that url local variable is assigned to a function activation object. Why isn't it assigned to location?


Solution

  • with adds the argument location for the purposes of lookup, but your var url is still hoisted to the containing function - i.e. buildUrl as you are creating a variable, not looking one up.

    However, you should completely avoid with, see the statement on MDN.