Search code examples
javascriptoperators

What's this JavaScript syntax?


I am new to JavaScript. The following code is from some production codebase. The regDefinition is passed in JSON form. But I am not quite sure about the syntax in the method body. Especially the || and [] parts.

function getCookieValue(regDefinition) {
    return (document.cookie.match(regDefiniation.regEx) || [])[regDefiniation.index] || null;
}

Solution

  • It looks like someone has made a lot of effort to make this very hard to read.

    If I interpret it right, it does something like this:

    • call the match method.
    • it returns an array of matches, or nothing (null, undefined?). If it doesn't return anything, default to an empty array.
    • Of the array, get the element with index 'regDefiniation.index'.
    • If that item doesn't exist (which can be the case for matches, and will always be the case for the empty default array), return null.