Make shorter code in javascript using if else conditions - javascript

I know about the ternary expression in javascript. However i don't know how to make this piece of code shorter.
if (x == false) {
x = true;
cancelAnimationFrame(BI.req);
}
else {
x = false;
BI.req = requestAnimationFrame(BI.fn.animate);
}
I guess I can make two separate functions and use them with the ternary expression. Something like this:
function cancel() {
x = true;
cancelAnimationFrame(BI.req);
}
function request() {
x = false;
BI.req = requestAnimationFrame(BI.fn.animate);
}
x == false ? cancel() : request();
But this doesn't feel like I am really making my code much shorter. Any suggestions will be much appreciated.

You can use ternary for the functions. And use ! operator to set x
x ? BI.req = requestAnimationFrame(BI.fn.animate) : cancelAnimationFrame(BI.req)
x = !x
Or even more shorter
(x = !x) ? cancelAnimationFrame(BI.req) : BI.req = requestAnimationFrame(BI.fn.animate)
The question was about shorter code so I answered this. Otherwise your own snippet is fine or consider Nina Answers because these two lines are completely non-readable.
You shouldn't use ternary operator like that too. Don't use ternary operator instead of if-else whenever there are two or move expressions in any block.

You could shorten it a bit by moving the assignment to the bottom and use a positive check.
if (x) {
BI.req = requestAnimationFrame(BI.fn.animate);
} else {
cancelAnimationFrame(BI.req);
}
x = !x;

Related

In Angular, what does the double pipe ('||') mean? [duplicate]

People often write this in order to specify default values:
var thing = this || that;
which is, AFAIK, the same thing as this:
var thing = !!this ? this : that;
What do you call the technique used to specify defaults in the first code block?
NOTE: I am not asking what a logical OR is called. I am asking what the alternative to ternary notation (as written in the first code block) is called.
I'd call:
var a = A || B;
conditional assignment, since it is effectively:
if (!!A) {
a = A;
} else {
a = B;
}
and it is a replacement for the conditional operator : ?
var a = A? A : B;
It might also be called "logical assignment" since it involves a logical OR expression, but it doesn't seem to fit with what it's doing.
As mentioned elsewhere it is a logical OR.
The evaluation in question is a short-circuit evaluation.
It might help to look at it like this:
if ((foo = bar)) {
} else {
foo = baz;
}
The if statement evaluates to the value of bar. If bar is false, null etc the evaluation would be false.
Edit: Note:
It is perfectly valid to evaluate an assignment. If we say:
if ((a = b)) { ...
note that it is not:
if (a === b) { ...
the evaluation is done on the result of the assignment. Here it would evaluate to true if (b).
One should however always wrap them in parenthesis. This makes it clear that we are evaluating the assignment and not comparing the variables.
If one do not like it that is fair enough, (I'm rather used to it from C), but in this case it is merely for the sake of the answer to the question.
In the same way we have:
if ((foo = foo)) {
} else {
foo = baz;
}
var x = false;
console.log((x = x)); // False
As such we can say:
(x = x) || (x = y)
And to make it short:
x = (x || y);
or shorter:
x = x || y;
The double pipe is called the 'or' operator.
The double pipe is the Logical OR operator in JavaScript.
If the technique had a name I guess it would be "(ab)using the short-circuiting of the logical OR operator"

How to return(true/false) in ternary operators in jQuery/Javascript?

How to use return in ternary operator in jQuery?
myfunc: function() {
for(i = 0; i < 10; i++) {
(6 == i) ? Do_This_and_This : return true;
}
//Error: Expected an operand: but found return false or true.
}
As per understanding return false will return back to function and breaks the loop and return true will work as continue which moves to next iteration.
Please validate understanding and provide solution for same. If there is another way to do it please suggest
UPDATE: My solution have big javascript and i have put small snippet for an instance that what it is doing.
Like in for there are nested ifs` and nested ternary operators too. Lets give more snippet
myfunc: function() {
for(i = 0; i < 10; i++) {
($.inArray(questionNumber, questions) > -1) ? ((Ra === "") ? Report= Report+"<tr><td>lakslak</td></tr>" : Report= Report+"<tr><td>lasaaakslak</td></tr>") : return false;
}
}
The ternary operator is used on expressions, not on statements. You cannot put a return inside there - if you need to, use an if statement.
However, in your case can easily move the return outside:
return (6 == i) ? false : true;
Although you'd better do
return 6 != i;
For your updated code, I'd suggest to use
myfunc: function(){
for (var i=0; i<10; i++) {
if ($.inArray(questionNumber, questions) > -1)
Report += (Ra==="") ? "<tr><td>lakslak</td></tr>" : "<tr><td>lasaaakslak</td></tr>";
// or even
// += "<tr><td>"+(Ra===""?"lakslak":"lasaaakslak")+"</td></tr>";
else
return false;
}
}
You cannot use a conditional operator to return in one case but not the other, because return is a statement, and the conditional operator's operands are expressions, not statements. In JavaScript, you can use an expression where a statement is expected (it becomes an ExpressionStatement), but not vice-versa.

What do you call the double pipe in javascript, as used in this context?

People often write this in order to specify default values:
var thing = this || that;
which is, AFAIK, the same thing as this:
var thing = !!this ? this : that;
What do you call the technique used to specify defaults in the first code block?
NOTE: I am not asking what a logical OR is called. I am asking what the alternative to ternary notation (as written in the first code block) is called.
I'd call:
var a = A || B;
conditional assignment, since it is effectively:
if (!!A) {
a = A;
} else {
a = B;
}
and it is a replacement for the conditional operator : ?
var a = A? A : B;
It might also be called "logical assignment" since it involves a logical OR expression, but it doesn't seem to fit with what it's doing.
As mentioned elsewhere it is a logical OR.
The evaluation in question is a short-circuit evaluation.
It might help to look at it like this:
if ((foo = bar)) {
} else {
foo = baz;
}
The if statement evaluates to the value of bar. If bar is false, null etc the evaluation would be false.
Edit: Note:
It is perfectly valid to evaluate an assignment. If we say:
if ((a = b)) { ...
note that it is not:
if (a === b) { ...
the evaluation is done on the result of the assignment. Here it would evaluate to true if (b).
One should however always wrap them in parenthesis. This makes it clear that we are evaluating the assignment and not comparing the variables.
If one do not like it that is fair enough, (I'm rather used to it from C), but in this case it is merely for the sake of the answer to the question.
In the same way we have:
if ((foo = foo)) {
} else {
foo = baz;
}
var x = false;
console.log((x = x)); // False
As such we can say:
(x = x) || (x = y)
And to make it short:
x = (x || y);
or shorter:
x = x || y;
The double pipe is called the 'or' operator.
The double pipe is the Logical OR operator in JavaScript.
If the technique had a name I guess it would be "(ab)using the short-circuiting of the logical OR operator"

Replace conditional operator with if/else automatically?

A specific JS parser (not in my control) does not understand nested conditional operator syntax like this:
return num === 1 ? condition ? condition : something : something;
Hence, I would like to replace all conditional operators (simple and nested) in a file with if/else blocks. How do I go about it? (A regexp for Textmate or similar would be helpful.)
How do I go about it? (A regexp for Textmate or similar would be helpful.
I don't think this is possible with regular expressions - you would need to parse the whole JS expression grammar with them. Of course you might use them to find appearances of ternary operators, but replacing them would need to be done by hand.
This is because conditional operators form expressions, while if/else structures are statements. That means you will need to lift the statement containing the ternary operator around the if-else. There are two solutions to transform the general
<some statement ( condition ? then-expression : else-expression) >
if ( condition ) {
<some statement then-expression>
} else {
<some statement else-expression>
}
var helper;
if ( condition )
helper = then-expression;
else
helper = else-expression;
<some statement helper>
Which of them to choose depends on the complexity of the some statement (for your return-statement I'd opt for #1). And since the replacements bring their own syntax rules, you even might need to adapt the surrounding blocks. All this is not a trivial task, and imho could be automated only if you already had a parsed AST to transform.
One idea would be to transform x ? y : z into (x && y) || z. You're still probably going to have to do some fairly fancy parsing to find the ternary operators, but at least you can leave them as expressions rather than statements which will mean the changes needed are much less extensive. Note however that there might be cases where these two things are not exactly equivalent (e.g. if y is 0) so use this approach with caution and only when you have some control over what code it will be applied to.
The idea of (x && y) || z is that when x is truthy, it evaluates to y, and when x is falsey, it evaluates to z. This works due to some edge-cases in the way that JavaScript handles short-circuiting for non-Boolean values. It's sort of a generalization of standard boolean arithmetic. Essentially, JavaScript will return the last value that it needed to inspect in order to perform the operation. So true && (stuff) returns stuff, whereas false && (stuff) returns false. Likewise true || (stuff) returns true, whereas false || (stuff) returns stuff.
There are two cases to check to show that (x && y) || z (mostly) does what we want:
Case 1: x is truthy
Since x is truthy, (true && y) || z evaluates to y || z. If y is also truthy, then this evaluates to y and we get our desired behavior. If y is not truthy, the operation fails and we get z instead!
Case 2: x is falsey
Since x is falsey, (false && y) || z evaluates to false || z, which in turn evaluates to z. Here we are lucky and always get the desired behavior regardless of y.
Example
Here's an example of the desired behavior in the chrome console:
> var x1 = "a" //truthy
> var x2 = "" //falsey
> var y = "y"
> var z = "z"
> (x1 && y) || z
"y"
> (x2 && y) || z
"z"
Just watch out for cases where y is not truthy!
> var y2 = 0
> (x1 && y2) || z
"z"
For future researchers, I'd like to offer my solution approach for these cases where I want to improve conditional statements, either through the ternary operator, switch statements, or traditional if/if else/else statements.
It is already known by many that the use of an object literal for this purpose is a good practice, especially when you have several options and a given parameter that you can use to index this object. Give an example below.
ternary operator version
const getAnimalSpecies = (sound) =>
sound === 'bark'
? 'Dogs'
: sound === 'meow'
? 'Cats'
: sound === 'howl'
? 'Wolfs'
: 'Not animal found';
switch statement version
const getAnimalSpecies = (sound) => {
switch (sound) {
case 'bark':
return 'Dogs'
case 'meow':
return 'Cats'
case 'howl':
return 'Wolfs'
default:
return 'Not animal found'
}
}
if/if else/else statement version
const getAnimalSpecies = (sound) => {
if (sound === 'bark') {
return 'Dogs';
} else if (sound === 'meow') {
return 'Cats';
} else if (sound === 'howl') {
return 'Wolfs';
} else {
return 'Not animal found';
}
};
object literal version
const getAnimalSpecies = (sound) => {
const animalSounds = {
bark: 'Dogs',
meow: 'Cats',
howl: 'Wolfs'
}
return animalSounds[sound] ?? 'Not animal found'
}
All these statements return the same results!
getAnimalSpecies('bark') // Dogs
getAnimalSpecies('purring') // Not animal found
But I think you can agree with me that the last one it's prettier and cleaner.
Beyond that, I found myself in a different situation, where the results were given by Booleans obtained by the parameter already processed. Sound complex ha 🤭!? Lets put two examples.
First one
ternary operator version
const imageExtensionAtEnd = /\.(jpe?g|png|gif|tiff?|webp|bpm|jfif)$/i;
const pdfExtensionAtEnd = /\.(pdf)$/i;
const audioExtensionAtEnd = /\.(mp3|amr|aac)$/i;
const videoExtensionAtEnd = /\.(ogm|wmv|webm|ogv|mov|asx|m4v|mp4|avi|3gp|mkv|mpe?g)$/i;
const getFileType = (file) => {
const type = imageExtensionAtEnd.test(file)
? 'image'
: videoExtensionAtEnd.test(file)
? 'video'
: pdfExtensionAtEnd.test(file)
? 'application'
: audioExtensionAtEnd.test(file)
? 'audio'
: undefined;
return type;
};
object literal version
export const getFileType = (file) => {
const fileTypes = {
[imageExtensionAtEnd.test(file)]: 'image',
[videoExtensionAtEnd.test(file)]: 'video',
[pdfExtensionAtEnd.test(file)]: 'application',
[audioExtensionAtEnd.test(file)]: 'audio'
};
return fileTypes['true'] ?? undefined;
};
Second one
conditional version
import { useMediaQuery } from '#material-ui/core';
const defaulValues = ['', '', '', '', ''];
const useMediaVariant = (values = defaulValues) => {
const [xs, sm, md, lg, xl] = values;
if (useMediaQuery('(max-width:600px)')) {
return xs;
}
if (useMediaQuery('(min-width:600px)')) {
return sm;
}
if (useMediaQuery('(min-width:960px)')) {
return md;
}
if (useMediaQuery('(min-width:1280px)')) {
return lg;
}
if (useMediaQuery('(min-width:1920px)')) {
return xl;
} else {
return values.at(-1);
}
};
object literal version
const useMediaVariant = (values = defaulValues) => {
const [xs, sm, md, lg, xl] = values;
const variant = {
[useMediaQuery('(max-width:600px)')]: xs,
[useMediaQuery('(min-width:600px)')]: sm,
[useMediaQuery('(min-width:960px)')]: md,
[useMediaQuery('(min-width:1280px)')]: lg,
[useMediaQuery('(min-width:1920px)')]: xl
};
return variant['true'] || values.at(-1);
};
export default useMediaVariant;
It is used liked this example:
import useMediaVariant from '.../hooks/useMediaVariant';
const valueHeading = useMediaVariant(['subtitle2', 'h8'])
<Typography variant={valueHeading} />
The second one is a custom hook I create to apply responsiveness in some material-ui components props...
Note that when you use the object['true'] method the last occurrence found will be the one returned. Important thing if there is more than one truthy possibility.
Hope to help someone.

Javascript shorthand if-else and returning

Can the javascript shorthand for if-else return out of a function? If so how would this work.
eg.
I have this:
if(boolean){
return;
}
and I would like to write it as this:
(value)? return;
Chrome complains that return is unexpected. Is there anyway to write something like this so that it is valid?
No, you can't do that unless you return a value. For example if your function had to return a value you could have written:
return boolean ? 'foo' : 'bar';
But you cannot stop the execution of the function by returning void using the conditional operator.
If you intend to return from the function at this point in its execution regardless of whether the test evaluates true or false, you can use,
return (value) ? 1 : 2;
But if you merely wish to return early when a test evaluates true (for instance, as a sanity-check to prevent execution when parameters are invalid), the shortest you can make it is:
if (boolean) return;
if(boolean) return;
Single line , readable , perfectly valid;
I know it's an old question but I want to add that there is a non-standard way to return out of a function in shorthand if-else, and that is performing Immediately Invoked Function Expression (IIFE):
function outOfFunction(boolean){
return (boolean)?(()=>{return true;})():(()=>{return false;})();
}
console.log(outOfFunction(true));
console.log(outOfFunction(false));
And if we want to be out of the function or continue with other task:
function shorthandExampleJustTrue(boolean){
var someVar = "I'm out";
return (boolean)?(()=>{return true;})():(()=>{
console.log("here my code ");
console.log(someVar);
return "anythig else";
})();
}
console.log(shorthandExampleJustTrue(true));
console.log(shorthandExampleJustTrue(false));
When we use arrow functions we are able to access to variables out of the immediate function context.
You want to do a ternary operator
which is this:
(bool) ? ifTrue : ifFalse;
Please note: you cannot omit the else portion of a ternary operator.
http://en.wikipedia.org/wiki/Ternary_operation
The conditional "ternary operator" (condition ? expression to evaluate when true : expression to evaluate when false) is often used for simple conditional variable assignment.
if you need :
if( x > 0) {
a = 10;
}else{
a = 30;
}
you can write:
a = (x>0)? 10 : 30;
You can think of it like a simple function, which takes 3 parameters (p1, p2, p3), if p1 is true it returns p2 and if p1 is false then it returns p3.
(p1)? p2 : p3;
And just like such a function, there's no way for it to cause the parent function to return based on the condition. It is not therefore a shorthand for if/else.
if I'm not mistaken you're talking about this right? a short-hand.
return (if the value here is true then ->) && false
example:
const isGood = true && "yeah";
console.log(isGood) //yeah
Use this as your short hand if the value is true then it will return false; using the && operator is better

Categories