Doubt about functions defined within constants

Asked

Viewed 44 times

0

Execute:

function ok(n) {
  return console.log(n + 2);
}

console.log('porque o resultado da expressão abaixo trás o valor "NaN"?');
console.log('const minhaConstEumaFuncao = ok(), result: ')

const minhaConstEumaFuncao = ok()


console.log('enquanto que se eu der um log na minha constant "minhaConstEumaFuncao" o valor que resulta é: ', minhaConstEumaFuncao)

console.log('Enquanto que se eu der um typeof(minhaConstEumaFuncao) aparece: ', typeof(minhaConstEumaFuncao));

Why the typeof the constant that stores a function is Undefined while the log of a function’s constant brings Nan?

2 answers

4


Let’s ask one question at a time.

because the result of the expression below brings the value "Nan"?

the function "ok" expects a parameter n and you are not passing any parameter, when you do not pass a parameter to the function it is like undefined, within the function you try to sum Undefined with 2, which generates an Nan (not a number).

To solve this just pass a parameter to the function like this:

ok(2)

So it will bring the value 4 :)

while if I log in my "myConstant" myConstEumFunction" the value that results is: Undefined

you are storing the return value of the function to the constant but the function returns nothing! then the constant has value undefined also.

Whereas if I give a typeof(myConstEumFuncao) appears: Undefined

typeof Undefined is Undefined

1

Because the console.log does not return a value.

If you do something like

var val = console.log(2 + 2);
console.log(val);

You will realize that val holds the value undefined. That’s because the console.log does not return the value it prints. So in your function if you want to return the same value that is printed by console, you should do something like

function ok(n) {
  var resultado = n + 2;
  console.log(resultado);
  return resultado;
}
  • But what would explain the typeof "variable" then be Undefined?

  • 1

    An uninitialized variable has the value undefined in JS. The value of minhaConstEumaFuncao is undefined, and the type of a undefined is "undefined".

Browser other questions tagged

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