Issue with nested if statement (within function) in Javascript - javascript

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

Related

Trying to solve If/else problem with specific string and boolean

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

How to come out of an if condition and land in else condition that is out of it?

I am working on some code where I have a specific requirement.
if(condition){
if(condition){
}else{
//if comes here then goto previous else
}
}else{
// come here if it goes to upper else part.
}
You should be able to do this in a single if statement. Just join your conditions with a boolean AND operator
if (condition && condition)
{
}
else
{
}
It does not really make sense if the 2 else blocks have the same logic, but if they are different then outsource in a function:
function sameLogic(){
// same code
}
if(condition){
// or maybe some extra code here?
$someCode = 'hy';
if(condition){
}
else{
// some other code here?
$yourCode = 'someting';
sameLogic();
}
}
else{
// no other code
sameLogic();
}
If its not like this example, see the answer from Neil N

JavaScript If string is equal to anything else

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

Javascript long else / if statement in a shortest way

I have written an else / if statement in my plugin but for optimization (less code) I want it to be shorter.
if ( self.first() ) {
if ( self.second() ) {
self.run();
}
else {
self.other_run();
}
}
else {
return false;
}
Example
if ( check cookie is true ) {
if ( check timezone is true ) {
run sth
}
else {
run other thing
}
}
else {
do nothing
}
What about?
if ( self.first() ) {
self.second ? self.run() : self.other_run();
}
else {
return false;
}
Is it ok to write it like that?
return self.first() ? ( self.second() ? self.run() : self.other_run() ) : false;
self.first() ? ( self.second() ? self.run() : self.other_run() ) : false;
Should work fine, but I'm not sure why you'd want to obfuscate your code like that.
(Keep in mind that "shorter" code isn't always "better" code.)
That may work, with some explicit parenthesis to separate your wrapped statements. Though it's not really easier to read/understand. How about something like this?:
if (self.first() && self.second()) {
self.run();
return;
}
if (self.first()) {
self.other_run();
return;
}
return false;
This follows Martin Fowler's refactoring pattern called Replace Nested Conditional With Guard Clauses.
This also makes it more clear that your function isn't always returning a boolean value. (Something I didn't immediately notice until I wrote this.) Perhaps you mean to do so (a bug which wasn't noticed in the overly-brief version of the code)?:
if (self.first() && self.second()) {
self.run();
return true;
}
if (self.first()) {
self.other_run();
return true;
}
return false;
Naturally, this code is obviously fake just to demonstrate a point. But if the conditional clauses do start to get unwieldy, you can always extract them into their own functions:
if (somethingIsTrue()) {
self.run();
return true;
}
if (somethingElseIsTrue()) {
self.other_run();
return true;
}
return false;

Javascript statements all to be evaluated

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
}

Categories

Resources