Javascript micro optimisation for if statement - javascript

I am fairly new to JavaScript and I have a question regarding how to optimise if statements.
I will show you two scenarios.
//first
var number = 10;
var calculationOneResult = functionOne(number);
var calculationTwoResult = functionTwo(number);
if (calculationOneResult === true) {
//stuff
} else if (calculationTwoResult === true) {
//more stuffs
}
//second
var number = 10;
if (functionOne(number) === true) {
//stuff
} else if (functionTwo(number) === true) {
//more stuffs
}
Here is my question:
In the first scenario, I am calculating two times.
In the second one, if the first function returns true, will it calculate the second elseif statement or will it skip it after doing the stuff ?

The following code:
if(statement1) {
// stuff
} else if(statement2) {
// other stuff
}
is equivalent to
if(statement1) {
// stuff
} else {
if(statement2) {
// other stuff
}
}
as there is no elseif in JavaScript - see documentation.
So the answer is any function in statement2 will be simply skipped.

Nothing in an else clause executes if the if expression tests as true, so the second version of your code will definitely save a function call in such cases.

Related

jQuery function doesn't exit after return [duplicate]

How do I break out of a jQuery each loop?
I have tried:
return false;
in the loop but this did not work. Any ideas?
Update 9/5/2020
I put the return false; in the wrong place. When I put it inside the loop everything worked.
To break a $.each or $(selector).each loop, you have to return false in the loop callback.
Returning true skips to the next iteration, equivalent to a continue in a normal loop.
$.each(array, function(key, value) {
if(value === "foo") {
return false; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
According to the documentation return false; should do the job.
We can break the $.each() loop [..] by making the callback function
return false.
Return false in the callback:
function callback(indexInArray, valueOfElement) {
var booleanKeepGoing;
this; // == valueOfElement (casted to Object)
return booleanKeepGoing; // optional, unless false
// and want to stop looping
}
BTW, continue works like this:
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.
$('.groupName').each(function() {
if($(this).text() == groupname){
alert('This group already exists');
breakOut = true;
return false;
}
});
if(breakOut) {
breakOut = false;
return false;
}
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
http://jsfiddle.net/9XqRy/
I know its quite an old question but I didn't see any answer, which clarify that why and when its possible to break with return.
I would like to explain it with 2 simple examples:
1. Example:
In this case, we have a simple iteration and we want to break with return true, if we can find the three.
function canFindThree() {
for(var i = 0; i < 5; i++) {
if(i === 3) {
return true;
}
}
}
if we call this function, it will simply return the true.
2. Example
In this case, we want to iterate with jquery's each function, which takes anonymous function as parameter.
function canFindThree() {
var result = false;
$.each([1, 2, 3, 4, 5], function(key, value) {
if(value === 3) {
result = true;
return false; //This will only exit the anonymous function and stop the iteration immediatelly.
}
});
return result; //This will exit the function with return true;
}
"each" uses callback function.
Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
I use this way (for example):
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
if cont isn't false runs commands block

Creating a loop for an else statement inside a function

I am trying to create a loop to include an else statement. It works perfectly with the if statement as below but when trying to put in the else statment it either shows nothing or creates 6 loops. Im assuming I am putting the else statement in the wrong place. Can someone please explain to me a) where to put the else statement and b) the nesting criteria of the ending curly braces inside a function
Heres what ive got and it works perfectly until i place the else statement in. thanks
var sports = ["golf", "cricket", "tennis", "badminton", "squash"];
function checkSport(sportToCheck) {
for (var i = 0; i <= sports.length; i++) {
if (sportToCheck == sports[i]) {
alert("yes we offer that sport");
}
}
}
checkSport("tennis")
Based on your variable names, I guess you don't have to use else in this context but you would like to end the loop/function as soon as the sport is found:
function checkSport(sportToCheck) {
for (var i = 0; i <= sports.length; i++) {
if (sportToCheck == sports[i]) {
alert("yes we offer that sport");
return; // stop the execution of the function
} else {
console.log("Do nothing so you don't need this else statement.");
}
}
alert("No we don't offer that sport"); // If the loop ends and cannot find any match
}
Because your function is check() and to respect Do One Thing rule, it's better to return true or false.
There are many ways to solve your issue but I prefer find().
var sports = ["golf", "cricket", "tennis", "badminton", "squash"];
function checkSport(sportToCheck) {
return sportToCheck === sports.find((sport) => sport === sportToCheck);
}
console.log(checkSport("football")); // Expect : false
console.log(checkSport("tennis")); // Expect : true
If you want to improve #Hangindev answer you can do this:
for (sport of sports) {
true === (sportToCheck === sport) && alert("yes we offer that sport");
}
No need for else statements. Simply run through each possible value in the sports array, and use the return statement to pause further script execution within that function.
The function returns either true or false depending on whether the string is inside the sports array.
var sports = ["golf", "cricket", "tennis", "badminton", "squash"];
function checkSport(sportToCheck) {
for (var i = 0; i <= sports.length; i++) {
if (sportToCheck == sports[i]) {
alert("yes we offer that sport");
return true;
}
if (i == sports.length) {
alert("sorry we do not offer this sport");
return false;
}
}
}
checkSport("tennis")
You could use this for something like:
if (checkSport("tennis")) {
// sport exists
} else {
// sport does not exist
}

Execute function only once - Depending conditions

I know how to execute a function once, this is not the question
First, this is my code
var executed1 = false;
var executed2 = false;
var executed3 = false;
function myFunction()
{
if(-------------------)
{
//Verification - If the others conditions have ever been called
if (executed2)
{
executed2 = false;
}
else if(executed3)
{
executed3 = false;
}
//Verification - If the condition have ever been called during this condition = true;
if (!execution1)
{
execution1 = true;
//My code here ...
}
}
else if (-------------------)
{
if (executed1)
{
executed1 = false;
}
else if(executed3)
{
executed3 = false;
}
if (!execution2)
{
execution2 = true;
//My code here ...
}
}
else if (-------------------)
{
//Same thing with execution3
}
}
setInterval("myFunction()", 10000);
I'll take the first condition, for example
(1) If the condition is true, I want to execute my code but only the first time : as you can see, my function is executed every 10s. As long as the first condition is true, nothing should append more.
If the first condition becomes false and the second condition true, it’s the same process.
But now, If the first condition ever been true and false, I would like that if the condition becomes true again, it will be the same thing that (1)
Is there any way to read a cleaner code to do that ?
Because, now there are only 3 conditions, but there may be 100.
use clearInterval to stop execution your function and one if to check conditions
var fid = setInterval(myFunction, 1000);
var cond = [false,false,false];
function myFunction()
{
console.log(cond.join());
// check conditions in some way here (e.g. every is true)
if(cond.every(x=>x)) {
clearInterval(fid);
console.log('Execute your code and stop');
}
// change conditions (example)
cond[2]=cond[1];
cond[1]=cond[0];
cond[0]=true;
}

Illegal break statement in $.each [duplicate]

How do I break out of a jQuery each loop?
I have tried:
return false;
in the loop but this did not work. Any ideas?
Update 9/5/2020
I put the return false; in the wrong place. When I put it inside the loop everything worked.
To break a $.each or $(selector).each loop, you have to return false in the loop callback.
Returning true skips to the next iteration, equivalent to a continue in a normal loop.
$.each(array, function(key, value) {
if(value === "foo") {
return false; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
According to the documentation return false; should do the job.
We can break the $.each() loop [..] by making the callback function
return false.
Return false in the callback:
function callback(indexInArray, valueOfElement) {
var booleanKeepGoing;
this; // == valueOfElement (casted to Object)
return booleanKeepGoing; // optional, unless false
// and want to stop looping
}
BTW, continue works like this:
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.
$('.groupName').each(function() {
if($(this).text() == groupname){
alert('This group already exists');
breakOut = true;
return false;
}
});
if(breakOut) {
breakOut = false;
return false;
}
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
http://jsfiddle.net/9XqRy/
I know its quite an old question but I didn't see any answer, which clarify that why and when its possible to break with return.
I would like to explain it with 2 simple examples:
1. Example:
In this case, we have a simple iteration and we want to break with return true, if we can find the three.
function canFindThree() {
for(var i = 0; i < 5; i++) {
if(i === 3) {
return true;
}
}
}
if we call this function, it will simply return the true.
2. Example
In this case, we want to iterate with jquery's each function, which takes anonymous function as parameter.
function canFindThree() {
var result = false;
$.each([1, 2, 3, 4, 5], function(key, value) {
if(value === 3) {
result = true;
return false; //This will only exit the anonymous function and stop the iteration immediatelly.
}
});
return result; //This will exit the function with return true;
}
"each" uses callback function.
Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
I use this way (for example):
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
if cont isn't false runs commands block

How Would I Make an If Statement From Arguments in Javascript?

I need to pass certain parameters into a function and have that function pull from an array based on the arguments passed to it. It's hard to explain, so I'll show you what I'm trying to do.
function SearchDeck(deck,...){
var tryagain = true;
do{
if(deck[0].property == value){
//do something;
tryagain = false;
}
else{
deck.splice(0,1);
}
}
while(tryagain);
}
There are multiple decks to look in, the proper deck will be passed in. I want to always be drawing off the top of the deck (index 0 of the array). I need to draw continuously until I find a card that matches what I'm after. I splice out the 0 index if it doesn't match. What I'm after is dynamic, varying across the properties or even the operators I would use.
Some examples of if statements I would have are...
deck[0].color == "orange"
deck[0].value >= 5
deck[0].value < -4
I could make multiple functions or have the function fork based on an argument, but that doesn't seem like the best way to go about this.
If I'm understanding this correctly, you want the behavior of the if(deck[0].property == value) to be different for each invocation of the SearchDeck(...) function?
My recommendation would be to pass in a function:
function SearchDeck(deck, validationFunction, ...){
var tryagain = true;
do{
if(validationFunction(deck[0])){
//do something;
tryagain = false;
}
else{
deck.splice(0,1);
}
}
while(tryagain);
}
Then when you call the code, you can do:
SearchDeck(deck, function(firstCard) { return firstCard.color == "orange" }, ...);
SearchDeck(deck, function(firstCard) { return firstCard.value >= 5 }, ...);
SearchDeck(deck, function(firstCard) { return firstCard.value < -4 }, ...);
Or, if the cases you're looking for might be reused, it might also be cleaner to make those named functions:
function validateColor(firstCard) {
return firstCard.color == "orange";
}
function validateHighValue(firstCard) {
return firstCard.value >= 5;
}
function validateLowValue(firstCard) {
return firstCard.value < -4;
}
SearchDeck(deck, validateColor, ...);
SearchDeck(deck, validateHighValue, ...);
SearchDeck(deck, validateLowValue, ...);
It sounds like you may be interested in the typeof operator:
if (typeof deck == 'object') { ... }
if (typeof deck[0].color == 'string') { ... }
if (typeof deck[0].value == 'number') { ... }
Alternatively:
if (deck[0].hasOwnProperty('color')) { ... }
This is what I came up with. You need to push the way of check (either "== 'oragne'" or "<3") as string.
function searchDeck() {
var deck = Array.prototype.slice.call(arguments, 1),
tryagain = true,
string = deck[deck.length - 1];
deck.pop();
while (tryagain) {
if (eval('deck[0].property' + string)) {
//do something;
alert('card found');
tryagain = false;
} else {
deck.splice(0, 1);
}
}
}
Hope this is what you wanted ;)
Here is a working jsfiddle example, of course there might be a more elegant way, this is just what I came up with. Note that eval can be dangerous, so you should be carefull if user picks what the test will be (the string pushed into the array).

Categories