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;
}
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.
$ 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).
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.
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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With