Ternary short circuit vs If short circuit in JavaScript - javascript

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.

Related

Javascript “!” How to interpret the operator?

I cannot interpret this code block. "(! control)" should return true, but the actual value from the foreach function is not running this part, but the "else" part that runs the "false" value below. How is this possible?
let control = false; // False Döndürdük
const filmlist = Storage.getFilmsFromStorage();
filmlist.forEach(function (film) {
if (title === film.title) {
control = true;
}
});
if (!control) // ıs return true? {
const newFilm = new Film(title, director, url);
UI.addFilmToUI(newFilm);
Storage.addFilmToStorage(newFilm);
UI.displayMessages("success", "Film basarili eklendi");
UI.clearInputs(titleElement, directorElement, urlElement);
e.preventDefault();
} else {
UI.displayMessages("danger", "Eklemeye calistiginiz film sistemde mevcuttur");
}
The logical NOT (!) operator (logical complement, negation) takes truth to falsity and vice versa. It is typically used with Boolean (logical) values. When used with non-Boolean values, it returns false if its single operand can be converted to true; otherwise, returns true.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT
let state = true;
console.log(!state)
NOT logical operator
In programming, we use the ! operator followed by a boolean to indicate the contrary.
For example, if we have this code here:
let num = 2;
if(!num){
console.log("This will not reach");
} else {
console.log("This will reach");
}
In this example, the expected output is "This will reach", because the expression will evaluate the number as true (I recommend that you look about falsy values in Javascript and the difference between equality and strict equality operators).
So, you can read it as: If num is not true.
Actually, you could use it to transform boolean values as a switch:
let isOn = true
toogleSwitch(){
isOn = !isOn;
}
This will change the value of the isOn variable to it's respective boolean contrary. If is set primary true, after executing the toggleSwitch, it will be false.

if statements and return var === somethingElse

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

what does && return in javascript expression

I was reading the javascipt code in some application and code was this
getTotalFees:function(){
return this.grid
&&this.grid.getStore().sum('fees');
}
Now i am confused what it will return.
IT looks to me like
return a&&b
won't it return true or false rather than b
Logical AND (&&):
expr1 && expr2 Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
Source
So, basically:
If the first parameter is falsy, it returns that parameter. Else, it literally returns the second parameter.
In your case, this means that, if this.grid exists, it returns this.grid.getStore().sum('fees');
This is done to protect against calling a method on undefined property, witch would cause an error. So if this.grid is undefined, then undefined is returned.
In expressions if a && b when a equals to false (or in javascript it can be an expression like in Cerburs answer), then a is returned.
Similarly with || operator, the first from the left that equals to true (in javascript not 0, not undefined, not null, not NaN, and not false of course) is returned.
You misunderstand what && does. Let a and b be "entities". Then a && b does:
evaluate a
if a is falsy return a
if a is truthy evaluate b
return b
Example:
var f = function() {
console.log("test");
return 'foo';
}
> 0 && f()
0
> 1 && f()
test
"foo"
Note that in first case we didn't get console.log because f() was not evaluated because 0 is falsy. This property is important and actually
a && b != b && a
even though mathematically it should be the same (but it is not due to side-effects of evaluation).
Falsy values include: 0, false, "" (empty string), null, undefined,NaN (not a number type). I don't think there are any other possible values (someone correct me if I'm wrong). Every other object is truthy.
So in your case the code can be rewritten as:
if (this.grid) {
return this.grid.getStore().sum('fees');
} else {
return this.grid;
}
Ok, let's assume that this.grid.getStore().sum('fees') returns something, let's say "okay!".
now the return statement in your code is a convoluted way of saying :
if(this.grid)//this.grid is defined and doesn't evaluate as 'false'
return this.grid.getStore().sum('fees');
else
return this.grid;
if this hasn't got a grid, we return undefined, else we call gridStore... and return its own return.
It is a common way of avoiding "undefined has no method 'gridStore'"
the VERY important part is that, in a && f(), f() will NOT be called if 'a' evaluates to false. there are many things that evaluate to false, such as any undefined variable, null, empty strings... (note that strings that contain falsy things like "false" or "0000" are actually truthy). or even unreadable babble like function(){return null;}(); may evaluate as false.

Is there a simple way to toggle a javascript variable between true and false ?

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.

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