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
Related
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"
I am trying to short circuit the code to return false with a ternary operator. My understanding was that the ternary had an implicit return and in this case would have the same result as the if statement below it. That would be to immediately return false if the two arrays.length do not match and to pass onto the following logic if they did. I would appreciate some explanation as I have tried to understand the difference but it does not make sense to me why this would not work.
`
function same(arrOne, arrTwo) {
// This ternary and if statement should do the same thing?
// arrOne.length !== arrTwo.length ? false : {}
if (arrOne.length !== arrTwo.length) {
console.log(false)
return false
}
let result = {}
// append frequencies of numbers to result object
arrOne.forEach((i) => {
result[i] ? result[i]++ : (result[i] = 1)
})
// check to see if square matches root in object
arrTwo.forEach((i) => {})
console.log(result)
}
same([1, 2, 3, 4], [4, 1, 9]) // false lengths do not match
// same([1,2,3], [1,9]) // false
// same([1,2,1], [4,4,1]) // false frequency must be the same
`
I have tried to short circuit the function to return false with a ternary operator that tests the length of the two arrays taken as arguments if their lengths do not match. The code runs as if the ternary is doing nothing.
The ternary operator does not implicitly return. Only a return statement returns from a function.
What you are probably confusing is that a ternary operator returns a value. As in, you can assign the result of a ternary expression to something:
var foo = bar ? 'baz' : 42;
This is what it means for the ternary operator to return a value. This does not mean that it will implicitly execute a return and stop a function from processing. It just returns a value the same way 1 + 2 returns a value (3).
A ternary operator isn't useful to conditionally return from a function. Even if a ternary expression would do what you think it does, it would always have to return or never; but you want to return only in certain conditions. E.g. with a ternary you can only do this:
return foo ? bar : baz;
You can decide what to return inline, you cannot decide whether to return or not.
I'm doing the Angular course on codeschool and passed one of the exercises by doing:
this.isSet = function(value) {
if (value === this.tab) {
return true;
}
};
But in the next exercise, my code gets replaced by this:
this.isSet = function(tabName){
return this.tab === tabName;
};
This must be a silly question, but can you bypass an if statement by just using a simple === ?
if value === this.tab, true will be returned, if value !== this.tab, undefined will be returned. In the second example === will return true and !== will return false. Undefined and false are both 'falsy', therefore you can use them in much the same way.
If you re-read your own code you'll see that the if statement does not add anything, and that if it fails, your function will return undefined, which is not optimal, as it's not a boolean value.
It's not a "bypass" (I don't quite understand what you mean by that), but the statement return this.tab === tabName; returns true or false depending on the evaluation result (which will always be a boolean value. I.e. the second code example returns the same value (true) as the first, when the values of value/tabName and this.tab respectively are equal (===).
The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. It's this case where === will be faster, and may return a different result than ==. In all other cases performance will be the same.
See this tutorial for more details: http://www.c-point.com/javascript_tutorial/jsgrpComparison.htm
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"
I have this:
modalTogglePreview: function ($scope) {
if ($scope.modal.wmdPreview === true) {
$scope.modal.wmdPreview = false;
} else {
$scope.modal.wmdPreview = true;
}
}
Is there some way I could achieve the same but without the if statement ?
$scope.modal.wmdPreview = !$scope.modal.wmdPreview;
The unary ! operator interprets its argument as boolean, and returns the boolean complement. Note that this really isn't exactly the same as your code: yours only works if the variable is exactly true when it's tested. In my experience (for what that's worth), relying on variables used as flags in JavaScript to be real booleans is a little fragile. (There are counter-arguments however, so it's up to you.)
To explain further, the ! operator will interpret the values undefined, null, 0, NaN, false, and the empty string "" as being false. Any other value is true.
Aside from using the not operator as Pointy mentioned (which should be the preferred way), if you find yourself setting a boolean value inside an if...else statement, then you are likely doing something wrong.
The condition is already evaluated to a boolean value. So your if...else statement is equivalent to
$scope.modal.wmdPreview = $scope.modal.wmdPreview !== true;
Have a look at these examples:
var result;
if (cond) {
result = true;
}
else {
result = false;
}
This means, if the condition (cond) is true, set result to true. If cond is false, set result to false. The value we assign to result is exactly the value of cond. Hence the above is equivalent to writing
var result = cond;
Now, sometimes we use conditions that don't evaluate to a boolean. To convert any value to its boolean equivalent, you can apply the not operator twice:
var result = !!cond;
Similar for the other way round:
var result;
if (cond) {
result = false;
}
else {
result = true;
}
If cond is true, assign false to result. If cond is false, assign true to result. This is the same as in your situation. The value we assign to result is the opposite of the value of cond. As Pointy showed, we can use the not operator for this:
var result = !cond;
This works with every condition, but depending on the expression, it can make it harder to read. For example, !(x > 5) is not as obvious as x <= 5. So if you find yourself in such a situation, you can usually flip the comparison operator.