Why does it return "Undefined" because it has an "if/Else"?

Asked

Viewed 171 times

-4

I have this logical condition using the if/Else!

function area(largura, altura) {
    const area = largura * altura
    if (area > 20) {
        console.log(`O valor acima do permitido: ${area}m2.`)
    } else {
        return area
    }
}

console.log(area(5, 5)) //retorna no console "25m2 undefined".

As far as I knew case the condition if were true, he did not read the condition of else. Yet in that instruction he is reading the else returning the result undefined. Why does this happen?

  • 1

    this Undefined must be the return of the function area(5,5), inside your if it writes on the console and does not return anything for that of Undefined

  • So, but he returned the result 25m²...still not understood why he rendered the IS, if the condition of the if is true!

  • did debug to make sure where is passing and what is shown Undefined?

  • You didn’t go to @kervincandido already explained the problem

3 answers

3

He doesn’t get into the else at any time, and that’s the problem, in the else returns something, when it enters the if he returned nothing, which is undefined, and that is what needs truth.

I think that’s what you want, otherwise the problem is not well defined and the whole code is wrong.

function area(largura, altura) {
    const area = largura * altura;
    if (area > 20) {
        console.log(`O valor acima do permitido: ${area}m2.`);
    } else {
        return area;
    }
}

let resultado = area(5, 5);
if (resultado != undefined) console.log(resultado);
console.log(area(5, 5) + 1);
resultado = area(4, 5);
if (resultado != undefined) console.log(resultado);

I put in the Github for future reference.

The if is used to validate the parameter, so if it is outside the given criteria it displays a message from log and terminates the function by returning nothing, and that part is very important, as he did not calculate anything the result of the function is an undefined value. I imagine that is what you want, if not, the code is completely wrong and we have no way to solve the problem because we do not know what to do, we can only help what is in the question.

So this is a function that may or may not give a result, if the parameter is ok it returns a valid result, if the parameter passed is not adequate it generates a bad value and does not return a valid result, therefore it returns a undefined.

What to do to use the function if it can return an invalid value? You must test if the value is valid before using it. This is a design pattern of the best known and used.

Then stores the result in a variable and makes a if to see if the value is valid, and only if it is can you use the variable somewhere, like printing it for example.

But if you don’t want to return an invalid value then you would have to take the condition and accept any past value. Of course, there are alternatives, but it is not common to be used, especially in Javascript. You could make an exception, which luckily isn’t in the JS culture, and you’d have to deal with it in the call, it just changes the way you treat it. Or it would have to return a valid value even if invalid, which would make the code unreliable, would not make sense.

Note that if making an account with the undefined result gives an invalid result and this is obvious, you will have to do something to deal with it.

Keep the undefined

Why is the answer not good? See below that in an account it gives a result wrong silently, if you do not take care causes a huge damage. My solution gives a clear and obvious error, can not continue with that value.

function area(largura, altura) {
    const area = largura * altura;
    if (area > 20) {
       // Ou retornas false ou null
       console.log(`O valor acima do permitido: ${area}m2.`);
       return false;
    } else {
       return area;
    }
}

console.log(area(5, 5) + 1);

I put in the Github for future reference.

0

This happens because when you run a function with console.log(myFunction()) he expects some return of its function.

Your if occurs correctly, and executes your console.log(), but you perform the function through the console.log() he expects some return and returns nothing.

With that the JS showcase undefined.

To solve this, you could change the console.log() by a return, would look like this:

function area(largura, altura) {
    const area = largura * altura;
    if (area > 20) {
       return false;
    } else {
       return area;
    }
}

var valor = area(4, 5);

if(!valor)
{
  console.log("Os valores informados são altos demais.");
}else{
  console.log(valor);
}

  • 2

    And if it’s used in an account?

  • I don’t know what that would be, I’m a beginner, could you explain to me?

  • Look at my answer.

  • I edited my answer, it got better?

  • improved, but still fall into the problem I speak in my answer.

  • I hadn’t realized it, I’d have some way to solve this problem in a different way than your answer?

  • There is, but I find it more complicated, if it was one that I think is appropriate I would have posted.

  • Okay, I marked the response as wiki, thank you very much

Show 3 more comments

-6


Quite simply the code is not reading the condition else.

The code is not returning any results within the condition if, so when the function has just been executed the returned value is undefined, because no value has been defined. When the value log is done this is exactly what it will write.

function area(largura, altura) {
    const area = largura * altura
    if (area > 20) {
        console.log(`O valor acima do permitido: ${area}m2.`)
    } else {
       return area
    }
}

// Aqui faz print de undefined porque não é retornado nenhum valor da função
console.log(area(5, 5)) 

MDN web Docs

The overall value undefined represents an undefined value. It is one of the primitive types of Javascript.

A function returns undefined if a value is not returned.

Note

I edited the answer and removed the code proposal considering the comments left and the question asked.

Return undefined, false, null, 0, etc. is subjective to the intention of the programmer and application of the code. It should always be considered who will use the code and what is considered a normal or exceptional behavior.

Initially this response suggested an approach with return false. You can find arguments for and against in the comments.

  • Two return followed? How the second will be executed?

  • Well viewed @Maniero. I am changing the answer to take this into account, but anyway you should not let go undefined

  • I like your explanation, but since I don’t have enough reputation yet, I couldn’t leave any comment on your answer to the question of undefined.

  • I edited my answer to show why your answer is not good.

  • @Maniero I appreciate the effort to give a good answer, but the reality is that the output parameters should always be treated (such as input parameters). undefined is not a good answer to a function. If in his code there is no return to values above 20, then make it an error, can not be solution. The error must be dealt with in some way. What if it wants to add up all the areas? In this case your suggestion does not work, because it fails with results undefined. Always depends on the Veloper approach. Jsfiddle

  • 1

    Yes, when the calculation has wrong input parameters it is to fail. The goal is just that. This Jsfiddle shows the absurdity that it is to return anything other than undefined. It gives a completely wrong result, you can not add something with what can not be calculated, only an error is acceptable in this case. You’re making the nonexistent turn to 0, but the nonexistent is different from 0, zero is a valid, nonexistent value is invalid.A wrong answer is a good answer to a function? This is your answer, you treat the error as if it were a valid and arbitrary answer to be 0

  • 2

    How so undefined is not a good answer to a function? Then the language API itself is all wrong, it has many native functions that return undefined to indicate an exceptional condition or invalid value (and who called the function that tries to check the return to know if it worked - the treatment of the error, in this case, is out of function, because it only indicates what happened - even because the treatment may vary, so it makes more sense to stay out even).

  • 1

    @hkotsubo https://answall.com/q/21767/101

  • @Maniero The goal to return false does not allow the sum. It does not matter if the JS allows it (JS has its problems). What matters is that the function gives a valid answer. An exception to this function is not "area exceeded value", but "cannot calculate value". Overcoming value is a matter of business logic and business logic is no exception. Doing direct accounts with "functions you already know that can return problematic results" is another problem.

  • If the JS has problems, you have to get around, not cause more problems. Yes, the purpose of your code is to give a valid answer, until it is invalid, this is a major error. Is another problem? And how do you solve? How do you make sure he doesn’t screw up the whole code without the consumer not even noticing?

  • problem solved @Maniero

  • It’s not subjective, it’s a clear mistake. If you said that you prefer to use exception to deal with it I would even accept as subjective, because it is a solution, although the culture of JS is not to use it. A solution that causes problems silently is bad for everyone, it has no subjectivity in it. Now you didn’t propose a solution, but okay this whole page was a problem from the beginning and now it’s closed and hidden from the others, it won’t cause extra problems for those who are learning.

Show 7 more comments

Browser other questions tagged

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