Unexpected Behind The Scenes of console.log() 😶‍🌫

arjuncodess

Arjun Vijay Prakash

Posted on February 8, 2024

Unexpected Behind The Scenes of console.log() 😶‍🌫

🤔 Have you ever thought about how console.log works and how it can handle many arguments at once?

If you’ve worked with JavaScript, then you must have used the console.log method.

It's a function that can accept any number of arguments and print them in the console.

console.log(n1, n2, n3, n4.....n)
Enter fullscreen mode Exit fullscreen mode

😮 But have you wondered how it handles these variable number of arguments?

Well, such functions are also known as variadic functions and you can create them in JavaScript using the rest operator(...).

Let's consider an example of a function written to calculate the sum of n numbers.

First, you create a function using the rest operator to collect all arguments into an array.

This allows an unlimited number of arguments to the function.

(To be honest, there's always some limit, try finding out and comment below as a sign you read the article!)

let sum = (...args) => {
    console.log(args)
}

sum(1, 2, 3, 4, 5, 6);
sum(0);
sum(10, 20, 30);
Enter fullscreen mode Exit fullscreen mode

Image

When the function is called, observe this keyword args captures the arguments as an array.

Once you have this array of values you can continue writing the code to print the sum.

let calculateSum = (...numbers) => { 
    console.log(numbers.reduce((total, num) => total + num))
} 

calculateSum(1, 2, 3, 4, 5, 6); 
calculateSum(0); 
calculateSum(10, 20, 30);
Enter fullscreen mode Exit fullscreen mode

Image

Comment below the theories you thought were behind this functionality! (Believe it or not! I thought it was some kind of miracle 😂)

I hope you liked the article! ❤️

Connect with me: linktree

Happy Coding! 🚀
Thanks for 14415! 🤗

💖 💪 🙅 🚩
arjuncodess
Arjun Vijay Prakash

Posted on February 8, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related