JavaScript declaring variable as " g = g || {}; " what does it means? [duplicate] - javascript

This question already has answers here:
What does the construct x = x || y mean?
(12 answers)
Closed 7 years ago.
Good day, was reading a JavaScript script library and come across this
var g = g || {};
What does this means?

This is a way to ensure g is actually initialized as an object. It is the same as:
if(!g) g = {};
The || is an OR. The second operand will be returned only if the first one evaluates to false.

It means, that if g is 0/null/undefined, the g will be defined as an empty object.
The common way:
function foo(g) {
// If the initial g does not defined, null or 0
if(!g) {
// Define g as an empty object
g = {}
}
}

JavaScript returns the first argument if true, otherwise the second one. This is equivalent to an OR.
So in your example, if g is not set, it is set to an empty object.

Following description is taken from this page.
expr1 || expr2
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand can be converted to true; if both can be converted to false, returns false.
In your case, if g has a falsy value (false/null/undefined/0/NaN/''/(document.all)[1]), then g will be set with {}

Related

How can jquery || "OR" be used outside of an if statement? [duplicate]

This question already has answers here:
JavaScript OR (||) variable assignment explanation
(12 answers)
What does the construct x = x || y mean?
(12 answers)
In Javascript, what does it mean when there is a logical operator in a variable declaration? [duplicate]
Closed 8 years ago.
I've never seen the OR paramater || used outside of an if statement.
What does this line of code do?
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document
Is it saying making it equal to either one of those???
A || B
evaluates A first. If it is true, A is returned, and B never needs to be looked at.
If A is false, B is evaluated and returned.
For example, if you write
function (x)
{ x = x || 50
...
This would make x=50, if x is nil (or some kind of false value).
Otherwise, x would not be changed.
It is like having a default value, or a failsafe protection. If you know that the answer should never be false, then if A is false, you provide a backup value of B.
A way to get a DOM reference to the iframe's window object is to use:
contentWindow.document
Now, cause IE<8 has problems with it, a small polyfill is to use
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document;
// Browser you get this one ^^^ ? NO? Sh** you're IE7, go with^^
So earlyer versions of IE will skip the contentWindow cause not recognized, and thanks to the || (or) operator will follow up with the next contentDocument.
I don't have to repeat what's the OR operator cause other smart people already explained it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
This is just a short form of the ternary operator, which always returns a value depending to a statement. So, e. g.:
var fruit = "apple";
var test = fruit === "apple" ? fruit : "banana";
This sets the variable test to the value of fruit, when fruit is set to "apple". Otherwise, test will be initialized with "banana".

What it exactly means in Javascript (assigning variable) [duplicate]

This question already has answers here:
Is there a "null coalescing" operator in JavaScript?
(19 answers)
What does "var FOO = FOO || {}" (assign a variable or an empty object to that variable) mean in Javascript?
(8 answers)
Closed 9 years ago.
I have question because I am not sure and cannot find answer on Stack Overflow about this.
What this exactly mean:
variable = variable || {}
or something that:
this.pointX = options.pointX || 6;
I understand that it assign to variable a variable if it exist or empty Object if variable doesn't exist but why it working that?
Is || not mean 'or' here?
The || is effectively working like a SQL COALESCE statement.
var x = y || z;
means:
if y evaluates to a "truthy" value, assign y to x.
if y evaluates to a "falsy" value, assign z to x.
See http://11heavens.com/falsy-and-truthy-in-javascript for more detail on "truthy/falsy" (or just google it).
The || is an or operator.
It basically means if variable is undefined, it will assign variable to a new object literal.
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Expressions_and_Operators#Logical_operators
|| does mean OR here:
var x = 5
var x = x || {} //If v is defined, v = v, else v = {} (new, empty, object).
//x = 5 since x already was defined
var y = y || {}
//y = {} since y was undefined, the second part is run.
The || operator returns the actual object that determines its "truthiness" value, not just a boolean (true or false). It "short circuits" in that once it can determine the result, it stops.
If variable has a truthiness value of true, it is returned (since when true is ored with anything, the result is true). Otherwise, the second operand is returned (even if it has a truthiness value of false) since it determines the truthiness of the whole expression.
this.pointX = options.pointX || 6;
Means assign this.pointX the value of options.pointX if available(i.e. not null) otherwise assign the value of 6
The || operator in JavaScript differs from some other languages you'll find it in. When JavaScript evaluates || it seems to return one operand OR the other. It doesn't do a typical truth table evaluation evaluating to true if any operand evaluates to true, and false if not.

What is this communicating: my_var = my_var || 69 [duplicate]

This question already has answers here:
What does the construct x = x || y mean?
(12 answers)
Set a default parameter value for a JavaScript function
(29 answers)
Closed 8 years ago.
I saw this in a Javascript example
my_var = my_var || 69
I assume it means to check if my_var exists, if not set my_var to 69. Is this the case? Is there any documentation on this, it is very hard to represent as a google/SO search, could somebody point me in the direction of docs or duplicate QA?
(The example didn't use 69, that's just me being crass)
Easy enough to try in the JS console.
var my_var
my_var = my_var || 69
//69
var my_var = 5
my_var = my_var || 69
//5
You are setting the variable only if it is currently carrying a falsy value.
Falsy values in JS are:
false
null
undefined
The empty string ''
The number 0
The number NaN
It's called "default" most of the time. The value "defaults" to the value after ||. The operation is loose comparison, like what you do with the if statements using ==.
Anything not falsy like:
false
empty string ('')
null
undefined
0
NaN
is considered true. If the first value isn't any of these, then it's the one assigned. If it is, the value on the right is assigned.
The || or operator has two operands (left and right). It checks whether the value to the left is truthy and if so assigns that to the variable otherwise assigns the right hand value to the variable.
var my_var = false;
my_var = my_var || true;
//true

Assignment with double ampersand "&&" [duplicate]

This question already has answers here:
Javascript AND operator within assignment
(7 answers)
Closed 7 years ago.
I just saw someone use this piece of code:
ctx = canvas.getContext && canvas.getContext('2d');
How does the double ampersand work in this context? Would it not just assign "true" to the ctx variable?
This is a common way to make sure your function exists before you call it.
It works like this (From developer.mozilla.com):
expr1 && expr2 Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
In other words, Javascript does not coerce the operands to boolean values unless it has to.
4 && 5 Returns 5, not true.
In your case, if the first expression is undefined (which is convertible to false), then ctx will be false, and the second expression does not get evaluated. If the first expression is a function (which cannot be converted to false), then Javascript evaluates the second expression, and assigns it's value to the ctx variable.
It will assign the return value of canvas.getContext('2d') to ctx if canvas.getContext is actually a function.
The part on the left is just to avoid an error. It makes sure that canvas has a getContext property before trying to call getContext(). This way, the code won't call canvas.getContext() if the function doesn't exist. If it didn't check first and called when the function didn't exist, an error would be logged to the console and execution would halt.

What does a !! in JavaScript mean? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
myVar = !!someOtherVar
What does the !! operator (double exclamation point) mean in JavaScript?
Came across this line of code
strict = !!argStrict
... here and wondered what effect the !! has on the line? Pretty new to JS!
It converts your value to a boolean type:
var x = '1';
var y = !!x;
// (typeof y === 'boolean')
Also note the following:
var x = 0;
var y = '0'; // non empty string is truthy
var z = '';
console.log(!!x); // false
console.log(!!y); // true
console.log(!!z); // false
It converts the value to a value of the boolean type by negating it twice. It's used when you want to make sure that a value is a boolean value, and not a value of another type.
In JS everything that deals with booleans accepts values of other types, and some can even return non-booleans (for instance, || and &&). ! however always returns a boolean value so it can be used to convert things to boolean.
It is a pair of logical not operators.
It converts a falsey value (such as 0 or false) to true and then false and a truthy value (such as true or "hello") to false and then true.
The net result is you get a boolean version of whatever the value is.
It converts to boolean
Its a "not not" arg
commonly used to convert (shortcut) string values to bool
like this..
if(!!'true') { alert('its true')}

Categories