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
Related
In the following code, how the statement works, as this statement is the part of an javascript file.
this.isSelected = function(checkTab)
{
return(this.tab===checkTab);
}
this.isSelected is a function, taking checkTab as a parameter. It compares it to this.tab and returns true if they are equal, otherwise false.
this.isSelected = function(checkTab)
{
return (this.tab === checkTab);
}
// equivalent to
function isSelected(checkTab) {
if(this.tab === checkTab) return true;
return false;
}
How to evaluate condition in non short circuit way in typescript?
Typescript does not allow & or | for boolean type.
The reason why I need a non short circuit checking is I call showErrors in function isValueValid.
Given this function
function isValue1Valid(){
if(value1 === 0) return true;
showErrors1();
return false;
}
function isValue2Valid(){
if(value2 === 0) return true;
showErrors2();
return false;
}
Then in my condition
if(isValue2Valid() & isValue2Valid()){
//Submit data
}
Although I can do it like this one
if(isValue2Valid() & isValue2Valid()){
//Submit data
return;
}
showErrors1()
showErrors2()
But I feel to call it inside isValueValid function. In reality I always think to call show errors by default whenever there's an error.
To answer your question, you could do
if ([isValue2Valid(), isValue2Valid()].every(Boolean)) {
//Submit data
}
to evaluate all function calls and then combine their values. But you really shouldn't have isValueValid call showError in the first place. Instead, make your test functions return the error messages, and then if there are any, show them:
function getValue1Error() {
if (value1 === 0) return null;
else return "error1";
}
function getValue2Error() {
if (value2 === 0) return null;
else return "error2";
}
// then:
const errors = [getValue1Error(), getValue2Error()] // or even better, just a loop over your fields
if (errors.some(Boolean)) {
for (let error of errors)
showError(error);
} else {
// Submit data
}
If you want to use functions with side-effects (which is not a good idea in general), it might help to be very explicit about what is called and when:
var value1Valid = isValue1Valid(); // might show some messages
var value2Valid = isValue2Valid(); // might show some more messages
if (value1Valid && value2Valid) {
// submit data
}
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');
}
I am using a method to find Media Queries in code.
function checkMediaQueries() {
var css = cssText;
var patt1 = /#media/gi;
countMQ = css.match(patt1).length;
if (countMQ == 0) {
return false;
} else {
return true;
}
}
It all works fine when it finds some Media Queries. But when the method cant find any, it wont return anything because countMQ is null. I know the problem, but cant find a solution for it.
How can i avoid this result and make my method return false instead?
Thx for help
Remove the .length, as null has no length
var countMQ = css.match(patt1);
and check for truthy, not 0
if (countMQ) {
return true;
} else {
return false;
}
or even null, if you wan't to be more specific
if (countMQ === null) {
or simpler
function checkMediaQueries() {
return cssText.match(/#media/gi) ? true : false;
}
FIDDLE
I cant seem to get this function to return true even after ticking the two check boxes I have on the page. I've been working on this for hours now and running out of ideas. Any help would be much appreciated.
if(myfunction() == true){
alert('YAY!');
}
function myfunction(){
if($("input[type=checkbox]").length > 0){
$('.checkbox').each(function(){
if($(this).prop('checked')){
return true;
}
else{
$(this).find(".CheckboxCheck").show();
return false;
}
});
}
else{
return true;
}
}
You are returning true from within the function that you passed to each, not from myfunction. Except in the case that there are no check boxes on your page, and thus the else block executes in myfunction, myfunction is returning undefined.
You can do something like this however:
if(myfunction() == true){
alert('YAY!');
}
function myfunction(){
var returnValue = true;
if($("input[type=checkbox]").length > 0) {
$('.checkbox').each(function(){
if($(this).prop('checked')){
returnValue = true;
return false; // Stops the each loop.
}
else {
$(this).find(".CheckboxCheck").show();
returnValue = false;
return false; // Stops the each loop.
}
});
}
return returnValue;
}
Now, I'm not exactly sure of what you're trying to do, and you will almost certainly need to tweak the code above. I'm just providing it as a way to illustrate how to get a value out of the function passed to each. If you're trying to determine if all of the checkboxes are checked, for example, then you'll want your each function to look something like this:
var returnValue = true;
...
$('.checkbox').each(function() {
if (!$(this).prop('checked')) {
returnValue = false;
return false;
}
});
EDIT: After looking at the second code snippet again, I realized that the each loop is unnecessary. If you want to determine if all check boxes are checked, all you need is this:
if ($('.checkbox:not(:checked)').length == 0) {
// All .checkbox elements are checked.
}
Now, keep in mind that the :not() and :checked selectors can't utilize the native JS functions, so they are slower, but probably not enough to matter. I prefer the conciseness.
Returning from inside the each callback function will not return from the outer function. The function will return undefined as you haven't specified any return value for it, and that is not equal to true.
You can use a variable for the result, that you set from within the loop:
function myfunction(){
var result = true;
$('.checkbox').each(function(){
if(!$(this).prop('checked')){
result = false;
$(this).find(".CheckboxCheck").show();
return false; // exit the loop
}
});
return result;
}