How do I declare a ternary operation for it to show on an HTML page?

Asked

Viewed 71 times

2

<script>
    function calcular() {
        var ns1 = window.document.getElementById('nt1')
        var n1 = Number(ns1.value)

        var ns2 = window.document.getElementById('nt2')
        var n2 = Number(ns2.value)

        var ns3 = window.document.getElementById('nt3')
        var n3 = Number(ns3.value)

        var ns4 = window.document.getElementById('nt4')
        var n4 = Number(ns4.value)

        var res = window.document.getElementById('res')

        var s = (n1 + n2 + n3 + n4) / 4

        s >= 6 ? 'Aprovado':'Reprovado'

        res.innerHTML = `Resultado: ${s} `

    }

The value of s was to show Approved or Failed, but instead only returns the mean value.

2 answers

5


Assign the expression result to a variable, and use this variable in the output:

var resultado = s >= 6 ? 'Aprovado' : 'Reprovado';
res.innerHTML = `Resultado: ${resultado}`;

Or, as Maniero suggested, make the term ternary directly in string template:

res.innerHTML = `Resultado: ${s >= 6 ? 'Aprovado' : 'Reprovado'}`;

Which use will depend on the situation and style, there is no rule.

  • 1

    Thank you so much! Solved my problem.

3

You believe too much in variables and interestingly in this case the lack of one was the problem. You made the expression and did not keep anywhere the result of it.

Then tried to use the average value and not what wanted to print which is the text of the approval or disapproval.

One of the problems that caused this was the variable’s bad name, it doesn’t seem but if you had called it media it would be harder to use it in place of the expected result. It would be more obvious that it is printing something wrong

You can solve this problem well with only one variable (it gives without any, but then it starts to be unreadable, so avoid).

function calcular() {
    var media = (Number(window.document.getElementById('nt1').value) +
    Number(window.document.getElementById('nt2').value) +
    Number(window.document.getElementById('nt3').value) +
    Number(window.document.getElementById('nt4').value)) / 4;
    window.document.getElementById('res').innerHTML = `Resultado: ${media >= 6 ? 'Aprovado' : 'Reprovado'}`;
}
calcular();
<input id="nt1" value="1">
<input id="nt2" value="2">
<input id="nt3" value="3">
<input id="nt4" value="4">
<div id="res">

I put in the Github for future reference.

There is nothing wrong with creating other variables, but I find it unnecessary, too obvious variable for me is noise, unless it is a mandatory intermediate result or is used more than once.

  • 1

    I didn’t think to use it that way. As I’m still learning the basics, I’m still too stuck to the variables.

Browser other questions tagged

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