String includes with two statements - javascript

I have a form where one can enter info gain if the want to change anything. The data is taking from the API, this.company is JSON and this.company.name points to the company name.
I have a if else code that does something if the string starts with Be or Pe, first though I want to do something when it doesn't include any of those. But I can't seem to make it with two statements. Can't find any documentation on this what so ever.
Entire code is just two more if else based if it's Be or Pe. They do not affect this code, that works when company name matches any of those. Problem is when company name does not match any of those.
Can anyone help me out?
Tried this:
if (!this.company.name.includes("Be") || !this.company.name.includes("Pe")){
do something}
Also tried
if ((!this.company.name.includes("Be") || !this.company.name.includes("Pe"))){
do something}
Can't get it to work. Last resort is to change the if else and make a last else that will be fall back. But that will cause another problem when input isn't done at all.
Edit.
Seems I wasn't clear on the agenda and full code. I wanted to see if it's possible to have two statements, and use ! infront of them. Here's the full code.
if (this.company){
if (!this.company.name.includes("Be") || !this.company.name.includes("Pe")){
this.category = 0;
some code which will eliminate further questions in the form..
}
else if (this.company.name.includes("Be"){
this.category = 1;
some code ...
}
else if (this.company.name.includes("Pe"){
this.category = 2;
some code...
}
}

You have a minor logic problem here.
I think you wanna go for something like:
if (this.company.name && !(this.company.name.includes("Be") || this.company.name.includes("Pe"))){
That means when the company has a name and this name has no "Be" or "Pe" in the name. Remember if you wanna negate a statement you really have to negate the whole statement and not only parts of it or partwise.
(!A || !B) is not equal to !(A || B)
The first one means When A or B doesnt include "Be" and "Pe" - so far so good - but this statement is also true when only A doesn't include "Be" independent from what B is and it's also true when only B doesn't include "Pe" independent from A. On the upperhand the second one spoken means when A or B doesn't include "Be" and "Pe" - nothing else - You could also write something like (!A && !B) this is the same like !(A || B).
That means you could also go with:
if(!this.company.name.includes("Be") && !this.company.name.includes("Pe"))
A general mathematical overview about this topic would be "Boolean algebra".
Further you said when the name starts with "Be" or "Pe" in your suggestion with "include" these search strings can be anywhere in the String not only in the beginning.
The solution would be the startsWith method for strings:
this.company.name.startsWith("Pe")
Regarding to your update
Correct me if im wrong but I think "be" and "pe" is just the beginning and more categories planned.
Under this conditions i would think of something like this:
if (this.company)
switch(this.company.name.slice(0,2)){
case "Be": this.category = 2;break;
case "Pe": this.category = 1;break;
//possibly more conditions
default : this.category = 0;break; //when company name doesn't start with the cases before
}
In my personal point of view this is a bit more readable. But this depends on the amount of methods and things you wanna call if the conditions are true.

Just add an initial if/else statement to check if there is an input value or not and within the if statement, you can nest your second if/else statement for checking if the company name starts with "Be" or "Pe" using the startsWith() method.
if (this.company.name) { // checks if input has value or not
if (this.company.name.startsWith("Be") || this.company.name.startsWith("Pe")) {
[do something]
} else {
[no company which starts with Be or Pe. Do something else]
}
} else {
[no value was inputted. do something else]
}
Edit:
With regards to your updated question, you can just add a bang ! in the nested if statement and add the other if statements as required like this:
if (this.company.name) { // checks if input has value or not
if (!this.company.name.startsWith("Be") && !this.company.name.startsWith("Pe"))) {
this.category = 0;
} else
if (this.company.name.startsWith("Be")) {
this.category = 1;
} else
if (this.company.name.startsWith("Pe")) {
this.category = 2;
}
} else {
[no value was inputted. do something else]
}

You can use RegExp.test
if(/^(?:Pe|Be)/.test(this.company.name)) {
//starts with Pe or Be
} else {
}
If only care about the case when name does not include any of these
if(/^(?!Pe|Be)/.test(this.company.name)) {
//does not start with Pe or Be
}

Related

Troubles with the OR logical processor when coding discord bot

This is my current code, I'm wondering whether i have to use a mess of 'else if,' or if i can keep it compact.
if (message.content.toLowerCase().includes(`word`||`word2`||`word3`||`word4`||`wd`||`wd2`||`wd3`||`wd4`)){
message.reply('don\'t swear in front of me!');
message.delete({ timeout: 100 })
}})
The issue is that only the very first string, word, is being tested for.
All the other strings give no response when i type them into discord.
You have the right idea but you're using the || operator wrong. The || operator checks whether the statement on the left is false/null/undefined and if so, checks the statement on the right. The way you've defined it ('word'||'word2'||...), the operator takes the left statement, in this case the string 'word', and checks if it's false/null/undefined which it isn't because it's a string. Therefore it never checks any other words.
How I think you meant to use it, is like the following:
if (message.content.toLowerCase().includes(`word`) ||
message.content.toLowerCase().includes(`word2`) ||
message.content.toLowerCase().includes(`word3`) ||
...etc
){
// Code here
}
In theory this would work, but as you can see yourself this is far from clean and will get big and bulky with little effort. A better approach would be with using the Array.some() function which calls a function for each item in an array and returns true when one item passes the function. Take a look at the example below:
// Define an array of all the words that need to be checked.
const arrayOfBadWords = ['word', 'word2', 'word3', ...];
if (arrayOfBadWords.some(word => message.content.toLowerCase().includes(word))) {
message.reply('The message contains a blacklisted word.');
} else {
message.reply('The message looks absolutely fine.');
}

A question about a little gusess the age game i made with Js

in my udemy course, we just got introduced to JS!
I love this language, and right now I'm pretty much a novice.
I hope you can help me, i want my code to keep asking the user to guess the age that I've set as the sercretNumber.
i got 2 problems :
1) I think my code can and need to be shorter maybe with some OR and AND.
2) I can't get it to tell the user that if the number is negative or above 100, to prompt the user again for input by saying - Your number needs to be from 1-100.
I get it to work once and it's gone!
here's the Js code :
var secretNumber=98;
var numbGues=Number(prompt("Can you guses My age? (Hint - its 1-100"))
while (numbGues!=secretNumber){
// here I want this message to keep repeating if the user enters a non-valid input such as: -987 , or 54564654//
if (numbGues<0 || numbGues>100 ){
var numbGues=Number(prompt("Pleae choose a valid number between 1-100"))
}
if (numbGues<secretNumber){
var numbGues=Number(prompt("Too low! try again"))
}
else if (numbGues>secretNumber) {
var numbGues=Number(prompt("Too High! Try again!"))
}
if (numbGues==secretNumber) {
alert("You guessed it!")
}
}
Think about the if, if - else if, if structure you have here. It's possible to streamline it. Once you've covered all bases, you don't need another if, you just need an else to end the conditional statement.
As to your second point, in your first if statement, you're already prompting the user for the very same situation you mentioned. Just replace it with the error message you want to be displayed in that block.
little bit changed your code. you need to change
if (numbGues==secretNumber) {
alert("You guessed it!")
}
this if statement. finally your code looks like this.
var secretNumber=98;
var numbGues=Number(prompt("Can you guses My age? (Hint - its 1-100"));
while (numbGues!=secretNumber){
// changed if else statements
if (numbGues<0 || numbGues>100 ){
numbGues=Number(prompt("Pleae choose a valid number between 1-100"));
}else if (numbGues<secretNumber){
numbGues=Number(prompt("Too low! try again"));
}else if (numbGues>secretNumber) {
var numbGues=Number(prompt("Too High! Try again!"));
}
}
//you need to check this if statement in here otherwise if user entered secret number first time didn't show any alert
if (numbGues==secretNumber) {
alert("You guessed it!")
}

better way to write if else statement

First time writing Javascript. I just would like know if there is a shorter way of writing this:
<p id="demo"></p>
<script>
function myFunction() {
var letter = document.getElementById("myInput").value;
var text;
if (letter === "5544") {
text = "Abar, Marlon 1,800";
} else if (letter === "5545") {
text = "Pia, Darla 1,800";
} else if (letter === "5546") {
text = "Salazar, Alex 1,500";
//etc...
} else {
text = "Incorrect Account Number";
}
document.getElementById("demo").innerHTML = text;
}
</script>
Tried map but I couldn't get it to work.
There isn't really a shorter way to write an if statement in that way (which I will assume is what you're asking). However, there could be a few different ways to write this depending on how many things you want to check.
Use a Switch statement
There is a cleaner way when dealing with multiple cases that letter could be.
This would be a switch statement and it would look like this:
var text;
switch (letter) {
case "5544":
text = "Abar, Marlon 1,800";
break;
case "5545":
text = "Pia, Darla 1,800";
break;
// more cases
default:
text = "Incorrect Account Number";
break;
}
This reads a little better than an if else statement in some cases. The default keyword here acts as your else clause in an if else statement. The case acts as your different if statements if you will.
Essentially, the switch statement above will fall through each of the cases it defines until it finds a case that matches letter (such as "5544"). If none matches, it hits the default case. The break keyword at the end of each case stops things from falling through to the next defined case once a match is found.
This method could get cumbersome with more than 6 or 7 cases.
Create an object and look up the value
Now, a shorter way to get the value you want could be to define an object and get the value based on what has been entered like so:
var letter = document.getElementById('selector').value;
var obj = {
'5544': 'Abar, Marlon 1,800'
};
if (letter in obj) {
// do something if found
}
else {
// do something if not found
}
This could be an easy way to get a value if you have many values to check.
Other thoughts
As a side note to all of this, there are short hand if statements called ternary statements which you can find here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator ... However, I would not recommend nesting these as it becomes very complicated and not very readable.
Conclusion
So, to reiterate the answer to your question: No, there isn't really a shorter way to write an if else statement with many values. You can use a switch statement to make it cleaner. Use the object lookup method if you have many values you would like to check.
JavaScript has object (map) literals. Use them for terse code. In your final application you'll get the data for the map from someplace else and not code it directly into your website, but if you did, it would look like this:
document.getElementById( "demo" ).innerHTML = {
"5544" : "Abar, Marlon 1,800",
"5445" : "Pia, Darla 1,800",
...
}[ document.getElementById( "myInput" ).value ];
you can use switch for a long if - else -if ladder:
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
This is how it works:
1)The switch expression is evaluated once.
2)The value of the expression is compared with the values of each case.
3)If there is a match, the associated block of code is executed.
if you need basic tutorials in java script then you should try w3 schools.

Adding multiple parameters to an else if statement?

Let me explain in more detail, I'm making a little sketch for my maths teacher that will calculate the missing sides and angles of a triangle. I have if/else/else if statements but I want an else if statement that will output something like "Check spelling" if none of the other statements are true. Basically, I want something that would do something like this (keep in mind I don't know how to program this yet)
// More code above
else if (side != "hypotenuse and adjacent"; "hypotenuse and opposite"; "opposite and adjacent") {
confirm("Please check spelling.");
}
Can you see what I am trying to do? A previous variable is called side and it prompts the user to input which sides of the triangle they have, so the sketch can work out the angle. What if they have a spelling mistake and it doesn't match any of the parameters I set, how would I make it follow out this block of code if they don't match? I may have just over-complicated things here but if someone could tell me how to do this, it would be greatly appreciated
You can try indexOf:
possibilities = ["hypotenuse and adjacent", "hypotenuse and opposite", "opposite and adjacent"]
// so if side not in that array (the same as not in any of that values)
if (possibilities.indexOf(side) == -1) {}
Are you asking for a default statement if none of the others are matched? Wouldn't that just be an normal else statement?
else{//what you want here}
The simplest way I can think of is to use if, else if and else. By using the else at the end, you won't need to write a huge check for the last line since all the previous.
if (A) { A is true }
else if (B) { Not A, but B }
else if (C) { Not A or B, but C }
else { Not A, B or C }
An much nicer way to do this trick, is to use a switch/case, which is described here.
switch(n) {
case A:
A is true
break;
case B:
B is true
break;
default:
Not A or B
}
However, if you only want the last check for "spell checking", I'd say #zishe has a neat answer to that.
The most simple way to do this is to use jQuery function:
$.inArray(value, array)
which returns either positive index if the string can be found inside of array or -1 otherwise. So the solutions should be something like this:
var myArray = ["hypotenuse and adjacent", "hypotenuse and opposite", "opposite and adjacent"];
// more code above
else if($.inarray(side, myArray) == -1) {
confirm("Please check spelling.");
}

Why would Javascript `if...else if` not end with an `else`?

Here is a snippet of JavaScript code from a tutorial I was working with. I don’t understand why it doesn’t end with a final else clause; I thought that was a rule.
var curScene = 0;
function changeScene(decision) {
var message = "";
if(curScene == 1) {
message = " welcome";
} else if (curScene == 2) {
message = " this is scene two";
} else if (curScene == 3) {
message = " this is scene three";
}
document.getElementById("sceneimg").src = "scene" + curScene + ".png";
if(message != ""){
alert(message);
}
}
I thought it was always supposed to end with an "else"?
The else block is optional. You can have if without else.
For the same reason as why you can have just a single if:
if( /*condition*/ ) {
//some code
}
//other stuff
Consider 3 Scenario
Scenario 1: Boolean condition
if (condition) {}
else {}
Specifying a condition as else if would be redundant, and it's really obvious to the reader what the code does. There is no argument for using else if in this case.
Scenario 2: Infinite states
Here we are interested in testing for conditions A and B (and so on), and we may or may not be interested in what happens if none of them holds:
if (conditionA) {}
else if (conditionB) {}
else {} // this might be missing as it is in your case
The important point here is that there isn't a finite number of mutually-exclusive states, for example: conditionA might be num % 2 == 0 and conditionB might be num % 3 == 0.
I think it's natural and desirable to use a reasonable amount of branches here; if the branches become too many this might be an indication that some judicious use of OO design would result in great maintainability improvements.
Scenario 3: Finite states
This is the middle ground between the first two cases: the number of states is finite but more than two. Testing for the values of an enum-like type is the archetypal example:
if (var == CONSTANT_FOO) {}
else if (var == CONSTANT_BAR) {} // either this,
else {} // or this might be missing
In such cases using a switch is probably better because it immediately communicates to the reader that the number of states is finite and gives a strong hint as to where a list of all possible states might be found (in this example, constants starting with CONSTANT_). My personal criteria is the number of states I 'm testing against: if it's only one (no else if) I 'll use an if; otherwise, a switch. In any case, I won't write an else if in this scenario.
Adding else as an empty catch-errors block
This is directly related to scenario #2 above. Unless the possible states are finite and known at compile time, you can't say that "in any other case" means that an error occurred. Seeing as in scenario #2 a switch would feel more natural, I feel that using else this way has a bad code smell.
Use a switch with a default branch instead. It will communicate your intent much more clearly:
switch(direction) {
case 'up': break;
case 'down': break;
default: // put error handling here if you want
}
This might be a bit more verbose, but it's clear to the reader how the code is expected to function. In my opinion, an empty else block would look unnatural and puzzling here.
It doesn't have to, for the same reason an if on its own doesn't require an else.
Usually it's a good idea to have one, as a sort of "catch-all" situation, but the above code could be written as:
switch(curScene) {
case 1: message = " welcome"; break;
case 2: message = " this is scene two"; break;
case 3: message = " this is scene three"; break;
}
In the above code, I could also add:
default: message = " invalid curScene value"; break;
But it's completely optional to do so. It depends on how reliable the curScene variable is whether or not I personally would add it in.
Not having an else clause is fine syntactically. MDN Documentation Basically the second if becomes the body of the else, see the section on "how it would look like if the nesting were properly indented".
As to whether it's bad practice I think that depends on intent. By not explicitly defining the final else clause, you might end up with a bug where a condition you didn't cover comes through. Consider this:
if(myVariable > 0) {
doSomething();
} else if(myVariable < 0) {
doSomethingElse();
}
Nothing happens if myVariable is 0. It would be hard to see if you were just glancing through the code. I would say if you run into this pattern it would be a code smell, something might be wrong, but it could be fine.
The same logic could always be expressed with nested if statements. I would go with whatever is more readable.
else is a default case for the if statement.
If there is no else then if none of the conditions in the if or else if cases are met than the if statment will do nothing.
Usually it is good practice to have a default case but there are a lot of times where it is not necessary and thus excluded from the code.
In this case, if the curScene was anything other than 1, 2, 3 then the else statment would be used, but since there is no processing to be done on other cases the coder has not included an else.
yes, always have a else is VERY GOOD habit(when using with if-elseif). sometimes people might even write this:
if(curScene == 1) {
message =" welcome";
else if (curScene == 2) {
message = " this is scene two";
}
else if (curScene == 3) {
message = " this is scene three";
} else {
// empty.
}
to tell people there is indeed nothing to do in the else.
change the if condition for answer validation if(answer==100) to if(answer===100)
it is working fine now...

Categories