...

Developer essentials: JavaScript console methods | MDN Blog

Developer essentials: JavaScript console methods | MDN Blog

If you know all about console.log(), you can skip to logging levels as we’ll quickly cover the basics first.
If you’re still here, let’s learn about what the console is and how it’s used.
Most people use console.log() to send generic information about their code to the console, which you can find in your browser’s developer tools (e.g., Firefox’s Developer Tools).

Note: You can copy and paste all of the examples below into your browser’s console and try them out for yourself.

The log() method is the bread and butter of the console object: you provide something to log(), and voilà — it’s logged to the console:

const hello = "Hi there, welcome to MDN Web Docs!";
console.log(hello); 

It’s great to find out if your code is working as expected by making the output visible, like this example where I’m checking if I correctly used DateTimeFormat:

const currentDate = new Date(); const formattedDate = new Intl.DateTimeFormat("en-US").format(currentDate);
console.log("Current date:", formattedDate); 

You can provide multiple items in the log and apply some fancy formatting as well (for more details, see Outputting text to the console):

const currentDate = new Date(); const formattedDate = new Intl.DateTimeFormat("en-US").format(currentDate);

console.log("Today's date is %s", formattedDate); 

It’s also fun to use the console interactively as most browsers support autocomplete that lets you tab through suggestions.
If you don’t know what to log, type console.log(window. (or any other object) and let browser suggest some interesting capabilities, like the navigator:

console.log(window.navigator.oscpu); 

Don’t forget to get rid of leftover console.log() calls in your code before you make it public, though! It’s good practice to remove development logging from production applications.

Discover more from WIREDGORILLA

Subscribe now to keep reading and get access to the full archive.

Continue reading