Skip to main content

Command Palette

Search for a command to run...

Why console.log() returns undefined?

Published
2 min read
Why console.log() returns undefined?
T

Web developer with a passion for creating user-friendly websites. Proficient in HTML, CSS, Js, and React.js and open to new opportunities .

If you're already familiar with JavaScript, then chances are you have come across the console.log() function. This is a great tool for debugging your code and printing out information to the browser console. But did you know that it can sometimes return undefined? Today we'll take a look at why this happens and what it means for your code! So if you want to learn more about how this works, stick around!


A function is console.log(). Additionally, a function will always provide the caller with some kind of value back. The function will return undefined if no return value is supplied, like in the case of console.log ().

For example, copy and paste the below code into the console:

const userName = window.prompt("Enter Your Name: ")
function isThisWorking(input) {
    console.log(`How are you ${userName} . ${input} is passed in as an argument.`);
    return "I am returning this string!";
}
isThisWorking(3);

So, isThisWorking function will return back "I am returning this string!" in the console, because that's what the function is returning.

But, If we removed the return, it will return back undefined:

const userName = window.prompt("Enter Your Name: ")
function isThisWorking(input) {
    console.log(`How are you ${userName} . ${input} is passed in as an argument.`);
}
isThisWorking(3);

one more example:

function functionA() {
    return 1;   // it will return 1
  } 
  functionA()

here in this code, we are returning 1, so our code will return 1.

 function functionB() {
    return;    // it will return undefine
  }
  functionB()

here in this code, we are returning nothing, so our code will return undefined.


Thanks for reading my blog post today – I hope it helped clear up some confusion surrounding console logs in JavaScript!