Another way of writing an if statement? - javascript

It may sound a bit stupid, but is there a shorter way of writing the following if statement in less words :
if(auxiliars.environment == "Development") {
less.env = "development";
less.watch();
}
Because I have that statement as part of a function :
set_environment: function(environment) {
if(auxiliars.environment == "Development") {
less.env = "development";
less.watch();
}
}
And I was wondering if I can somehow return that two lines of code :
less.env = "development";
less.watch();
The main reason I'm asking is because in PHP I'm doing something like the following :
return (!empty($len)) ? hash('sha512', str_pad($stream, (strlen($stream) + $len), substr(hash('sha512', $stream), $this->round(strlen($stream) / 3, 0), ($len - strlen($stream))), STR_PAD_BOTH)) : hash('sha512', substr($stream, $this->round(strlen($stream) / 3, 0), 16));
And I was wondering if I can do something similar in JavaScript.

Not really, why would you want? Your if statement is clean and easily to understand.
Yet, you might try the ternary operator:
auxiliars.environment == "Development"
? ( less.env = "development", less.watch() )
: void 0;
But using the comma operator doesn't make your code better.

Javascript has the ? : statement, if that's what you are asking.
So
var x = 5;
var y = (x < 10) ? "bar" : "foo";
will assign the string "bar" to y.

Yes, you can use the ternary operator

Related

JavaScript with coffescript syntax- if condition : optimize if statement structure

I have a function and I'm testing 4 variables, I want to optimize the structure of my if statement test, can some one help ? :
$scope.filterActivated = ->
if $scope.postParams.options.scopes.report.from || $scope.postParams.options.scopes.report.to || $scope.postParams.options.template_id || $scope.displayOptions.query.length > 0
return true
else
return false
you can remove true/false and optimize it a little bit like this:
$scope.filterActivated = ->
options = $scope.postParams.options
options.scopes.report.from or options.scopes.report.to or options.template_id or $scope.displayOptions.query.length > 0
Edit: JS for you:
$scope.filterActivated = () => {
let options = $scope.postParams.options;
return options.scopes.report.from || options.scopes.report.to || options.template_id || $scope.displayOptions.query.length > 0;
};
Not sure what you mean by optimizing, but a shorthand of that could be:
$scope.filterActivated = ->
$scope.postParams.options.scopes.report.from
|| $scope.postParams.options.scopes.report.to
|| $scope.postParams.options.template_id
|| $scope.displayOptions.query.length;
Edit:
Initially, I used the ternary syntax, but that's not supported by CoffeeScript. For reference Ternary operation in CoffeeScript
Edit 2:
Reduced it a bit more, #user633183 suggested using Boolean but I think this gives the same result.

JS Ternary functions with multiple conditions?

I have been using a ternary operator in JavaScript to modify the value of an object based on user input. I have the following code, which runs as it should:
var inputOneAns = inputOne == "Yes" ? "517" : "518";
As you can see, I am assigning a numeric string value to inputOneAnswhether a user has inputed "Yes" or "No". However, there may be a case that a user has not selected a value (as it is not required). If this input was left blank, I would like to assign an empty string "" to inputOneAns. Is there a wayf or me to embed an ternary operator inside of another ternary operator? To help clarify, here is the same function that I want to accompolish with my ternary function but with if else statements?
if (inputOne == "Yes"){
var inputOneAns = "517"
}else if (inputOne == "No"{
var inputOneAns = "518"
}else{
var inputOneAns = ""
}
Is it possible to include multiple expressions into a ternary function? Is there a better way to accomplish what I am looking for? Thanks for the tips in advance.
Yes you can go wild nesting ternaries. I find this version to be fairly readable:
var foo = (
bar === 'a' ? 1 : // if
bar === 'b' ? 2 : // else if
bar === 'c' ? 3 : // else if
null // else
);
but that's not a widely shared opinion, and you should probably stick to if/else or switch when working on a team.
Yes, you can use multiple condition in Ternary Operator. Hope this will help you.
var x=20;
var y = x<13 ? "Child" : x<20 ? "Teenage" : x<30 ? "Twenties" : "Old people";
console.log(y);
A switch statement is likely the best choice in a situation like this.
let inputOneAns;
switch(inputOne) {
case "Yes":
inputOneAns = "517";
break;
case "No":
inputOneNas = "518";
break;
default:
inputOneNas = "";
}
If you could do ternary operations beyond 2 conditions, they would become incredibly messy. You can put conditions together, but I've no idea why you would want that - that would be incredibly messy.
The most elegant and clean way is to take advantage of Object literals:
const Switch = (str) => ({
"Yes": "517",
"No": "518",
})[str] || '';
console.log(Switch("Yes")); // 517
console.log(Switch("No")); // 518
console.log(Switch("Non matching value")); // Empty
This has the advantage of being both readable and flexible.
Yeh you can chain them together much like using an else if statement, but it can sometimes be a bit hard to read though, so I tend to split mine over multiple lines.
var inputOneAns = inputOne == 'Yes' ? '517' :
inputOne == 'No' ? '518' : '';
However in this case I would suggest a switch statement seeing as you're comparing the same value for every case.
var r = inputOne == "" ? "" : (
inputOne == "Yes" ? "517" : "518");
Unfortunately JavaScript does not provide a super terse and readable way to do this. Personally I would just use some single-line if statements like this:
var inputOneAns;
if (inputOne === 'Yes') inputOneAns = '517';
if (inputOne === 'No') inputOneAns = '518';
else inputOneAns = '';
Which can be even cleaner if you abstract it into a function (note: no need for else in this case):
function getInputOneAns(inputOne) {
if (inputOne === 'Yes') return '517';
if (inputOne === 'No') return '518';
return '';
}
Personally, I don't really like switch statements for this for two reasons: firstly those extra break statements bloating the code, and secondly, switch statements are very limiting - you can only do simple equality checks, and only against a single variable. Besides, in the case that you know you will be always checking a single string I would favour a simple map object:
var map = { 'Yes': '517', 'No': '518' };
var inputOneAns = map[inputOne] || '';
Yes, and it does provide a cleaner code than switch statement.. with all the breaks..
inputOne == "Yes" ? "517" :
inputOne == "No" ? "518" : inputOneAns = "";
Seems like a classic use for a switch statement:
let inputOneAns = '';
switch(inputOne) {
case 'Yes':
inputOneAns = "517";
break;
case 'No':
inputOneAns = "518";
break;
default:
inputOneAns = "";
}
note you don't actually need the default case, but I find it makes things more readable.

Ternary operator displays error in JSHint - Expected an assignment or function call and instead saw an expression

I have a ternary operator dir === 'next' ? ++$currentSlide : --$currentSlide; in my JS used to increment of decrement an integer. when I run my script in grunt JSHint hightlights this line as Expected an assignment or function call and instead saw an expression.
Can anyone advise where I'm going wrong with this? Should I set my condition up differently etc?
You are misusing the conditional operator as an if statement, that's why you are getting that note. The real work in the code is done as a side effect of the expression, and the result of the expression is ignored.
As a real if statement, it would be:
if (dir === 'next') {
++$currentSlide;
} else {
--$currentSlide;
}
You can use the conditional operator if you use it as an actual expression:
$currentSlide += dir === 'next' ? 1 : -1;
In general, for disabling the 'Expected an assignment or function call and instead saw an expression.' warning, you can do /* jshint expr: true */
Does it pass if you write it like this?
$currentSlide = (dir === 'next' ? $currentSlide + 1 : $currentSlide - 1);
Linters and hinters usually don't like in/decrements because they're sensitive to bugs.
Try this syntax:
$currentSlide = (dir === 'next' ? $currentSlide+1 : $currentSlide-1);
make ternary operator in to if else condition
Before:
(pbook.id === book.id ? book.shelf = pbook.shelf : "none");
After:
if(pbook.id === book.id){
return book.shelf = pbook.shelf
} else {
return "none"
};

Javascript setting variable to result or nothing

See javascript comments
var SearchResult = {
googleApiKey: "",
googleUrl: "https://www.googleapis.com/shopping/search/v1/public/products?key={key}&country={country}&q={query}&alt=atom",
country: "UK"
Query: function( args )
{
// Is there a way to do this in a less messy way?
args.googleApiKey ? : this.googleApiKey = args.googleApiKey : null;
args.country? : this.country = args.country: null;
}
}
Basically, if someone supplies a new value for my object properties, I want it to set it, otherwise just continue using the default values supplied.
I'm aware of bitwise operators being good for option selecting but I don't know how I would port that into javascript?
args.googleApiKey = args.googleApiKey || this.googleApiKey;
args.country = args.country || this.country;
Not sure I understood your question;
In JavaScript you can use the following:
// thingYouWantToSet = possiblyUndefinedValue || defaultValue;
this.googleApiKey = args.googleApiKey || '';
The caveat to using this is that if the first value is a zero or empty string, you will end up using the default value, which may not be what you intend. e.g.
var example = '';
var result = example || 'default';
Although example is set, you will end up with the 'default' string. If this causes issues for you, switch to:
(typeof args.googleApiKey === 'undefined')
? this.googleApiKey = 'default'
: this.googleApiKey = args.googleApiKey;
You could make this cleaner using a helper function if you are repeating yourself a lot.
var mergedSetting = function (setting, default) {
return (typeof setting === 'undefined') ? default : setting;
}
this.googleApiKey = mergedSetting(args.googleApiKey, 'default value');

Shorthand for if sentence

Why I am asking
I have been having a lot of trouble understanding the shorthand for the if sentence in JavaScript, and I haven't found an article or tutorial that described it well. And that's why I am stuck opitimizing my little code. And I am new to JavaScript, so if someone could give me a basic understanding of the shortning of this code, I would very much appreciate you telling me the magic behind the code.
What I need help with
I am going to use the exact same code in a lot of functions. Therefore, I want to optimize it and make it shorter version of the code.
function welcomemessage() {
if (br == 1) {
hello();
}
else {
hey();
}
}
Use the ternary operator.
function welcomemessage() {
(br == 1) ? hello() : hey();
}
The ternary operator is useful, and not difficult to understand. here's how it works.
(condition) ? (true) : (false)
Edit:
Since JS treats functions as first class objects, it is possible to create a wrapper. Something like below (not tested though)
function ternaryWrapper(br, functionTrue, functionFalse){
return (br == 1) ? functionTrue : functionFalse;
}
//call it
ternaryWrapper(2,hello, hey);
Even shorter:
function welcomemessage(br){
[hello,hey][br-1](); //This will work.
}
welcomemessage(1); //hello();
welcomemessage(2); //hey();
Fun Fact:1
To make your script hard to read for someone else, do it like this:
function welcomemessage(){
return br==1 && (hello(),1) || (hey(),1); //This will work too.
}
1 Totally not related to the answer.
Update
var something = ( (br == 1) ? hello() : hey() );
something will be the value hello() or hey() returned.
Or:
var msgfuncs = [ hey, hello ];
function welcommessage() { msgfuncs[br](); }
(assumes that when "br" isn't 1 it's 0, which of course may be an invalid assumption.)
If the choice is made with different functions, just put the array directly in the surrounding function:
function welcomemessage() {
[ hey, hello ][br]();
}
If you want to make the decision and save the function to call later, you can do this:
var messageFunction = [ hey, hello ][ br ];
then any time later:
messageFunction();
In case br is always be numeric, the xbonez answer can be optimized a little bit by using strict comparison === (because it is a little bit faster):
function welcomemessage() {
(br === 1) ? hello() : hey();
}
And another interesting option is:
function welcomemessage() {
(br - 1) ? hey() : hello();
}
This last function works because when br is 1, it will turn to 0 (which is a falsish value) and evaluate to false, triggering hello(), and for the rest it will trigger hey()

Categories