Average calculation returning Undefined when no Arguments is passed

Asked

Viewed 33 times

0

(function(){

console.log(media())

function media() {

    let total = 0
    let qtd = arguments.length

    for(i = 0; i < qtd; i++) {


        if(typeof arguments[i] !== "number") {

            return "Digite valores Validos"

        }

        total += arguments[i]
        return (total  / qtd) || 0

    }
}

})()

I want to understand why when the function is executed without parameters it shows undefined, and wanted to know how can I do so that when she returns the same, show an error message or some console.log.

  • 2

    You’re giving a return within a loop for, does not make sense. What is your intention with the code above?

1 answer

1


This code will return two references to undefined.

The first reference being the call of the immediate function declared in line #1. The second reference being the call of the nested function: media(). The reason for the return of the reference to undefined of function media() is along that line:

for(i = 0; i < qtd; i++) {

The test condition of the loop for is: while i is less than qtd. Being qtd the number of arguments passed to the function media and i igual a 0, then when the function does not receive any argument we have: qtd igual a 0.

Zero is not less than zero, but equal.

This makes the loop for is not executed, causing the next instruction to be executed after the loop for, this statement being a sum with a non-existent value - because there is no passage of arguments, being arguments[i] non-existent, this non-existent value is evaluated in undefined. We know that any operation with undefined is resulting in undefined. Soon the return of the function is undefined.

To treat this return, before the function returns statement, we can make an evaluation of the expression arguments[i], for example:

if(arguments[i] == undefined) console.log("Houve um erro")

Doing so treatment, but of course there is a vastness of other treatment possibilities.

Browser other questions tagged

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