javascript return when stopping function [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 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.

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);
}
}

Why use a while loop for a game loop? [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 3 years ago.
Improve this question
Just wondering, is there a specific reason to use a while loop as the game loop. Or could I use another method, like this one.
Note: this is not proper code, and has not been tested. This is just a general idea. This example is also not consistent to a specific coding language, but may follow mostly JavaScript because that's the coding language I know off the top of my head. I've actually tried something similar to this in dart (google flutter).
var startTime;
var running = false;
function loop1(){
startTime = system.currentMillis();
loop2();
}
loop2(){
gameUpdate();
//ignore my math, I did not focus on doing that property
//this is just an example and is not proper math
var delay = 1000 / (system.currentMillis() - startTime);
setTimeout(loop3, delay);
}
loop3(){
if(running){
loop1();
}
}
edit: could using something like this to avoid the need to use sleep(); be helpful to performance? (or phone battery)
It is perfectly possible to use your code as a main game loop. The reason why a while is preferred is because a main game loop executes endlessly until aborted, this is done simply with while (true) and aborting somewhere inside with break, or with while (abort == false) and setting abort = true somewhere inside. Notice that other loop variants such as for and do-while are more verbose, unless your language let's you do for (;;). Also note that you can restructure your proposed loop to a more simpler version using a while loop.

Is it bad to have If-instanceof-statements in Typescript? [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 4 years ago.
Improve this question
selectAction: (actionEvent) => {
if (actionEvent instanceof Action1) {
// action1 body implementation
} else if (actionEvent instanceof Action2) {
// action2 body implementation
}
}
The above code snippet reflects that different types of action which does different functionalities.I have used if and else condition to check action.
I feel it's not a good solution since I might have more actions in the future and my if-else-ladder will keep growing and I need to update my code again when there is a change.
Any idea on improving this specific scenario?
Use the approach of duck typing to avoid conditional scenarios. Source
Have a method called selection() inside each type instance Action1 and Action2 so- on and use that to define the body/desired functionality you want to build. And simply call selection() method avoiding condition. So based on the instance of the type it will call the correct selection() method of the corresponding type
There's nothing inherently wrong with using if/else in TypeScript.
However, when you're using instanceof, the odds are that you probably have a better option available. In this case, almost certainly, the actions themselves should be responsible for doing what they do:
selectAction: (actionEvent) => {
actionEvent.execute();
}
...or
selectAction: (actionEvent) => {
const action = /*...derive action from actionEvent...*/;
action.execute();
}
...or similar (or of course, use actionEvent.execute() directly instead of selectAction).
This is fundamentaly polymorphism, having different objects conforming to the same interface, and doing (potentially) different things when called.

Javascript appears to be saying true == false [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have the following js function.
function showAttentionItem(sender)
{
debugger;
var assistanceRequired = sender.parent().hasClass("assistanceRequired");
if (assistanceRequired)
{
sender.children('.assistanceRequiredText').fadeToggle(0);
if (sender.children('.assistanceRequiredText').is(":visible"))
{
sender.children('.studentPerformanceText').hide();
}
}
if (!assistanceRequired)
{
if (sender.parent().hasClass("studentOutsideTargetRange"))
{
sender.children('.studentPerformanceText').fadeToggle(0);
}
}
}
What happens when I run it is, I hit the debugger line, and step through the code. assistanceRequired is true.
After executing sender.children('.studentPerformanceText').hide();, the next line it jumps to is sender.children('.studentPerformanceText').fadeToggle(0);, inside the if (!assistanceRequired) statement!
How could this possibly be happening?
This is guaranteed to work:
if (sender.parent().hasClass("assistanceRequired"))
{
// do whatever here
}
else
{
// do whatever ELSE here
}
Only one or the other can ever run when coded correctly since there is only one test and it will either be true or false the single time it is tested. There is no possibility for it to be changed by some side effect you are not aware of, which is most likely what is happening. This is not debatable.
If this does not work the way you want then something else is wrong that you are not showing and without an executable jsFiddle good luck convincing anyone that a fundamental thing like the if ... else construct is broken.
I can think of only one scenario to explain what you are seeing.
There's a double trigggering of showAttentionItem(), which, in the debugger, is perceived as a single call. On the first call, assistanceRequired is true and on the second it's false.

Jquery: stop a code from finishing or ignoring the rest of it if a certain condition is set? [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 9 years ago.
Improve this question
Can we stop a code from finishing or ignoring the rest of it if a certain condition is set?
For instance,
var breakme = false;
if(breakme === true) break;
....
....
bla bla bla the rest of the code
....
...
is it possible?
If your if statement is in an function you can use "return false" to break out of the function.
Example:
function myFunction() {
if (true) {
return false;
}
alert("Hey I'm executing other code");
}
The alert will never be executed as long as your statement is true.
Depends on why you want to do it, but the easiest way to terminate an entire script is to throw an error (assuming your block isn’t wrapped in a try):
throw new Error();
If you meant a function, it’s return. Node has a process.exit().

Categories

Resources