Table of contents
What is console🤔?
I hope you're familiar with a web browser, so a JavaScript Engine
is designed for these browsers with the console
. The browser developer console is a tool that logs the information associated with a web application, such as network requests and errors.
What is console.log()🤨?
So, if you're using the console and want to log some value on the console, then you need to use a function and that function which you're gonna use is console.log()
. So as the name suggests that it's a function the first and foremost thing that strikes our brain is output. We need to provide an argument
that is then treated as a parameter
. A parameter can be an array
, an object
, or any message
and it returns
the value of the parameter given.
Let's have a look at examples -
const myName = "Bhavesh Upadhyay"
console.log(myName)
const myDOB = 17
console.log(myDOB)
const beautifulArray = [ 0, 1]
console.log(beautifulArray)
const hereIsMyNewAndShinyObj = { a: true, b: false }
console.log(hereIsMyNewAndShinyObj)
Output on the console -
Problem🧐
But, one thing that you have surely observed is that the undefined
logging after every output, why is that? Is it something getting printed automatically or just because I'm printing something it comes as a bonus point with that? Well, To help you understand more clearly let's look at some more simple examples where I don't pass any parameter to the function to differentiate -
console.log()
console.log(5)
Solution 😎
As we know, we have the void keyword in JavaScript which is useful for evaluating expressions that do not return any value. But in JavaScript, we don't define the return type of the function compared to other programming languages so any function which does not have a return statement or does not have a value to return, returns undefined
.
Similarly, console.log() is a function in JavaScript that does not have a return statement, hence when we invoke
it, it logs the parameters if any and due to the missing return statement, it also logs undefined.
💡 when we provide the return statement in a function it does not logs undefined
Example -
const sumOf = (num1, num2) => {
console.log("the sum of", num1, "and", num2, "is")
return num1 + num2;
}
sumOf(2,3)
I hope this helps you learn and love JavaScript even more. See you soon with some other blog, until then peace out 👋.