how works boolean operator || [duplicate] - javascript

This question already has answers here:
Javascript || operator
(5 answers)
What does the Javascript expression 'a = a || function() {...}' mean?
(4 answers)
Closed 9 years ago.
I usually use this code to see if the argument of a function is undefined or not
var = (typeof var != "undefined")? var : "othervalue";
but, other uses this boolean operator
var = var || "othervalue";
However, I have seen that if the value of checking and boolean false argument is not done correctly.
// assuming it is false
var = var || "othervalue"; // will be "OTHERVALUE"!!!
I need to know what exactly this operator in this context.

It returns the last expression that terminated the condition. It doesn't work the same as checking for typeof arg == "undefined", as any falsey value on the left will jump to the RHS.

|| operator will return the last expression, if first one is falsely:
var test = first || "second";
// error will be raised, because first variable is not defined
var first;
var test = first || "second";
// test = "second", because first is falsely
var first = "first";
var test = first || "second";
// test = "first"
I always use ternary operator with typeof expression, because it's a really common thing to forget to define some variable:
var test = 'undefined' != typeof(first) && first ? first : "second";
// test = first if first is defined and true

I believe this is a perl style selection for first true (pseudocode below)
eat_breakfast = null
eat_dinner = null
eat_lunch = "eating lunch"
myVal = eat_breakfast || eat_dinner || eat_lunch
print myVal
would print "eating lunch"
it will set myVal to the first non-null/non-false entity.

Related

Does operator && in TypeScript works the same way as Java? [duplicate]

This question already has answers here:
What's the difference between & and && in JavaScript?
(4 answers)
Closed 3 years ago.
I know that in Java if I write condition1 & condition2, Java will check both conditions and even if condition1 is already false, Java will check condition2 and then decide.
On the other hand when writing condition1 && condition2 if condition1 is false it wont check condition2.
Does it work the same in JavaScript/TypeScript?
& and && are separate and different operators in Javascript (and hence Typescript).
In Javascript, & is the bitwise and, for example:
5 & 13 & 3 === 1; // 0b0101 & 0b1101 & 0b0011 = 0b0001
&& is the logical and and shorthands the same way as in other languages. However, beware of type coercion as Javascript has many surprises about what evaluates to a truthy or falsy value.
5 < 3 && foo(); // foo is NOT called
[] && foo(); // foo is called
"" && foo(); // foo is NOT called
Typescript (and Javascript) operator && differs from its Java counterpart. Consider this code:
example.ts
-----------
const b = true;
const str = "abc";
const result = b && str; // the operator '&&` returns string
const t = typeof result;
console.log(t) // prints 'string'
To see boolean printed in the console, you need to replace b && str with b && !!str.

Global variable is null [duplicate]

This question already has answers here:
JavaScript String concatenation behavior with null or undefined values
(7 answers)
Closed 6 years ago.
I have a global variable. The variable is equal to null. var a=null; Then I write a=a+"example" in console. But output is null example. Why is it so ?
There are three possibilities in javascript:
Option 1
var a;
a=a+"example";
output: "undefinedexample"
Option 2
var a=null;
a=a+"example";
output: "nullexample"
Option 3
var a="";
a=a+"example";
output: "example"
As per your Question you need to define third option. bcz in javascript null and "" both are different types.
For more ref JavaScript String concatenation behavior with null or undefined values
If You want to concatenate strings this way, You shouldn't assign null but an empty string. Value null will be changed to string 'null' in your code. Example:
var a = '';
for(var i=0; i<10; i++) {
a = a + 'abc';
}
As you are concatenating it with string it turning out to be string see this example it adopts the datatype you assign it to be for the initial value was null
if you concat with string it takes string type if number then with number type and so on
var s = null;
console.log(s+"example");
console.log(s+5);
console.log(s+17.5)
I don't know what u really expecting,according to your problem,i think you need to concatenate two string,if am correct you can use
var str1 = '';
var str2 = "example";
var res = str1.concat(str2);
instead of null you can use ''

What will be the value of variable thisconnection and HOW?

var connections = {key: 1234}
var thisconnection = connections["key"] || {status:"new"};`
In the above code, the variable thisconnection is subjected to the Logical operator '||'
When I simply type the following code in the console, thisconnection takes the value of the connections["key"] in any case.
Why don't you try it?
var connections = {key: 1234};
var thisconnection = connections["key"] || {status:"new"};
console.log(thisconnection); // returns 1234
Explanation:
If connections.key returned 0, NaN, false, undefined, "" (empty string), or any value that evaluated to false, it would continue evaluating the next || expression.
However, if the expression evaluates to a truthy value, the whole statement is finished with evaluation. This is known as short-circuiting:
As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:
false && (anything) is short-circuit evaluated to false.
true || (anything) is short-circuit evaluated to true.
Since 1234 is a truthy value, evaluation stops and the value 1234 is assigned.
In the following statement
var thisconnection = connections["key"] || {status:"new"};
You are saying if connection["key"] exists assign connection["key"] to thisconnection, other wise assign {status:new} to thisconnection.
It's same as following code
if(connections["key"]){
thisconnection = connection["key"]
}
else{
thisconnection = {status:new}
}
if connections["key"] is nil then {status:"new"} will be the value of variable
In JavaScript, || and && operators have a specific behavior when used in variable assignment. If you have something like this:
var theResult = a || b || c || d;
Then, the variable theResult won't be a boolean as we expect in other languages.
If a is truhty, then theResult = a. Else, if b is truhty, then theResult = b. And so on... If all variables are falsy, then theResult = d because d is the last statement in the or condition.
The rule is the following:
the value of theResult will be the value of the variable in a || b || c || d which break the chain
So, since we have only OR conditions, then the first value which resolve to true will break the chain. I mean, if a === true, then it's not needed to evaluate the rest of the condition because true || false || whatEver || weDontCare will always be true. If none of the variable breaks the chain, then the last variable is assigned to theResult.
First it will check connections["key"],
If it is not null, then the value of thisconnection with contain value of connections["key"]. Otherwise thisconnection will contain value of {status:"new"}.

Ternary operators in JavaScript without an "else"

I've always had to put null in the else conditions that don't have anything. Is there a way around it?
For example,
condition ? x = true : null;
Basically, is there a way to do the following?
condition ? x = true;
Now it shows up as a syntax error.
FYI, here is some real example code:
!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null;
First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.
This means several things:
use ternary expressions only when you have a variable on the left side of the = that is to be assigned the return value
only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
each part of the expression (after ? and after : ) should return a value without side effects (the expression x = true returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)
In short - the 'correct' use of a ternary expression is
var resultofexpression = conditionasboolean ? truepart: falsepart;
Instead of your example condition ? x=true : null ;, where you use a ternary expression to set the value of x, you can use this:
condition && (x = true);
This is still an expression and might therefore not pass validation, so an even better approach would be
void(condition && x = true);
The last one will pass validation.
But then again, if the expected value is a boolean, just use the result of the condition expression itself
var x = (condition); // var x = (foo == "bar");
UPDATE
In relation to your sample, this is probably more appropriate:
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
No, it needs three operands. That's why they're called ternary operators.
However, for what you have as your example, you can do this:
if(condition) x = true;
Although it's safer to have braces if you need to add more than one statement in the future:
if(condition) { x = true; }
Edit: Now that you mention the actual code in which your question applies to:
if(!defaults.slideshowWidth)
{ defaults.slideshowWidth = obj.find('img').width()+'px'; }
More often, people use logical operators to shorten the statement syntax:
!defaults.slideshowWidth &&
(defaults.slideshowWidth = obj.find('img').width() + 'px');
But in your particular case the syntax can be even simpler:
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width() + 'px';
This code will return the defaults.slideshowWidth value if the defaults.slideshowWidth is evaluated to true and obj.find('img').width() + 'px' value otherwise.
See Short-Circuit Evaluation of logical operators for details.
var x = condition || null;
You could write
x = condition ? true : x;
So that x is unmodified when the condition is false.
This then is equivalent to
if (condition) x = true
EDIT:
!defaults.slideshowWidth
? defaults.slideshowWidth = obj.find('img').width()+'px'
: null
There are a couple of alternatives - I'm not saying these are better/worse - merely alternatives
Passing in null as the third parameter works because the existing value is null. If you refactor and change the condition, then there is a danger that this is no longer true. Passing in the exising value as the 2nd choice in the ternary guards against this:
!defaults.slideshowWidth =
? defaults.slideshowWidth = obj.find('img').width()+'px'
: defaults.slideshowwidth
Safer, but perhaps not as nice to look at, and more typing. In practice, I'd probably write
defaults.slideshowWidth = defaults.slideshowWidth
|| obj.find('img').width()+'px'
We also have now the "Nullish coalescing operator" (??). It works similar to the "OR" operator, but only returns the left expression if it's null or undefined, it doesn't return it for the other falsy values.
Example:
const color = undefined ?? 'black'; // color: 'black'
const color = '' ?? 'black'; // color: ''
const color = '#ABABAB' ?? 'black'; // color: '#ABABAB'
What about simply
if (condition) { code if condition = true };
To use a ternary operator without else inside of an array or object declaration, you can use the ES6 spread operator, ...():
const cond = false;
const arr = [
...(cond ? ['a'] : []),
'b',
];
// ['b']
And for objects:
const cond = false;
const obj = {
...(cond ? {a: 1} : {}),
b: 2,
};
// {b: 2}
Original source
In your case i see the ternary operator as redundant. You could assign the variable directly to the expression, using ||, && operators.
!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null ;
will become :
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
It's more clear, it's more "javascript" style.
You might consider using a guard expression instead (see Michael Thiessen's excellent article for more).
Let x be a logical expression, that you want to test, and z be the value you want to return, when x is true. You can then write:
y == x && z
If x is true, y evaluates to z. And if x is false, so is y.
The simple way to do this is:
if (y == x) z;
Why not writing a function to avoid the else condition?
Here is an example:
const when = (statement, text) => (statement) ? text : null;
const math = when(1 + 2 === 3, 'Math is correct');
const obj = when(typeof "Hello Word" === 'number', "Object is a string");
console.log(math);
console.log(obj);
You could also implement that function for any objects. Here is an example for the type string:
const when = (statement, text) => (statement) ? text : null;
String.prototype.if = when;
const msg = 'Hello World!';
const givenMsg = msg.if(msg.length > 0, 'There is a message! Yayyy!');
console.log(givenMsg);
Technically, it can return anything.
But, I would say for a one liner the Ternary is easier to type and at least 1 character shorter, so therefore faster.
passTest?hasDriversLicense=true:0
if(passTest)hasDriversLicense=true

Can I get the "value" of an arbitrary statement in JavaScript (like eval does, but without eval)

In JavaScript is there a way to get the "value" of a statement in the same way that function() { return eval("if (true) { 1 }"); } returns "1";
function() { return if (true) { 1 } } and all similar permutations I've tried are not valid syntax.
Is eval just blessed with special powers to determine the "last" value of a statement in an expression?
Use case is a REPL that evaluates arbitrary expressions and returns the result. eval works, but I want to wrap it in function.
function(expr) { return eval(expr); }
But that really doesn't do anything more than what eval does, so I'm guessing you must want to do things with the return value of eval before returning it?
E.g.:
function custom_eval(expr)
{
var result = eval(expr);
if ((typeof result))=="string")
{
alert("The expression returned a string value of: " + result);
}
if ((typeof result))=="number")
{
alert("The expression returned a number with value: " + result);
}
//and so on and so forth...
return result;
}
var bob = custom_eval("x=\"bob\";x");
alert(bob);
(More on the typeof operator)
To evaluate arbitrary javascript code in javascript you have three options
eval. This is usually considered as "dangerous", but since javascript is executed on the client's computer, they can only harm themselves (unless you provide clients with a way to share their codes).
Function constructor. The same concerns apply.
write a javascript interpreter. This is definitely tricky for "arbitrary" code.
You can use || to get the first value that isn't null/undefined/0:
var t = 1 || 'b' || 3 || 'd'; // assigns 1
var t = 0 || null || undefined || 'd'; // assigns d
You can use && to get the last value, if no short-circuiting null/undefined/0 is found first:
var t = 1 && 'b' && 3 && 'd'; // assigns d
var t = 0 && null && undefined && 'd'; // assigns 0

Categories

Resources