How to code else if in short if statement? [duplicate] - javascript

This question already has answers here:
shortHand if else-if and else statement
(3 answers)
Closed 3 years ago.
For example, I have code with short if statement and how can I code else if in this code?
var age = 16;
age > 18 ? console.log("> 18") : console.log("< 18");
That would work like this code
var age = 16;
if (age > 18){
console.log("> 18");
}else if(age == 18){
console.log("= 18");
}else{
console.log("< 18");
}

A hybrid approach is recommended in this case:
var age = 16;
if (age == 18) {
console.log("= 18");
} else {
console.log(age > 18 ? "> 18" : "< 18");
}

Do it with ternary expression,
var age = 16;
console.log(age === 18 ? "=18" : age < 18 ? "< 18" : "> 18")
var age = 19;
console.log(age === 18 ? "=18" : age < 18 ? "< 18" : "> 18")
var age = 18;
console.log(age === 18 ? "=18" : age < 18 ? "< 18" : "> 18")

The if way could also be written like this:
var age = 16;
if (age > 18) {
console.log('> 18')
} else if (age == 18) {
console.log("= 18");
} else {
console.log("< 18");
}
So, you could use a nested ternary in the style of the code above:
var age = 16;
age > 18 ? console.log('> 18') : age === 18 ? console.log("18") : console.log("< 18")
Note, it would be more efficient to write the ternary inside console.log, since you are always returning similar values (in this case, strings):
var age = 16;
console.log(age > 18 ? age === 18 ? '18' : '< 18' : '< 18')

Related

Switch statement in JavaScript is not able to run my code Properly

var aged = 14;
switch (aged) {
case aged <= 13:
document.write("Child");
break;
case aged >= 14 && aged <= 18:
document.write("Teen");
break;
case aged >= 19 && aged <= 59:
document.write("Adult");
break;
default:
document.write("Boomer");
}
it just keeps outputting BOOMER!!
I honestly don't know what to do
I got the syntax right but I'm still confused
Because each of your case branches provide a boolean value, you need to match against a boolean.
Your logic is such that you want to enter a branch upon a true evaluation, so use true in the head of the switch.
var aged = 14;
switch (true){
case aged <= 13:
document.write("Child");
break;
case aged >= 14 && aged <= 18:
document.write( "Teen" );
break;
case aged >= 19 && aged <= 59:
document.write("Adult");
break;
default:
document.write("Boomer");
}
I think if/else would maybe be preferable here.
var aged = 14;
if (aged <= 13) {
document.write("Child");
} else if (aged >= 14 && aged <= 18) {
document.write( "Teen" );
} else if (aged >= 19 && aged <= 59) {
document.write("Adult");
} else {
document.write("Boomer");
}
You could also use the conditional operator, but I'd use it to provide a value instead of control the flow of the program.
var aged = 14;
var result = aged <= 13 ? "Child" :
aged >= 14 && aged <= 18 ? "Teen" :
aged >= 19 && aged <= 59 ? "Adult" :
"Boomer";
document.write(result);
And your conditions are a little redundant. You can simplify like this:
var aged = 14;
var result = aged <= 13 ? "Child" :
aged <= 18 ? "Teen" :
aged <= 59 ? "Adult" :
"Boomer";
document.write(result);

Improve an if statement chain

if (firstPositionCpc && (firstPosition > 0 && firstPositionCpc <= maxCPC)) {
var newCPC = firstPositionCpc;
} else if (topOfPageCpc && (topOfPageCpc > 0 && topOfPageCpc <= maxCPC)) {
var newCPC = topOfPageCpc;
} else if (firstPageCpc && (firstPageCpc > 0 && firstPageCpc <= maxCPC )) {
var newCPC = firstPageCpc;
} else {
var newCPC = minCPC;
}
Here is some wrong scenario
KeywordIdReport :197857118477
campaignName :BP 2015 QC (FR)
maxCPC : 3.00
OldCPC :0.46
firstPositionCpc : --
topOfPageCpc : 0.46
firstPageCpc : 0.05
NewCPC : --
Here NewCPC needs to be a number. Hence, firstPositionCpc, topOfPageCpc and firstPageCpc need to exist and be a number.
KeywordIdReport :97483945
campaignName :BP 2015 QC (FR)
maxCPC: 3.00
OldCPC :1.96
firstPositionCpc : 4.28
topOfPageCpc : 1.68
firstPageCpc : 0.85
NewCPC : 4.28
Here NewCPC needs to be lower or equal to maxCPC. Normally, the answer should be 1.68 instead of 4.28 for NewCPC.
How could I fix the chain of if statement so that it will fix the wrong scenarios?
UPDATE
Now after improvement, how could I say that the type of firstPositionCpc, topOfPageCpc and firstPageCpc exist and need to be a number?
Hence, firstPositionCpc, topOfPageCpc and firstPageCpc need to exist and be a number.
The above doesn't really make sense given that you have 3 comparisons, so my answer will lean on the assumption that you want firstPosition > 0.
So I need to check if a value type is number and if that number is in some bound so taking your first if statement:
if (firstPositionCpc && (firstPosition > 0 && firstPositionCpc <= maxCPC)) {
var newCPC = firstPositionCpc;
}
I would change it to the following:
if(typeof(firstPositionCpc) == 'number' && firstPositionCpc <= maxCPC && firstPosition > 0){....}
typeof() reads the type of the parameter and returns a string indicating the value.
See here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

My if statement "between" is giving me wrong result

I am new here. I have a problem with my if/else if statement.
I got this:
if (unalumno.notas >= "90" && unalumno.notas <= "100") {
unalumno.notas = "A";
} else if (unalumno.notas >= "80" && unalumno.notas <= "89") {
unalumno.notas = "B";
} else if (unalumno.notas >= "70" && unalumno.notas <= "79") {
unalumno.notas = "C";
} else if (unalumno.notas >= "60" && unalumno.notas <= "69") {
unalumno.notas = "D";
} else if (unalumno.notas <= "59") {
unalumno.notas = "F";
}
All the else if statement is giving to me the right result in letters, but the first if continue giving the result in numbers. Hope can understand me. Sorry for english lol
Have a good day
As I said in my comment, parse the integer out and change all of your comparisons to numbers instead of strings:
var unalumnoNotas = parseInt(unalumno.notas, 10);
if (unalumnoNotas >= 90 && unalumnoNotas <= 100) {
notas = "A";
} else if (unalumnoNotas >= 80 && unalumnoNotas <= 89) {
notas = "B";
} else if (unalumnoNotas >= 70 && unalumnoNotas <= 79) {
notas = "C";
} else if (unalumnoNotas >= 60 && unalumnoNotas <= 69) {
notas = "D";
} else if (unalumnoNotas <= 59) {
notas = "F";
}
Also, if you throw an error or return early if the value is greater than 100, you can remove all of the extra && <= 89
if (unalumnoNotas > 100) {
throw new Error('Number too high');
}
if (unalumnoNotas >= 90) {
notas = "A";
} else if (unalumnoNotas >= 80) {
notas = "B";
} else if (unalumnoNotas >= 70) {
notas = "C";
} else if (unalumnoNotas >= 60) {
notas = "D";
} else if (unalumnoNotas <= 59) {
notas = "F";
}
You should use integers for comparison, or just parseInt("your string").
You are comparing strings instead of the integers that you should be comparing. Instead of the numerical comparison you think you're doing, its actually comparing the position of the characters in the string on their ASCII position.
You should parse the value into an int type then compare to numbers instead of strings.

Change Marquee Content Using Javascript

Before anyone says, I know there are better ways than using a marquee, however, for this instance I am using one.
Depending on the date, I want the marquee to say a different thing. Why is the marquee not changing and always saying default?
Javascript
var d = new Date();
var n = d.getDate();
if (n > 0 && n < 8){
var bday ="Birthday Kids name and age 1"
}else if(n > 7 && n < 15){
var bday ="Birthday Kids name and age 2"
}else if(n > 14 && n < 22){
var bday ="Birthday Kids name and age 3"
}else if(n > 21 && n < 29){
var bday ="Birthday Kids name and age 4"
}else if(n > 28 && n < 32){
var bday ="BirthdayKids name and age 5"
}
document.getElementById("birthdays").textContent = "We wish a very happy birthday to "+bday;
<marquee bgcolor="#088A08" id="birthdays" direction="left" loop="20" width="100%">Default</marquee>
See the fiddle
Javascript
var d = new Date();
var n = d.getDate();
if (n > 0 && n < 8){
var bday ="Birthday Kids name and age 1";
}else if(n > 7 && n < 15){
var bday ="Birthday Kids name and age 2";
}else if(n > 14 && n < 22){
var bday ="Birthday Kids name and age 3";
}else if(n > 21 && n < 29){
var bday ="Birthday Kids name and age 4";
}else if(n > 28 && n < 32){
var bday ="BirthdayKids name and age 5";
}
document.getElementById("birthdays").textContent ="We wish a very happy birthday to "+bday;
Notice that i've removed the == from your code which solves the problem as there is a problem with the syntax error.
== is used for comparisons and for assignments just = is used..
try
document.getElementById("birthdays").innerHTML
edit:
replace == with = and make sure the getElementById is called after the element or after the page is loaded

Password strength function return only one vlaue [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am new with Javascript and ,I'm trying to write a password strength function.
But each time I enter a password, it returns only one value ("very strong").
I completely confused !!
Here is my Code :
function pwd_Validation()
{
var strength = new Array();
strength[0] = "Blank";
strength[1] = "Very Weak";
strength[2] = "Weak";
strength[3] = "Medium";
strength[4] = "Strong";
strength[5] = "Very Strong";
var password = document.getElementById('pwd')
if (password.length < 1)
var score = 1;
else if (password.length < 4)
score = 2
else if (password.length >= 8 && password.value.match(/[a-z]/))
score = 3;
else if (password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/))
score = 4;
else (password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/))
score = 5;
document.getElementById('spnPwd').innerHTML = strength[score];
if ( password.value = "")
document.getElementById('spnPwd').innerHTML = strength[0];
document.getElementById('spnPwd').style.color="#FF0000"
if ( strength[score] == 1)
document.getElementById('spnPwd').innerHTML = strength[1];
document.getElementById('spnPwd').style.color="#FF0000"
if ( strength[score] == 3)
document.getElementById('spnPwd').innerHTML = strength[3];
document.getElementById('spnPwd').style.color="#FFCC00"
if ( strength[score] == 4)
document.getElementById('spnPwd').innerHTML = strength[4];
document.getElementById('spnPwd').style.color="#19D119"
if ( strength[score] == 5)
document.getElementById('spnPwd').innerHTML = strength[5];
document.getElementById('spnPwd').style.color="#006600"
}
HTML code :
Password : <input type="password" id="pwd" onblur="pwd_Validation()" />
<span id="spnPwd" class="pwd_Strength" ></span><br />
There were several coding errors and logic errors. I would suggest this rewrite that makes the following fixes/improvements:
Get the actual password value and use its length instead of using the length of the password DOM element.
Handle the case of the length between 4 and 7 (a case your logic skipped)
Sequence the regex tests in the right order so it actually finds the proper score
Corrected the punctuation regex
Fix else logic problem
Put the colors into a parallel array.
Declare the strength strings in a more efficient/compact way.
Give your score a default value so it is guaranteed to have a value.
Don't repeat regex tests more than once
Use regex.test because it's more efficient than regex.match when all you want to know is if it matched
Pull the desired color value from the array rather than an if statement for every score
Only fetch the spnPwd DOM element once
Changed the numeric regex to \d
Use braces on all if/else statements for safety
And the suggested code:
function pwd_Validation() {
var strengths = ["Blank", "Very Weak", "Weak", "Medium", "Strong", "Very Strong"];
var colors = ["#FF0000", "#FF0000", "#FFCC00", "#FFCC00", "#19D119", "#006600"];
var score = 0;
var regLower = /[a-z]/, regUpper = /[A-Z]/, regNumber = /\d/, regPunctuation = /[.,!##$%^&*?_~\-£()]/;
var password = document.getElementById('pwd').value;
if (!password) {
score = 0;
} else if (password.length < 2) {
score = 1;
} else if (password.length < 4) {
score = 2;
} else if (password.length <= 7) {
score = 3;
} else {
// length is >= 8 in here
if (regLower.test(password) && regUpper.test(password) && regNumber.test(password)) {
// if it also has punctuation, then it gets a 5, otherwise just a 4
if (regPunctuation.test(password)) {
score = 5;
} else {
score = 4;
}
} else {
// if doesn't have upper, lower and numbers, then it gets a 3
score = 3;
}
}
var spanPwd = document.getElementById('spnPwd');
spanPwd.innerHTML = strengths[score];
spanPwd.style.color = colors[score];
}
There's an if missing from the last else so it's parsed like this:
...
else {
(password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/))
}
score = 5;
It's a good habit to always use brackets in control structures.
You forgot to convert the password field to its value:
var password = document.getElementById('pwd')
should be
var password = document.getElementById('pwd').value
In your original case, password.length is undefined, and all comparisons with it evaluate to false. (So the final else is executed)
Also, your last else block
else (password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/))
score = 5;
should be
else if(password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/))
score = 5;
Aside from that, please use braces in your ifs. It is bad practice to have code like this:
if(...)
...
else if(...)
...
else
...
This is better:
if(...){
...
}else if(...){
...
}else{
...
}
you save to the var score and then you ask strength[score]. if (strength[score] == 3)
then you are missing some { } in the second part of the code!
in the last part you can use
switch(score) {
case 1: ... break;
...
default: ... break;
}
I've pushed your code through jsbeautifier.org. This has reindented your code according to how a javascript interpreter would actually run it. Please notice how your if statements are not running the code you think they are.
function pwd_Validation() {
var strength = new Array();
strength[0] = "Blank";
strength[1] = "Very Weak";
strength[2] = "Weak";
strength[3] = "Medium";
strength[4] = "Strong";
strength[5] = "Very Strong";
var password = document.getElementById('pwd')
if (password.length < 1) var score = 1;
else if (password.length < 4) score = 2
else if (password.length >= 8 && password.value.match(/[a-z]/)) score = 3;
else if (password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/)) score = 4;
else(password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/))
score = 5;
document.getElementById('spnPwd').innerHTML = strength[score];
if (password.value = "") document.getElementById('spnPwd').innerHTML = strength[0];
document.getElementById('spnPwd').style.color = "#FF0000"
if (strength[score] == 1) document.getElementById('spnPwd').innerHTML = strength[1];
document.getElementById('spnPwd').style.color = "#FF0000"
if (strength[score] == 3) document.getElementById('spnPwd').innerHTML = strength[3];
document.getElementById('spnPwd').style.color = "#FFCC00"
if (strength[score] == 4) document.getElementById('spnPwd').innerHTML = strength[4];
document.getElementById('spnPwd').style.color = "#19D119"
if (strength[score] == 5) document.getElementById('spnPwd').innerHTML = strength[5];
document.getElementById('spnPwd').style.color = "#006600"
}
To take some particular examples out:
if (strength[score] == 5) document.getElementById('spnPwd').innerHTML = strength[5];
document.getElementById('spnPwd').style.color = "#006600"
Likely you intended this to be:
if (strength[score] == 5) {
document.getElementById('spnPwd').innerHTML = strength[5];
document.getElementById('spnPwd').style.color = "#006600"
}
Also:
else(password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/))
score = 5;
You probably meant:
else if (password.length >= 8 && password.value.match(/[a-z]/) && password.value.match(/[A-Z]/) && password.value.match(/[0-9]/) && password.value.match(/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/)) {
score = 5;
}
The actual issue you mention in your code is because of the second conditional that I've pulled out. The line score = 5 is not part of any conditional, and will always be run (for reasons mentioned above). This is why you're always seeing that the passwords are "Very Strong".

Categories

Resources