What Is The Difference Between else and !== In JavaScript? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
Is there any difference between else and !== in JavaScript?
I am beginner in JavaScript and I can't find their difference, for example in this code I expected the text to appear when I enter other days.
const day= prompt(`Insert The Day`);
if(day===`monday`){
console.log(`Pray All Day Long🙏🏽`)
}
else if(day===`tuesday`){
console.log(`Code All Day Long`)
}
else if(day===`wednesday`){
console.log(`Meditate All Day Long`)
}
else if(day===`Thursday`){
console.log(`Design All Day Long`)
}
else if(day!==`monday`){
console.log(`Why Not Monday?`)
}
else{
console.log(`Invalid Day`)
}

These 2 are entirely different operators.
else is to be applied after an if block, and is run if the condition from the if block wasn't met.
== is a "loose" equals, which means that values of different types with the same value are considered to be equal. This means that 1 == "1" will return true, even if 1 is an int and "1" is a string.
=== checks for absolute equality, which means that only values with the same type and value are considered equal. This means that 1 === "1" is false, but 1 === 1 is true.
!== is the opposite of ===, which means that any value with a different type or value is considered not equal. This means that 1 !== 2 is true, and 1 !== "1" is as well.

Firstly, I think you should learn about if..else. You can read more here, and the !== is an operator
And in your case, I suggest using switch
switch(day) {
case 'monday': console.log('Pray All Day Long🙏🏽');
break;
case 'tuesday': console.log('Code All Day Long');
break;
...
default: console.log('Invalid Day');
break;
}
Finally, the better performance sulotions are Map and using [key, value] of Object
Hope useful for you.

Related

Using == in javascript always false [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Hello I use a javascript function to change my HTML background color by DI state
here's my code
function pageData() {
var DI1_STATE =document.getElementById('DI1').textContent; //load DI1
console.log(DI1_STATE); //DI1_STATE= ON or OFF(TYPEOF = String)
console.log(DI1_STATE=='ON'); //ALWAYS FLASE
console.log(DI1_STATE=='OFF'); //ALWAYS FLASE
var result = DI1_STATE.localeCompare('ON'); //WORK preset 1(TRUE) or -1(FLASE)
console.log(result);
if (DI1_STATE == 'ON'){
document.getElementById('DI1').style.backgroundColor = 'Coral';
document.getElementById('DI1').style.color = 'White';}
else{
document.getElementById('DI1').style.backgroundColor = '#ccc';
document.getElementById('DI1').style.color = 'black';}}
I wonder why == is not work
the whole Html code
I made the server at a microchip,i update the "DI1" by getsensorDATA3()
and the server command below
You always have to check for line breaks, spaces or other non visible characters when comparing string values from html elements. Try
var DI1_STATE =document.getElementById('DI1').textContent.trim()
localeCompare is used to determine sort order and only reports back if the reference string comes before or after the comparison string (in the sort order):
Negative when the referenceStr occurs before compareString
Positive when the referenceStr occurs after compareString
Returns 0 if they are equivalent
You might use it like array.sort((a, b) => b.localeCompare(a));
Tests....
let test = document.getElementsByTagName('textarea')[0].value;
console.log('"' + test + '"')
console.log('test == "TEST"', test == "TEST") // false
console.log('test.localeCompare("TEST")', test.localeCompare("TEST")) // 1
test = test.trim();
console.log('test == "TEST"', test == "TEST") // true
console.log('test.localeCompare("TEST")', test.localeCompare("TEST")) // 0
<textarea>TEST </textarea>

Can we write an if statement backwards in javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What is the difference between these two expressions?
if (userStatus === 'OFFLINE') document.forms.newMessage.fields.disabled = true;
and
document.forms.newMessage.fields.disabled = (userStatus === 'OFFLINE');
document.forms.newMessage.fields.disabled = (userStatus === 'OFFLINE')
is equivalent to
if (userStatus === 'OFFLINE') {
document.forms.newMessage.fields.disabled = true;
} else {
document.forms.newMessage.fields.disabled = false;
}
Notice the else statement. If there is no else statement then your first piece of code only sets document.forms.newMessage.fields.disabled when the condition (userStatus === 'OFFLINE') is met.
Consider the case in which
document.forms.newMessage.fields.disabled is already true but userStatus is "ONLINE".
With your first piece of code, document.forms.newMessage.fields.disabled will remain true (because of the lack of else statement) , but with the second piece of code, it will be set to false.

How to check for two conditions using && operator [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to use 1 If statement to check that both values are not zero
if ((minvalue !== 0) && (maxvalue !== 0)) {
// Both are not 0
}
else
{
// Both values are 0
}
I can get it to work by using two if statements
if ((minvalue !== 0){
if(maxvalue !== 0){
// Both values are not zero
}
}
But I'm not sure how to do it in one If.
This will also work
if (minvalue || maxvalue) {
// Both are not 0
}else {
// Both values are 0
}
Edit :
If you example doesn't work, you should consider doing
console.log(minvalue,maxvalue);
Your code works, so that's your minvalue and maxvalue which are wrong. Might be strings
Your first code block should be fine. If you want to get a bit more clever about it you could instead test that the product of both values is not zero (as anything multiplied by zero will be zero).
const minvalue = 1
const maxvalue = 3
if (minvalue * maxvalue !== 0) {
console.log('foo!') // foo!
} else {
console.log('bar...') // [not hit]
}
Also, stylistically, it's considered bad practice to leave hanging curly braces. Move your else and subsequent opening block curly brace up a line (as above).

best way to compare 2 variables with 4 values each [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have 2 variables... both of them can get a status (0,1,2,"xxx")
What would be the best way to compare these variables? Or are a lot of if's and else if's the best way?
if((Status1 && Status2) == 2){
connectorImage = "connector.png";
}
else if((Status1 && Status2) == 1){
connectorImage = "connector_grey.png";
}
else if(Status1 == 1 && Status2 == 2){
connectorImage = "connector_greytogreen.png";
}...
You could try something like
if(Status1 == Status2){
//Do something
}else if(Status1 < Status2){
//Do something else
}else if(Status2 > Status1){
// Do something else
}
This should work, unless if all 16 combinations require a unique action. Then you're stuck with lots of if's and else's
it depends on what exactly you need to compare.
e.g.: If you need to get the correct image to a status i would use something like this:
function getImageByStatus(int status) {
switch (status) {
case 1:
return "connector.png";
case 2:
return "connector_grey.png";
}
return "";
}
In case you have more complex comparisons, your only way might be some if-statements
You can construct connector image from statuses:
var connectorImage = status1 + "_" + status2 + ".png";
and rename you images to something like "0_0.png", "1_0.png", etc.
Or rename your status to something more meaningfull
Or create a mapping between combined statues and connector names:
var statusesToConnectorImages = {
"0_0" : "connector.png",
"0_1" : "connector_grey.png"
}
var connectorImage = statusesToConnectorImages[status1 + "_" + status2];

Syntax error when trying to test for empty string [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
In Javascript, I am trying to do a simple task of testing and returning the longest of two words. If the words are empty then the return should say "empty string". I keep getting a syntax error when testing for an empty string with the or elseif statement. I am using (!word1) and (!word2) because my understanding is in Javascript it is a boolean statement and should be false. Please tell me where I am going wrong:
function longest(word1, word2) {
if (word1.length >= word2.length) {
return (word1);
} else {
return (word2);
} else if (!word1) || (!word2) {
return "an empty string";
}
}
console.log(longest('hi'));
if conditions should be surrounded by exactly 1 pair of parentheses.
Change else if (!word1) || (!word2) to else if (!word1 || !word2).
Your "else" clause should be the last clause in your if statement:
function longest(word1, word2) {
if (word1.length >= word2.length) {
return (word1);
} else if (!word1 || !word2) {
return "an empty string";
} else {
return (word2);
}
console.log(longest('hi'));
You got your else and else if around the wrong way. Heres the complete code for your problem.
function longest(word1, word2) {
if ((!word1) || (!word2)) {
alert ("an empty string");
} else if (word1.length >= word2.length) {
alert (word1);
}else{
alert (word2);
}
}
longest('hi');

Categories