-7
Good afternoon, everyone.
I’m a beginner and started a Javascript course.
I’m trying to do this exercise:
- Make a Script to ask the user for his name, age, city of birth and UF. Write on the page the following sentence: I [name of the person], I am x years old, I am [older or younger] and I was born in the city of [name of the city] - [U].
I did the following however, it is replacing the age by the "adult" or "minor":
Exercise 3<script>
var nome = prompt("Digite seu nome");
var idade = prompt("Digite sua idade");
var cidade = prompt("Digite a cidade em que nasceu");
var uf = prompt("Digite a UF da cidade em que nasceu");
var maiorDeIdade = "maior de idade"
var menorDeIdade = "menor de idade"
if (idade > 18){
idade = maiorDeIdade
}
else {
idade = menorDeIdade
}
document.write("Eu " + nome + ", tenho " + idade + " de idade, sou" + idade + " e nasci na cidade de " + cidade + " - " + uf );
</script>
How to leave showing age in number and whether it is older or younger ide age?
Thank you!
You want to do
idade = idade + ' (' + maiorDeIdade + ') ';
?– Rafael Tavares
In the text he should present example: I Vinicius am 18 years old, I am of age and I was born in the city of Brasilia - DF
– Vinicius Barros Marques
prompt
returns a string. so Javascript can’t verify that the text "18" is larger than the number 18. Use Number or parseint to convert from string for number (whole) before checking the condition of majority. Answer to another question– Valdeir Psr
Shouldn’t it be >= 18? Anyway, don’t overwrite the age variable, otherwise you lose the number given by the user
– bfavaretto
@Valdeirpsr the problem is that you are using a variable (
idade
) for two things. Create a variablevar maiorOuMenorDeIdade
, within theif
instead of storing inidade
, store in this new variable. And then in yourdocument.write
swap thesou + idade +
forsou + maiorOuMenorDeIdade +
– Rafael Tavares
https://codesandbox.io/s/maior-ou-menor-de-idade-3d5zt
– Rafael Tavares
It worked out here guys. Thank you!
– Vinicius Barros Marques
@Viniciusbarrosmarques to succeed and be right are very different things; I always put this to show the difference https://i.stack.Imgur.com/zdAbK.jpg. You’ve received a response that makes you right, more than just seeing the result show up. Someone thought she was wrong for giving a negative, the person could steer what she thought wrong there, because I couldn’t see.
– Maniero