This question already has answers here:
Function declarations should not be placed in blocks. Use a function expression or move the statement to the top of the outer function
(2 answers)
Closed 6 years ago.
Why should we avoid call functions inside if conditions in functions? For instance:
var numberChoice = function(number){
if (number == 1){
alert("You have choosen 1");
nextLevel();
}
else if(number == 2){
alert ("You have choosen 2");
nextLevel2();
}
else{
alert("Please choose a number within range 1-2");
guessAgain();
}
};
var number = prompt("What is your number?");
I could possible have missunderstood what's going on. Are you able to give an explanation of it?
function example(){
function a() {} // Okay
if (something) {
function b() {} // Danger!
}
}
Haverbeke, Marijn (2014-12-04). Eloquent JavaScript: A Modern Introduction to Programming (Kindle Locations 1168-1169). No Starch Press. Kindle Edition.
Unless your function (within if condition) is asynchronous there is no problem.
The functions that you are using is synchronous - meaning your script will finish executing it and return a value first before going to next task - in this case it will work fine.
For asynchronous function (which is executed in parallel to the other lines of instructions), then the results from that function is not returned yet and your script will continue without the right value (returned value) from it - this will cause problem.
In your two sample there is no issue.
there is no rule that don't allow you to call function in a if condition.
the only point is a warning when you have several if on the same checking :
if (number === 1) {
function1();
}
if (number === 2 ) {
function2();
}
in that case if you don't put return at the end of your function when the function will be called other condition will be evaluate.
better code is using else or switch
In your case there are no issue.
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 3 years ago.
I am creating a javascript function ( function ask(question) ) that should return either 1 or -1 depending on what button the user presses.
Before I used a prompt :
function askOld(question)
{
var answer;
do{
answer=prompt(question);
if (answer==="yes") return 1;
else if (answer==="no") return -1;
} while (1);
}
which was ugly, but worked. It is important that all this is in a function, because I need to pass it to other functions, and store it in a variable.
Now I am trying to take off the prompt, and use eventListener.
function askTest(question)
{
var answer;
document.querySelector('.domanda_intervista').textContent = question;
document.querySelector('.button_no').addEventListener('click',function(){
console.log("clicked no");
answer="n";
});
document.querySelector('.button_yes').addEventListener('click',function(){
console.log("clicked yes");
answer="y";
});
if (answer==="y") return 1;
else if (answer==="n") return -1;
return 2;
}
answerNow=askTest("is this true?");
console.log("answerNow",answerNow);
But this did not work. So I tried to call it continuously until the user pressed the button but that did not work out as expected...
do{
answerNow=askTest("is this true?");
console.log("answerNow",answerNow);
}while (answerNow===2)
I looked for existing questions here, but none seem to answer this question. Can someone please help?
By the way, I come from Python, Javascript is new to me, so apologize if anything I am asking it obvious/dumb...
This question already has answers here:
Is returning early from a function more elegant than an if statement?
(14 answers)
Is it good style (or more efficient) to "return early" at the top of a function?
(2 answers)
Invert "if" statement to reduce nesting
(25 answers)
Closed 3 years ago.
When writing javascript or PHP for that matter I use two ways to write if statements.
Return as soon as possible
Below I try to end the function as soon as possible. If the value is not what I expect, return it. The benefit I see here is that I don't need {} and I don't need to nest anything.
function hello(value = null) {
if(!value) return;
console.log("I'm still here!");
console.log("End of function");
}
Do something on match
In this case I don't return at all. Instead I do something if I get a "match". The upside here is that I don't need to return anything.
function hello(value = null) {
if(value) {
console.log("I'm still here!");
console.log("End of function");
}
}
So which is better? One of them or equally good?
This question already has answers here:
Are all javascript callbacks asynchronous? If not, how do I know which are?
(5 answers)
Closed 6 years ago.
Will the map function always finish running before the if statement runs? I want to make sure that the elements in the array are always added up before the if statement runs. Will there ever be a time when the map function doesn't finish running before the if statement starts and so the if statement will not get the true value of the add variable?
var arr = [ '33.3%', '33.3%', '33.3%' ];
var add = 0;
arr.map(function(elem){
add += parseInt(parseFloat(elem)*10000)
});
if (add <= 1001000 && add >= 999000) {
console.log("passed!!")
}
Yes. Unless you have asynchronous requests or multi-threaded operations like WebWorkers, your code is synchronous, i.e. it is executed in strict order.
Array.prototype.map of javascript is synchronous, but if you want an async behaviour you can use nodejs async module.
NodeJS Async Map
var async = require('async');
var arr = ['1','2'];
async.map(arr, getInfo, function (e, r) {
console.log(r);
});
function getInfo(name, callback) {
setTimeout(function() {
callback(null, name + 'new');
}, 1000);
}
http://code.runnable.com/UyR-6c2DZZ4SmfSh/async-map-example-for-node-js
This question already has answers here:
Are braces necessary in one-line statements in JavaScript?
(22 answers)
Closed 7 years ago.
I've searched and I can't find a question already like this. However, why does this code work?
this.askTeller = function(pass) {
if (pass == 1234) return bankBalance;
else return "Wrong password.";
};
Shouldn't it be like
this.askTeller = function(pass) {
if (pass == 1234) {
return bankBalance;
}
else {
return "Wrong password.";
};
Shouldn't it be like
Arguably, it should be:
this.askTeller = function(pass) {
if (pass == 1234) return bankBalance;
return "Wrong password.";
};
or
this.askTeller = function(pass) {
return pass == 1234 ? bankBalance : "Wrong password.";
};
E.g., there's no point to the else at all.
But getting to your point about {}: They're optional. Control-flow structures like if (and while, and for, etc.) are connected to the one statement that follows them; if you want to have them connected to more than one statement, you use the block statement ({...}) to do that.
Many, many, many people always use the block statement even when they could get away with not using it, both for clarity and to make it easier to add a second thing into the block.
in Javascript the curly brackets are optional for if/else when you have only one statement after to execute. Note that if you will execute multiple stuff after then you will need to include the {/} or only the first statement will be applied to the condition
You can drop curly braces for nearly all block-scoped structures (if, for, while, etc). The only exception (heh) I've ran into where this isn't the case is with try and catch.
If you don't include curly braces, only the first statement after the block will be executed.
var out = document.getElementById("out");
for (var i = 0; i <= 5; i++) out.innerHTML += i;
if (out.innerHTML === "012345") out.innerHTML += " success!";
<textarea id="out"></textarea>
brackets are optional for if statement
This question already has answers here:
Semantic meaning of writing functions
(3 answers)
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 8 years ago.
So, lets say I have a little program that gives the user an alert that says Hello, that is inside of a function. Everyone says that you should call functions like this:
var thefunct = awesomefunct();
Yet it still works perfectly fine like this:
awesomefunct();
What is the difference between the two, and why couldn't I just use the second one? I know that both methods work but all my programmer friends tell me to use the first one. Why?
If you run
awesomefunct()
You call the function. So when you type:
var thefunct = awesomefunct();
You run the function and assign the result to thefunct variable.
after that just typing
thefunct
Wont call the function. So there is not that much differencebetween the 2 other than that you catch the return value on the first 1.
The difference is that the return statement of the function will be assigned to the variable thefunct in the first one, whereas the second just runs the function and doesn't store the return statement.
Say I have a function like this:
function doSomething(a, b) {
return (a*b)
}
It would be a good idea to store the result in a variable, because the function returns the result, it doesn't assign it to a previously declared global variable.
Do you care about the return value? Use:
var thefunct = awesomefunct();
Don't care about the return value? Use:
awesomefunct();
You may be misunderstanding what your code is doing.
Writing thefunct is not calling the function awesomefunct, your function has already been called when you wrote var thefunct = awesomefunct(); in which case thefunct now contains the return value of awesomefunct
The first type of function call:
awesomefunct();
runs the function, but the return value (if any) is not stored anywhere.
The second type of function call:
var thefunct = awesomefunct();
runs the function, and stores whatever the function returns (0, "I'm awesome", an object, whatever it may be) in the variable thefunct.