Use return prompt with ternary operator

Asked

Viewed 58 times

1

How can I use its return directly in the expressions? Because I can only use it if I open the prompt 2 times.

I wanted, if in condition, the value is what I want, it (the value) fall in the direct expression, without me having to open the prompt again, understand?

let promptValue = prompt('Valor') > 10 ? 'Valor do prompt aqui' : 'Não';
console.log(promptValue);

As you can see, instead of the "Value of the prompt here" I would only get this value if I put another prompt, but in case I want the value I put in the condition prompt. Like?

1 answer

3


The prompt always returns a String, and not a number. You have to use Number() to convert to number. More than that you need to store the value in a variable in order to use as a condition and option in that ternary.

const val = Number(prompt('Valor'));
let promptValue = val > 10 ? val : 'Não';
console.log(promptValue);

  • 1

    Ah, that’s what I wanted to know. I put it in string there just for example, but it has the return in this val. Thanks Sergio, I didn’t know

  • Sergio, I saw your response again, now that I understand. For example, without creating a variable to pick up the prompt, do it directly, just like the question, how could it be? Ali vc stores the prompt in val and then creates another variable. It would be more or less like this here: Let promptValue = prompt('Value') > 10 ? 'Prompt value here' :?

  • 1

    @Lucascarvalho no, the ternary has no reference to the condition within the options. You could do let promptValue = ((val) => val > 10 ? val : 'Não')(Number(prompt('Valor')));, but this is a complex and disguised way.

  • 1

    Got it, ball show! Thanks for the explanation!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.