Why is it that after defining a function through the browser console , " undefined " is returned ? Why happens? What would be missing in a function declaration for this not to happen?
For example, when creating a function with the following syntax, " undefined " is returned:
function miFuncion(algo){
return algo;
}
//salida: undefined
Also if I use a syntax like the following, " undefined " is returned:
var miFuncion = function(algo){
return algo;
}
//Salida: undefined
but, when you try something like:
miFuncion = function(algo){
return algo;
}
change the return after the function is created, does anything change using this syntax?
I add a screenshot to make the idea that the question raises more objective
The browser console is designed to take the last expression, look up its return value, and then display that value.
When you make an assignment statement JavaScript assigns the assigned value, but the console will take one more step and that is to return the return value of the last statement.
In the console declaring a variable using or not using the keyword
var
actually does the same thing: assign the property to the objectwindow
:The difference is that the declaration does not have
var
a return value, which is why the console returnsundefined
, while using the declaration without the keyword,var
the console immediately returns the assigned value.It should be noted that when declaring functions (regardless of the way it is done) it also returns,
undefined
since the function declaration does not have a return value either.I hope I was clear with the explanation.
The function is created, but the argument
algo
has no value assigned, so it returnsundefined
.Try the following:
For your first function being like this:
We assign a default value to the parameter and then print on the screen.
Resulting:
For example, you can check the type of that parameter like so:
Which returns:
Otherwise, if you assign a value to it as I explained at the beginning and repeat the code using it,
typeof()
it will return:The above should be applicable for the 3 cases you show.