My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Why console.log("kill me now") gives me undefined?

Mushtaq Smb's photo
Mushtaq Smb
·Jan 11, 2022·

2 min read

Let's do a simple exercise - open your browser's dev console and display your name. If you have used JS at least once, you know the most common way to display something on the screen is using the console.log web API.

console.log("mushtaq");

I get the result as

mushtaq //line 1
undefined //line 2

How about we print some number?

console.log(9);

the output is as follows,

9 //line 1
undefined //line 2

Although we are displaying valid data types i.e string and number type. Why are we still seeing the undefined keyword displayed in the result? How about the following Boolean or an expression?

console.log(true);
console.log(9+6);

we get,

true //line 1
undefined //line 2

and expression result below respectively,

15 //line 1
undefined //line 2

No matter what data type we use alongside console.log() we are still at the receiving end of the undefined keyword. This calls for some clarification.

According to the official documentation undefined type is applied to a variable that has only been declared but not been explicitly assigned a value by the user. In all our examples we are actually assigning legit strings, numbers, boolean etc as values to display, yet we still see the undefined keyword. Why?

The culprit here isn't what we pass onto the console.log() method as a parameter but the method itself. We should understand that console log method is an inbuilt function which does not have any predefined return expression or a value, it always returns undefined. Without a return value at this stage JS engine in our browsers cannot proceed ahead with the interpretation and continue with the execution of remaining Javascript code. Because from the point of JS engines, a function always returns something.

The function returns explicitly if a return statement is defined by the user, whereas an implicit return means that return value will always be undefined. The console log method has an implicit return value, hence the keyword undefined is always printed after every usage of console.log();