JavaScript comparison involving method is never true - javascript

I have the following JavaScript logical condition using the ternary operator:
var columnheader = (elem.getText === "ID") ? (Page.TableColumn(elem.getText())) : (Page.TableColumn(toTitleCase(elem.getText())));
For some reason when elem.getText value is 'ID' with no whitespace it doesn't evalute the first expression only the second, is there something wrong in my syntax? I've checked and double checked!

getText is a function. In your code, you are comparing the function with "ID", not the result of the function call (getText() ).
Should be:
var columnheader = (elem.getText() ==="ID") ? (Page.TableColumn(elem.getText())) : (Page.TableColumn(toTitleCase(elem.getText())));

Related

What does this JavaScript expression in BIRT report mean?

I am working on a BIRT Report and one of the fields contains the following expression:
dataSetRow["user_id"] != dataSetRow["creatorId"] ? dataSetRow["orderCreator"] : ''
What is the logic of this statement?
That statement is the equivalent of the code below, and is called the 'ternary' operator:
var value;
if(dataSetRow["creatorId"]){
value = dataSetRow["orderCreator"];
}
else{
value = '';
}
//To be clear, this isn't assigning to anything - this is the same expression you have in your question.
dataSetRow["user_id"] != value
You could use that expression, which returns a boolean, in an if block, for example:
if(dataSetRow["user_id"] != value){
//Do something
}

"Is not a function" error message at string modification with JavaScript?

I'm trying to modify the value of a string given a condition in a ternary operator statement:
($.trim($("#la").val())) ? a = $("#la").val() : a = 'NaN'
However I'm getting the error message:
"NaN" is not a function
What have I got wrong?
You'd generally do that like this
var a = $.trim($("#la").val()).length ? $("#la").val() : NaN;
or in this case, where an empty string would be falsy, you could do
var a = $('#a').val() || NaN;
The issue with NaN not being a function is probably because you quoted it, so it's a string, but unquoting it wont make it a function, it's still a native property!
var a = ($.trim($('#la').val()).length > 0) ? $('#la').val() : 'NaN';
should give you what you want.
Try this one:
var value = $("#la").val();
var a = ($.trim(value).length>0) ? value : 'NaN';

Can someone please explain this syntax in Javascript - " type = type || 'fx' " [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does this construct (x = x || y) mean?
I've seen this code here. And some similar code on other places that I can't recall.
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
What does it mean?
I don't understand a) at all but I *think* I understand b) like this:
If type is false then type will be equal to "fx" otherwise type will equal whatever it was before.
I'm not sure, but perhaps I'm wrong.
What is this syntax called? Conditional variable? :P I tried Googling for an answer but have no idea what to use in my query.
a)
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
is synonym for
if (jQuery.fx) {
if (jQuery.fx.speeds[time]) {
time = jQuery.fx.speeds[time];
}
}
which is almost the same as
b)
type = type || "fx";
is synonym for
if (!type) {
type = "fx";
}
Simply it checks if type is not false, null, undefined. If yes, type is being filled with fx
For A, what we're doing is a shortcut for an if-else statement. The stuff before the question mark refers to the if statement, the next element is the "then" statement, and the final part is the "else" statement.
var action = my_status == 'hungry' ? 'eat' : 'do not eat';
In this case, it would translate into something like this:
if (my_status == 'hungry')
action = 'eat';
else
action = 'do not eat';
For B, double pipes (||) mean "or". What we're evaluating here is a Boolean value based on whether one OR the other is true.
var not_hungry = ate_lunch || full;
If either ate_lunch OR full is true, the not_hungry is also true.
You can do the same thing with double ampersands (&&) which mean AND.
var single = nerdy && cocky;
If nerdy AND cocky are true, then single is also true. If only one of those is true, then the statement resolves to false (since both must be true for single to be true).
Hope that helps. :)
Edit (h/t Phrogz):
It's worth noting that || and && in JavaScript don't only operate upon and evaluate to a Boolean value, but rather are "guard" operators that test for 'truthiness' and evaluate to one of the two operands. (
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
Can be written as:
if (jQuery.fx) {
if (jQuery.fx.speeds[time]){
time = jQuery.fx.speeds[time];
}
}
In this case the ternary operation (? :) is redundant. The statement returns time if JQuery.fx.speeds[time] doesn't exist - so it returns itself.
More general: somevar = a || b is called short circuit evaluation. Basically it's a short way of writing
if (a) {
somevar = a;
} else {
somevar = b;
}
a) Set time to jQuery.fx.speeds[time] if and only if jQuery.fx and jQuery.fx.speeds[time] exists:
if(jQuery.fx && jQuery.fx.speeds[time])
time = jQuery.fx.speeds[time];
b) Your description is correct
a.) is structured using ternary operator, in simple term think of
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
as equivalent to:
time = if(jQuery.fx){ jQuery.fx.speeds[time]; } else { time : time; }
b.) you are correct in that type will be defined if type is already defined, otherwise it'll default to "fx". However, I'm not sure if there's a technical name for it except it is the logical expression for OR
Yes, you're right about what it does. It's known as short-circuit evaluation. It does something similar to C's ternary operator.
It's a ternary operator
http://en.wikipedia.org/wiki/Ternary_operator
I was trying to link to the first result here...
https://www.google.com/#hl=en&cp=4&gs_id=1j&xhr=t&q=wiki+inline+if&

How does javascript logical assignment work?

In javascript, if we have some code such as
var a = "one";
var b = q || a;
alert (b);
The logical OR operator will assign a's value to b, and the alert will be "one."
Is this limited to assignments only or can we use it everywhere?
It seems an empty string is treated the same as undefined. Is this right?
How does this work with AND variables? What about combinations of them?
What is a good example of when to use these idioms, or when not to?
For your q || a to evaluate to a, q should be a 'falsy' value. What you did is called "Short circuit evaluation".
Answering your questions:
The logical operators (like and - &&, or - ||) can be used in other situations too. More generally in conditional statements like if. More here
Empty string is not treated as undefined. Both are falsy values. There are a few more falsy values. More here
AND, or && in JavaScript, is not a variable. It is an operator
The idiom you have used is quite common.
var x = val || 'default'; //is generally a replacement for
var x = val ? val : 'default' //or
if (val)
var x = val;
else
var x = 'default';
The way || works in Javascript is:
If the left operand evaluates as true, return the left operand
Otherwise, return the right operand
&& works similarly.
You can make use of this for in-line existence checks, for example:
var foo = (obj && obj.property)
will set foo to obj.property if obj is defined and "truthy".
I'm not quite sure I follow your question. You can use an expression anywhere you can use an expression, and a logical operator on two expressions results in an expression.
alert(q||a);
alert(true||false);
var x=5;
var y=0;
if (y!=0 && x/y>2) { /*do something*/ }
The last bit is useful. Like most languages, Javascript 'short-circuits' ANDs and ORs. If the first part of an AND is false, it doesn't evaluate the second bit - saving you a divide-by-0. If the first part of an OR is true, it doesn't evaluate the second.
But you can use boolean operators anywhere you can use an expression.
Javascript evaluates logic by truethness/falseness. Values such as (false, "", null, undefined, 0, -0) are evaluated as logic false.
Combine this with the lazy evaluation, 'OR' operations are now evaluated from left to right and stops once true is found. Since, in your example, the truthness is not literally a boolean, the value is returned.
In this case:
x = 0; y = 5; alert(y || x)/*returns 5*/; alert(x || y)/*also returns 5*/;
this can also be other objects.
functionThatReturnsTrue() || functionThatDoesSomething();
This behavior is shared with other scripting languages like Perl. The logical OR operator can be used as a syntactic shorthand for specifying default values due to the fact that the logical OR operator stops evaluating its operands when it encounters the first expression that evaluates to true: "evaluate the first operand and if the value is interpreted as not false, assign it. Otherwise repeat for the second operand."
I find I often use this behavior to specify default values for function parameters. E.g.
function myFunction(foo, bar) {
var fooValue = foo || "a";
// no need to test fooValue -- it's guaranteed to be defined at this point
}
IMHO - don't use for boolean type assignment. It can be confusing. As undefined !== false, ie false itself is a value.
E.g. If u want to copy a field value from an object if and only if that field is defined
var bar.value = false;
var foo = true;
var foo = bar.value || foo; // ==> should be false as bar.value is defined
For boolean type assignment, u should really use
var foo = (bar.value !== undefined) ? bar.value : foo;

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

Categories

Resources