what does the following code do in java script:
var x = x || {};
var is the keyword that tells JavaScript you're declaring a variable. x is the name of that variable. = is the operator that tells JavaScript a value is coming up next. 100 is the value for the variable to store.
This means that if window. google doesn't have value (undefined, null) then use {} . It is a way of assigning a default value to a variable in JavaScript. Follow this answer to receive notifications.
The double pipe operator ( || ) is the logical OR operator . In most languages it works the following way: If the first value is false , it checks the second value. If that's true , it returns true and if the second value is false , it returns false .
Always declare JavaScript variables with var , let , or const . The var keyword is used in all JavaScript code from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If you want your code to run in older browser, you must use var .
||
is the logical OR
.
The expression
var x = x OR {};
should become more obvious then.
If x
has a falsy value (like null
, undefined
, 0
, ""
), we assign x
an empty object {}
, otherwise just keep the current value. The long version of this would look like
var x = x ? x : {};
If x
is undefined (or null, or any other false
value), it becomes an empty object.
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