Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's this JavaScript syntax?

Tags:

javascript

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;
}
like image 439
smwikipedia Avatar asked Jul 06 '14 16:07

smwikipedia


People also ask

What is this syntax in JavaScript?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.

What it's for '$' in JavaScript?

$ is simply a valid JavaScript identifier. JavaScript allows upper and lower letters, numbers, and $ and _ . The $ was intended to be used for machine-generated variables (such as $0001 ). Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function).

Does JavaScript have this?

In JavaScript, the this keyword allows us to: Reuse functions in different execution contexts. It means, a function once defined can be invoked for different objects using the this keyword.

What is .type in JavaScript?

typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well. The typeof operator is useful because it is an easy way to check the type of a variable in your code.


2 Answers

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.
like image 94
GolezTrol Avatar answered Sep 23 '22 07:09

GolezTrol


There are some good answers here, but nobody seems to really be explaining why you'd do

(foo || [])[bar]; // or similarly (foo || {})[bar]

instead of just

foo[bar]

Consider case the RegExp failed,

var foo = null, bar = 0;

Now without anything special you'd get an error thrown and the code would stop

foo[bar]; // TypeError: Cannot read property '0' of null

However the parenthesised-or version will be different

(foo || [])[bar]; // undefined (note, no error)

This is because the result of (null || []) is [], and you can now try to read a property of it safely

like image 43
Paul S. Avatar answered Sep 22 '22 07:09

Paul S.