Bearing in mind that empty strings (""
) in Javascript are values falsy, you can use vagas[lugar]
directly on if
without the need for any kind of comparison.
This happens because the if
, when testing its expression, checks whether the value can be converted to the corresponding boolean. As Boolean("")
(note the empty string in the first argument) evaluates to false
, in case the vacancy is "empty", it will not "enter the if
".
Learn more about values Truthy and falsy here.
Thus:
if (vagas[lugar]) {
// A vaga está usada...
} else {
// A vaga está vazia...
}
The advantage of this is that your array may contain other values falsy, which will also be considered as an empty vacancy. For example, null
, undefined
, false
etc..
We therefore have:
let vagas = [
null, undefined, '', // <--- Todos os valores desta linha serão vistos como vaga vazia.
'Fiat, Placa ABC-0123' , 'HB20, Placa ACB-0213' ,
'Palio, Placa BCA-3210', 'Kadett, CBA-2031'
];
console.log(`No estacionamento tem ${vagas.length} vagas`);
for (let lugar = 0; lugar < vagas.length; lugar++) {
if (vagas[lugar]) {
console.log(`Na vaga ${lugar + 1} está o Automóvel ${vagas[lugar]}.`);
} else {
console.log(`Vaga ${lugar + 1} está vazia.`);
}
}
Another option is to compare the value literally with an empty string, as suggested by another answer.
When there is no car in the vacancy, Voce wants to show on the console something like
A vaga 5 está vazia
, would that be? because I didn’t quite understand your question.– Cmte Cardeal
exact! pardon I’ll edit the question but that’s right!
– Murilo C.