Question

I'm taking charge of a javascript webapp. It's very complex, and I'm having some trouble with syntax:

getThemeBaseUrl = function() {
  var customConfigPath = "./customer-configuration";                    
  if (parseQueryString().CustomConfigPath) {                           
    customConfigPath = parseQueryString().CustomConfigPath;
  }
  var clientId = parseQueryString().ClientId; 

  return customConfigPath + "/themes/" + clientId;
};

parseQueryString = function() {
  var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;
  while ( m = re.exec(queryString)) {
    result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
  }
  return result;
};

in particular parseQueryString().CustomConfigPath and the var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;

The first seems to be a sort of property access by the parseQueryString function.

The second seems an array declaration, but without the Array() constructor. Also, the m value is recalled without the presumed array result in the while cycle.

Was it helpful?

Solution

By looking at:

parseQueryString().CustomConfigPath

you can say that parseQueryString() is expected to return an object with CustomConfigPath property.

And from this:

var result = {};

you see that result is indeed an object ({} is an empty object literal). It is not an array. Later, in a loop, there is:

result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);

so we're assigning properties to the result object. One of this properties will be (as we can expect) a CustomConfigPath. This will be taken from the query string - we'll use regular expression to do this: re = /([^&=]+)=([^&]*)/g. So address of the webpage on which this code is executed looks like: http://example.com/something?SomeKey=value&CustomConfigPath=something.

General syntax for assigning properties to an object is:

result[key] = value;
// key   -> decodeURIComponent(m[1]) 
// value -> decodeURIComponent(m[2])

OTHER TIPS

parseQueryString().CustomConfigPath calls the parseQueryString function, which returns an object. Then it accesses the CustomConfigPath property of that object. A common idiom for the first 4 lines of the function is:

var customConfigPath = parseQueryString().CustomConfigPath || "/.customer-configuration";

var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m is a declaration of 4 different variables, not an array:

  • result is an empty object
  • queryString is the query string from the current URL, with the ? removed.
  • re is a regular expression
  • m is a variable that isn't initialized, it will be assigned later in the while loop.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top