console.log("hi") gives undefined hi console.log(1+1) gives undefined 2
Whether it's a string or integer calculation, I get undefined then the correct answer.
Why do I get the undefined message? Is there a good way to avoid it?
console. log will log to the console (as the name suggests) while return just ends the function and passes the value to whatever called that function. Since you're not using that return value, you won't see anything but it is produced.
A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
This is happening because your form is submitting to itself and the page loads in a fraction of seconds for you to notice the difference.
Return value: It returns the value of the parameter given. JavaScript codes to show the working of this function: 1) Passing a number as an argument: If the number is passed to the function console. log() then the function will display it.
The console will print the result of evaluating an expression. The result of evaluating console.log()
is undefined
since console.log
does not explicitly return something. It has the side effect of printing to the console.
You can observe the same behaviour with many expressions:
> var x = 1; undefined;
A variable declaration does not produce a value so again undefined
is printed to the console.
As a counter-example, expressions containing mathematical operators do produce a value which is printed to the console instead of undefined
:
> 2 + 2; 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With