Multiple if statements with locks [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have multiple if statements like this:
if (variable == something && lock01 == false)
{
do your thing
lock01=false; lock02=true; lock03=true; ....
}
else
{
lock01=true; lock02=false; lock03=true;
}
This locks all other if statements so only one is active at a time. The problem with this is if I add more if statements, I have to add more locks by hand. It also only works from top to bottom one after another. Is there a better way to do this? If it's easier in Jquery, JQ code is also ok.
edit: I forgot to write that I loop through the if statements and only one can be unlocked at a time.

One option would be to use a variable that identifies which lock is unlocked:
unlocked = "lock01";
// or
unlocked = 1;
Then your code could look something like this:
if (variable == something && unlocked === 1) {
// do your thing
} else {
unlocked = 2;
}

Probably the best thing to do is to use switch statements instead of "n" if/else statements.
So you code will looks like:
switch(variable) {
case 1:
do your things here;
break;
case 2:
do something else;
break;
case 3:
case 4:
when variable is 3 or 4 do the same code
break;
default:
do something else;
lock = false;
}
and so on.
Switch statements works with strings or numbers (as far as I know), just make sure to use quote with strings (e.g.: case 'something').
If you don't want to use switch statements, then use else/if:
if(variable == something) {
do something;
}
else if(variable == something_else) {
do something_else;
}
else {
lock = false
}
This way only the first matched "if" will be executed.

Related

How to escape 2 functions at the same time in Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Does anyone know how does this if statement "escape 2 functions at the same time"
client.on('message', message => {
if (Math.floor(Math.random()*20) === 19) return;
//rest of code
}
Like it escapes its if check and the .on message event.
Also, this is probably a dupe, but I couldn't find what I was looking for or didn't know what to search for.
Just to add, an analogy would be like when you use break; + labels: to stop a loop from going on. See, if I used a return; it would only stop the if statement (in the below code ofc), and the for loop would continue. But if I used a break start; it would also stop the for loop, this is what am trying to do.
start: {
for (var i = 0; i > x; i++) {
if (x === 1) {
break start;
}
//code
}
}
You can't escape the if condition. If you want this to do nothing, then simply return.
client.on('message', message => { return; })
// or, more concisely
client.on('message', () => {})
But this is a strange thing to do, unless you were trying to override the on callback method. But I assume is an event emitter that can have multiple subscribers, so that doesn't make sense either.
I guess what you want do is to detach your listener from emitter on certain condition. You would have to change your calls a little: add a function name and you will be able to adress it its body. Then you just detach your listener when your condition is met:
client.addListener('message', function onMessage(message) {
if (Math.floor(Math.random()*20) === 19) {
client.removeListener('message', onMessage);
}
}

Which piece of code is generally more accepted? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I was wondering which of the pieces of code below are generally more accepted or maybe even better:
function doStuff(check) {
if(!check) {
return "blablabla";
} else if (check >= 5) {
return "blablabla";
} else {
return "blablabla";
}
}
or
function doStuff(check) {
if(!check) {
return "blablabla";
} else if (check >= 5) {
return "blablabla";
}
return "blablabla";
}
Since the return statement makes the JavaScript interpreter leave the current function it is in I don't see a reason to put an else statement at the end of the second example because the only way to get there is if all previously mentioned comparisons resulted false anyways.
Is this just a case of pick whatever the hell you like but be consistent at it or is there an actual rule for this?
I would even go one step further:
function doStuff(check) {
if(!check)
return "blablabla";
if (check >= 5)
return "blablabla";
return "blablabla";
}
But this is a matter of taste. While I find it better to omit unnecessary else statements, I have also heart colleagues say that you should always put this else there to make the control structure clearer... But in such simple cases I would not bother putting them in.
For numeric values, though, I would prefer check == 0 to !check.

JavaScript: Is it allowed to use a `ternary` statement inside an `if` statement? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In the following script, I've used a ternary statement in the else if portion of an if statement, juxtaposing the two. In a case like this, should I substitute another if statement inside the else if?
var attackOpt = prompt('Which attack option does Angelo use in this turn?');
// Remaining number of times Angelo can cast spells:
var angMP = 3;
// Validity Check to see if the attack option entered can be executed:
while (true) {
if (attackOpt === 'slash') {
break;
}
else if (attackOpt === 'magic') {
(angMP) ?
break;
: attackOpt = prompt('Angelo can no longer cast spells. Select again.');
}
}
Yes, it will work but it makes the code difficult to read. Consider revision to your 'while' loop instead:
while (attackOpt !== 'slash' && angMP) {
attackOpt = prompt('Angelo can no longer cast spells. Select again.');
}
Of course, this is a stylistic choice and entirely up to you.
Yes, you can have a ternary operator expression (it's not a statement) anywhere an expression is allowed.
But a ternary operator uses expressions as its 3 arguments. break is not an expression, but a statement. You can't use break there.
You'll have to use an if statement.
You cannot do this. It will result in syntax error and the code won't run. Ternary operator is used to return values quickly without if-else. No breaks are allowed. However, you can use something like that, in a single line:
if (angMP) break; else attackOpt = prompt('Angelo can no longer cast spells. Select again.');
Or even the simpler form in other parts of your code:
if (angMP) break;
not needed it will work properly without any problem
(angMP) ? break : attackOpt = prompt('Angelo can no longer cast spells. Select again.');

'if/else' vs 'if' for performance and readability? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I've recently started using Snippet 2 instead of Snippet 1, for basic selection statements. This seems a bit un-conventional, so I wanted to know if there is performance difference, or if one seems more readable than the other.
Snippet 1
function foo() {
if(case1){
//...
} else if (case2) {
//...
} else if (case3) {
//...
} else{
// catch other cases
}
}
Snippet 2
function foo() {
if(case1){
//...
return;
}
if(case2){
//...
return;
}
if(case3){
//...
return;
}
// catch other cases
}
Your snippets are the same thing. But I'd use elseif even if I return. It kind of gives me a sense that those if statements are related and helps me with readability.
if ... else also helps in performance, let's say, when you're if-ing the same variable. Why test a condition if the previous one succeeded? elseif it so it won't try again.
It's a matter of design. It depends on what you want to achieve so there's no EXACT BEST way of doing it. It's all a matter of how you need to exit your code block that contains the ifs.
The Ifs alone mean that all of the conditions can possibly happen - they'll be checked one by one. The chained if-else statements mean that only one of the conditions can actually happen - if one of the conditions get executed, I believe it skips over all of the rest. Most languages support a switch statement as well, which would be somewhat more readable than chaining together a bunch of if-else-if statements. Correct me if I'm wrong, but I believe this applies in every language I've used so far.
Edit: In this particular case (as pointed out by some others below - thank you), all of the conditions cannot happen because of the return statements in each of the if statements. In a more general case though, my explanation still holds.
It depends on your needs. As a general rule, the more exit points you have to a function, the harder it is to read. That said, there is often benefit of
if(somehting)
{
// one liner;
return;
}
if(something else)
{
// 30 lines of something else.
return;
}
// catchall
instead of:
if(something)
{
// one liner;
return;
}
else if(something else)
{
// now nested! 30 lines.
return;
}
Chances are, though, that you could probably make things even easier to read by turning those conditions into their own functions. Wouldn't this be nice:
if(something)
{
doSomething();
}
else if(something else)
{
doSomethingElse();
}
else
{
doJustElse();
}
The benefit of the last one? Succinct, clear, clean, obvious, and a low learning curve.
If you have too many else if statements then it always better to use switch rather than using if.
Snippet 1 is going to be better for performance when you don't need case 3 to be satisfied, since the other else if will not be fired. However, if you have a lot of other else if, you should use a switch

javascript return when stopping function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
If I write this:
$('#SomeDiv').click(DoSomething);
function DoSomething() {
if (SomeCondition === true) {
return false;
}
// more code here
}
regardless of whether I put return; or return false; or return true; the code doesn't throw exceptions and the function execution stops.
Which is the best option?
If those are the only options, use return; in this case. (read below)
If the function normally returns something (calculates something, gets some value, etc) then you definitely don't want to return anything, because you might confuse the caller.
If your function doesn't normally return anything, then it might not hurt to return anything you like, but it might still confuse callers.
I would personally rather just put an else after the if, and not use the return;. And if the function gets too large, just retractor it a bit.
If you just want to stop the function on some condition and don't care what it returns, then it doesn't matter which of the three you choose. If you're not using the output of the function, I'd just use a simple return; statement to stop it executing further.

Categories

Resources