Keep original value with "variable = NEWVAR || variable;" [duplicate] - javascript

This question already exists:
In Javascript, what does it mean when there is a logical operator in a variable declaration? [duplicate]
Closed 9 years ago.
Is this a legitimate way to update variables and keep the original value if the new value is undefined?
variable = NEWVAR || variable;
I created a Fiddle and so far it looks fine, but I don't want to get any nasty surprises.
Here is a test case:
var test = "hello";
test = undefined || test;
alert('"' + test + '"');

I would say, yes, i use it quite often. But you have to keep in mind that
Douglas Crockford: Javascript The Good Parts (p. 40)
The || operator produces the value of its first operand if the first operand is truthy. Otherwise, it produces the
value of the second operand.
So if NEWVAR contains any falsy (false,null,undefined,NaN,0,"") value, the second opertand is evaluated.
As long as you are aware of this you can always use the || operator to get default values
Douglas Crockford: Javascript The Good Parts (p. 51)
The || operator can be used to fill in default values:
var middle = stooge["middle-name"] || "(none)";
var status = flight.status || "unknown";

Yes and no. It technically works, but you have to be careful of falsy values because if NEWVAR is 0, false, "", or any other falsy value, it won't be assigned. A wiser way to do this would be to check whether or not NEWVAR is defined, perhaps with a tertiary operator:
variable = (typeof NEWVAR === "undefined") ? variable : NEWVAR;

Related

How can I pass label value as variable for if else case? [duplicate]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I was trying to compare a variable to a value and accidently ended up using '=' in place of '==' hence the code looked like:
var test = 1;
if(test = 2) {
console.log(test);
}
instead of:
var test = 1;
if(test == 2) {
console.log(test);
}
I assume the value was successfully assigned to the variable , hence the condition returned truthy and console.log() was executed. Is my assumption correct? What is a good coding practice to avoid such mistakes besides Yoda Condition reference
Lint it. There are tools that can automatically analyze your Javascript and catch common errors like this.
The assignment operator (=) in JavaScript evaluates to the right-side value of the expression, which means that test = 2 evaluates to 2 and since all values that aren't falsey (0, false, null, undefined, '', NaN) are thruthy by definition, the if condition was entered.
A good practice would be to always use the === sign when checking for equality and !== for inequality and there are tools that will help you enforcing those rules, like JSHint
Use if (a === b) { do stuff ; } that's three equals, ===
In Javascript you often need three equals, ===, as this requires primitives to have both the same type and value, and will not perform type coercion which, although you don't mention it, can be another source of confusion.
If you leave off an equals, it becomes two equals comparison, a == b, which might not work quite as expected if you are a beginner or unaware of the quirks of this comparison in Javascript, but at least is not an assignment.
The answer in JavaScript is pretty easy: always use strict comparison. This will avoid not only assignment errors, but also some non-intuitive behavior that can come from JavaScript's weak comparison rules.
Edit: Didn't see the questioners requirement to avoid this method.
Use strict comparison operator (===). You can also change the order of the values being compared which will fail if you use assignment statement rather than comparison operator.
Fails:
var test = 1;
if(2 = test) {
console.log(test);
}
The above code will throw an exception since you can't assign a value to the constant value.
Works:
var test = 1;
if(2 == test) {
console.log(test);
}
a = b is an assignment. Meaning a will equal to b.
a == b is a comparison. Meaning does a equal to b.
a === b is the same as == however no type conversion is done. Meaning does a equal to b, but also is it the same object/type?
Where your going wrong with your code is
var test = 1;
if(test = 2) { //this is true, because test now equals 2.
console.log(test);
}
When you assign something the value returned isn't representative of whether or not the assignment was successful, it actually just returns the right hand side of the assignment (e.g, the test = 2 in if (test = 2) would return 2 which is "truthy" in JavaScript, thus causing console.log(test) to evaluate. This can actually be quite useful in certain cases. For example:
while ((value = retrieveSomeValue()) !== null) {
console.log(value);
}
The code above continually assigns some variable value to the result of some function retrieveSomeValue, tests the resulting value to make sure it isn't null, and executes the while body.
To answer your question though: The === operator is more easily distinguished from the = operator and probably behaves more like what you would expect out of ==. Which equals operator (== vs ===) should be used in JavaScript comparisons?

How JS engine distinguish null from undefined [duplicate]

This question already has answers here:
What is the difference between null and undefined in JavaScript?
(38 answers)
JavaScript checking for null vs. undefined and difference between == and ===
(8 answers)
Closed 4 years ago.
In below code snippet a==b return true, i.e they point to same memory location, hence they will have same value.
I would like to know, how JS engine knows a===b is false.
How is type information determined when 2 different types point to same memory location?
Edit 1: From comments it looks like my question might not be clear. I totally understand difference between == and === in terms of usage in JS language. I am more interested in knowing how JS engine saves type information for null and undefined. As per my understanding variables a & b point to same memory location that is why I get a==b, if this understanding is wrong, please correct me.
Edit 2: Ok I will put my question in another way. How typeof operator knows a is object and b is undefined despite having a==b.
var a = null;
var b = undefined;
console.log(a==b);
console.log(a===b);
console.log(typeof a);
console.log(typeof b);
In the code snippet added in the question:
var a = null; var b = undefined;
console.log(a==b);
console.log(a===b);
console.log(a==b) returns true because == uses type coercion to check the equality of both the variables. Therefore, null and undefined are thought of as equals.
console.log(a===b) returns false because === does not use type coercion. For ===, null and undefined are not same types and it doesn't care about checking deep equality when the operands aren't of the same type.
This has got nothing to do with memory locations.
a = null, b= undefined;
a == b /* only check their values */
a === b /* also check their types + values */
typeof a == typeof b // false
typeof "variable" gives the type of the variable.

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

Categories