How do I check if a string is not equal to any of the other options? I know I can just do a simple else statement, but I'm not sure if it'll work since the code in my ifs aren't combined, yet they are just if() and else if() for its own, but then no else. How could I do a else statement/check if its anything else without using a switch/case statement?
Here's an example.
if(object1 === "string") {
function1();
}
if(object1 === "string2") {
function2();
if(object2 === "string" && variable === 10) {
function1();
}
if(object1 || object2 === "") {
alert("That's not a valid option!");
}
WARNING
I can't insert the code here as standalone or snippet, due to it exceeding the maximum character limit. I am only able to add a JSFIDDLE. Please excuse the inconvienence.
JSFIDDLE
The two main ways you can do it without if/else if/else being combined are a simple fall through
function foo(opt) {
if (opt === 'this') { return true; }
if (opt === 'that') { return 'something else'; }
/* Code here represents the case that opt is not this or that */
}
Another more complex way of doing it would be to have some kind of array of options and then checking them all but it's a bad pattern and you really should consider using if/else if/else as a combined tree (not sure you've really explained why you can't do this.
function foo(opt) {
var checked = ['this', 'that'];
if (opt === 'this') { return true; }
if (opt === 'that') { return 'something else'; }
if (checked.indexOf(opt) === -1) { return 'fall through case'; }
}
A switch is also possible but that's just a variation of a combined if/else if/else so if you can't use the latter I don't see how the former would help
Again the above is a bad pattern but if for some reason that's what you have to then there's an implementation.
Another solution would be to raise flags when going through one of the if statement, so that at the end, you can check those flags and if none are true, then you can do whatever you want.
var flag = false;
if(object1 === "string") {
function1();
flag = true;
}
if(object1 === "string2") {
function2();
flag = true;
if(object2 === "string" && variable === 10) {
function1();
flag = true;
}
if(object1 || object2 === "") {
alert("That's not a valid option!");
flag = true;
}
if(!flag) {
alert('no other options were validated');
}
Related
I want to shorten the conditions of a javascript if but I don't know how I can achieve it
code:
if ((!emailValidation() || (!nameValidation()) || (!surnameValidation()) || (!addressValidation()) || (!cityValidation()) || (!postalCodeValidation()))) {
}
I have the conditions defined in this way:
let surnameValidation = () => {
if (apellidoUsuario.value.length == 0) {
surnameError();
return false;
}
else if (apellidoUsuario.value.length == 1) {
surnameError();
return false;
}
else {
apellidoUsuario.focus;
apellidoUsuario.style.border = '0';
apellidoUsuario.style.backgroundColor = 'transparent';
apellidoUsuario.style.outline = '1px solid #00ffb1'
apellidoUsuario.style.transitionDuration = '0.4s'
return true;
}
I appreciate any help! :)
You can remove all unnecessary parenthesis in your if condition:
if (
!emailValidation() ||
!nameValidation() ||
!surnameValidation() ||
!addressValidation() ||
!cityValidation() ||
!postalCodeValidation()
) {
}
Other than that, there's not really a clean, readable way to shorten your code.
Proposition #1:
I would probably get those validations into a variable or function:
validations() {
return [
emailValidation(),
nameValidation(),
surnameValidation(),
addressValidation(),
cityValidation(),
postalCodeValidation()];
}
and then I would:
if(validations().some(x=> !x)){
...
}
since validations return an array you can just use the some operator to find any invalid value.
Proposition #2:
I particularly would:
valid() {
return [
emailValidation(),
nameValidation(),
surnameValidation(),
addressValidation(),
cityValidation(),
postalCodeValidation()].every(x => x === true);
}
and then I would:
if(!valid()){
...
}
It is always cleaner to use true conditions on if statements instead of false ones.
References: Clean Code - Uncle Bob.
Now that I have a recursive function, I wonder what is best in order for the same flow to continue.
Nest an another function, isn't it?
In other words, I would like another prompt that asks the user's age when the user answers yes to the first prompt.
The issue that I'm facing now is that the last prompt does not comeback if the user writes something different than "yes" or "no".
They way I've nested it makes the prompts pop up in a way that I can't figure out:
function showPrompt(msg) {
var str = prompt(msg).toLowerCase();
if (str === "yes") {
function showPrompt(firstQuestion) {
var age = prompt(firstQuestion).toLowerCase();
if (age < 21) {
alert("You're too young. Go home.");
} else if (age >= 21) {
alert("Welcome.");
} else {
showPrompt(firstQuestion);
}
}
showPrompt("How old are you?");
} else if (str === "no") {
alert("goodbye.");
} else {
showPrompt(msg);
}
}
showPrompt("Do you like gambling?");
The problem is that you are overwriting your function. If you give your second function another name I guess it works the way you want. And as given in the other answer, you do not need to define your function in the condotional clause:
function showPrompt(msg) {
var str = prompt(msg).toLowerCase();
if (str === "yes") {
nextQuestion("How old are you?");
} else if (str === "no") {
alert("goodbye.");
} else {
showPrompt(msg);
}
}
function nextQuestion(secondQuestion) {
var age = parseInt(prompt(secondQuestion));
if (typeof age == "number" && age < 21) {
alert("You're too young. Go home.");
} else if (typeof age == "number" && age >= 21) {
alert("Welcome.");
} else {
showPrompt(secondQuestion);
}
}
showPrompt("Do you like gambling?");
Your problem is the conditional creation of showPrompt within the function called showPrompt, see Function declarations inside if/else statements?. While such declarations are allowed, they have side effects and should be avoided.
One side effect is that the conditional function declaration creates a local variable that is undefined unless execution enters the if block and assigns it a value. In the OP, the local showPrompt declaration shadows the global showPrompt created by the global function declaration. Hence if the block is not entered, when it's called, its value is undefined and a TypeError is thrown, e.g.
// Global foo
var foo = 23;
function bar() {
// Declaration creates a local foo even if
// if block is not entered
if (false) {
function foo (){}
}
// foo is undefined
console.log(typeof foo);
}
bar();
To fix that, change the name of the function in the if block and move it out of the block.
Also, as pointed out by epascarello, you should do numeric comparisons using numbers, not strings. When using comparison operators, if one of the values is a number, then the other will be converted to number too for the comparison. But if they are both strings (prompt returns a string), they'll be compared as strings. But for readability, it's best to use numbers for both sides.
Finally, you should test the value returned by the prompt to see it's a string. If the user clicks "Cancel", it will return null and calling toLowerCase will throw an error. So if the value isn't a string, the user clicked cancel and the function should handle it (e.g. exit).
function showPrompt(msg) {
function showPrompt2(firstQuestion) {
var age = prompt(firstQuestion);
if (typeof age != 'string') {
return;
}
if (+age < 21) {
alert("You're too young. Go home.");
} else if (+age >= 21) {
alert("Welcome.");
} else {
showPrompt2(firstQuestion);
}
}
var str = prompt(msg);
if (typeof str != 'string') {
return;
}
str = str.toLowerCase();
if (str === "yes") {
showPrompt2("How old are you?");
} else if (str === "no") {
alert("goodbye.");
} else {
showPrompt(msg);
}
}
showPrompt("Do you like gambling?")
Problem
I've tried multiple avenues and watched videos. I'm stuck...
function exerciseThree(typeOfPizza){
let lovesPizza;
// In this exercise, you will be given a variable, it will be called: typeOfPizza
// You are also given another variable called: lovesPizza;
// Using an if/else statement assign lovesPizza to true if typeOfPizza is 'pepperoni', assign it to false if it is 'olives'
What I've tried:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
Another attempt
// if(lovesPizza===pepperoni){
// return true
//}
//else (lovesPizza===olives){
// return false
// }
Another one
//if (lovesPizza.equals(pepperoni))
// return "true";
//else (lovesPizza.equals(olives))
// return "false"
As the comments say, you're looking for if / else. You should also double check your reading of the question, you had your checking / assigning variables the wrong way around
function exerciseThree(typeOfPizza){
let lovesPizza;
if (typeOfPizza === 'pepperoni') {
lovesPizza = true;
} else if (typeOfPizza === 'olives') {
lovesPizza = false;
}
console.log('lovesPizza:', lovesPizza);
};
exerciseThree('pepperoni');
exerciseThree('olives');
I would highly recommend using a switch statement in this case here. Switch statements run faster and are easier to work with in my opinion.
But to point out what you're doing wrong:
Here you are checking if lovesPizza has the value of pepperoni. But you should be checking typeOfPizza. This is why you're most likely getting undefined:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
Check out how this looks with a switch statement.
function exerciseThree(typeOfPizza) {
switch (typeOfPizza) {
case 'pepperoni':
return true;
case 'olives':
return false;
default:
return false;
}
}
exerciseThree('pepperoni');
exerciseThree('olives');
Your else statement needs an if
if(somethingisTrue)
{
return "it is true";
}
else if(somethingelseistrue)
{
return "no the other thing was true";
}
else
{
return "nothing is true"
}
Also === checks the strings equal and are both strings. It is often better to make sure the if is case insensative
if(!typeOfPizza)
{
//raise an error as null was passed in
return "false"
}
else if(typeOfPizza.toLowerCase().trim()==="pepperoni"){
{
return true..... you can build the rest
I often write a function (prototype) called cleanString or compareString to perform all the normal cleaning up of strings.
A simple solution is but doesn't use ifs as asked.
function exerciseThree(typeOfPizza){
let lovesPizza= typeOfPizza==="pepperoni";
return lovesPizza;
}
I certainly hope you teacher is playing a trick on you.
There is no sane suggestions what to do if you send for instance 'ham' into it, and not handle all possibilities are just sloppy.
let lovesPizza;
function exerciseThree(typeOfPizza){
if(typeOfPizza === 'pepperoni') {
return true;
} else if (typeOfPizza === 'olives') {
return false;
} else {
return undefined;
}
}
lovesPizza = exerciseThree('pepperoni');
console.log(lovesPizza); // true
lovesPizza = exerciseThree('olives');
console.log(lovesPizza); // false
lovesPizza = exerciseThree('ham');
console.log(lovesPizza); // undefined
first time here and I've run into an issue... idk if it's my syntax or my logic is completely wrong...
var hasExperience;
var amountOfExperience;
function employed(hasExperience,amountOfExperience) {
if(hasExperience === true){
if(amountOfExperience > 5)
return true;
} else {
return false;
}
}
It doesn't seem to want to return false if the first two if statements aren't met... anyone can help?
Thanks!
If you need both of the if statements to evaluate to true, you should write it like this:
if(hasExperience === true && amountOfExperience > 5){
return true;
} else {
return false;
}
In your example, if(hasExperience === true) then you run the code inside the if block, else run the code inside the else block. It's important to understand that this is completely independent of what's inside the if block.
if(hasExperience === true){
// code inside if block
} else {
// code inside else block
}
The code inside the if block happens to be another if statement that will return true if(amountOfExperience > 5), and does nothing otherwise. Again, this is independent of the other if statement.
if(amountOfExperience > 5)
return true;
Using &&, means that both statements have to evaluate to true in order to execute the code inside of the if block. You can read more about this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
Also, as some others have stated, you can just write your function like this:
function employed(hasExperience,amountOfExperience) {
return hasExperience === true && amountOfExperience > 5;
}
Since your evaluating (hasExperience === true && amountOfExperience > 5) as a boolean and returning that boolean, you can avoid the if statement all together.
Try experimenting with this a little bit more to understand what's going on.
Update based on comment:
You could also accomplish this using the nested if, but this makes the code messy and difficult to read.
if (hasExperience === true) {
// only hasExperience is true
if (amountOfExperience > 5) {
// hasExperience is true and amountOfExperience is greater than 5
return true;
} else {
// hasExperience is false and amountOfExperience is less than 5
return false;
}
} else {
// hasExperience is false and we have no idea what amountOfExperience is
return false;
}
Hi I want each if statements to be evaluated (java script). This is not happening, when one or two are true the remaining statements are not evaluated. They are all independent questions. What should I be using instead of if and else? Thanks.
//Side-Vent-Even
if (SideVent == "Side-Vent-Even" && Canvas=="Base-Shirt") {
// do this
}
//Side-Vent-Uneven
else if (SideVent2 == "Side-Vent-Uneven" && Canvas=="Base-Shirt") {
// do this
}
//Golf-Tee-Right
else if (GolfTee == "Golf-Tee-Right" && Canvas=="Base-Shirt") {
// do this
}
//Golf-Tee-Left
else if (GolfTee2 == "Golf-Tee-Left" && Canvas=="Base-Shirt") {
// do this
}
Turn them in to regular ifs, which will cause them all to be run independently of each other
if(){
}
....
if(){
}
If else are used when you wish to perform condition from either of them but not both or all, in your case you want all of them to be performed, hence use if condition statement for all, like
//Side-Vent-Even
if (SideVent == "Side-Vent-Even" && Canvas=="Base-Shirt") {
// do this
}
//Side-Vent-Uneven
if (SideVent2 == "Side-Vent-Uneven" && Canvas=="Base-Shirt") {
// do this
}