Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does console.log say undefined, and then the correct value? [duplicate]

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?

like image 396
Michael Durrant Avatar asked Jun 21 '14 14:06

Michael Durrant


People also ask

Why does console log work but not return?

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.

Why is returning undefined?

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 .

Why does console log disappear immediately?

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.

What is the return value of console log?

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.


1 Answers

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 
like image 160
James Allardice Avatar answered Oct 21 '22 04:10

James Allardice