What does the solution make comparisons against strings in the following code? JS
The statement of the exercise is : Declare the weekday variable that receives a string "Sunday". Then implement a conditional using the if that compares if dayweek equals "Sunday", if true print a string " today is football day!!!".
I made the following code:
var diaDeSemana = "domingo";
if ( "domingo" === diaDeSemana) {
console.log("hoje é dia de futebol!");
}
The solution is accepted, but the warning appears that it compares against strings! I have searched the internet about the different ways of comparison, but I did not find any result for this error.
7 answers
What you did is right. I see no need to compare in any other way in an exercise except somewhere you have a string.
What you can do is declare the right answer in a variable as well and then compare those variables. This is sometimes used when the server is the one giving the right answer in a variable of fetch
.
For example:
const RESPOSTA_CERTA = 'domingo';
function oQueFazerHoje(diaDeSemana) {
if (diaDeSemana === RESPOSTA_CERTA) return 'hoje é dia de futebol!';
}
console.log(oQueFazerHoje('domingo'));
At work we use a lot the practice of declaring static/constant string variables in letters uppercase to be clear to the programmer that he is using a constant. In addition to avoiding errors, it is also good practice not to write the mesta string multiple times in different variables... I have even created a tool to change javaScript and do this in code automatically.
I solved this problem as follows:
var diaDeSemana = "domingo";
var dia = 'domingo';
if (diaDeSemana == dia)
{
console.log("Hoje é dia de futebol!!!");
}
Without displaying the error message!
I am redoing the exercise and found this solution:
var diaCerto = "domingo"
var diaDeSemana = diaCerto
if(diaDeSemana == diaCerto){
console.log("Hoje é dia de futebol!!!")
}
var diaDeSemana = "domingo";
var valorComparativo = "domingo";
if (diaDeSemana === valorComparativo) {
console.log("hoje é dia de futebol!");
}
var diaDeSemana = "domingo";
var dia = 'domingo';
if ( diaDeSemana === dia) {
console.log("hoje é dia de futebol!");
}
let diaDeSemana = "domingo"
let dia = "domingo"
if (diaDeSemana == dia)
{
console.log("Hoje é dia de futebol!!!");
}
var diaDeSemana = "domingo";
if ( diaDeSemana = "domingo" ) {
console.log("hoje é dia de futebol!");
}
In this way and the correct Sunday is being assigned to the day of the week, it cannot be compared, for we know that it is already a day of the week.