What is the difference between the console.log and the alert functions?

the title really says it, but what is the difference between

console.log();

and

alert();

i know both get text typed in and display the output, but what is the actual difference between the two? not urgent, just curious :grinning:


The quick summary

console.log():

  1. log() is a method on the console.
  2. Is used in all types of Javascript.
  3. Is un-intrusive on a webpage.
  4. Is generally used for testing and not production.

alert():

  1. Is a method on the window.
  2. Can only be used when a Window object is involved, usually a webpage on a browser.
  3. Is intrusive, takes focus away from the window and requires user input to clear.
  4. Can be used in testing for more immediate feedback, or used (sparingly) in production for urgent user alerts.

The big explanation

In terms of functionality, console.log() takes text as an input and outputs it onto the console, whether that’s the web console or in raw JS onto the command line, essentially wherever the JS is running. More specifically, the log() method is a method on the console object that logs whatever text it takes in to whatever console JS is running on.

The alert() method however is not a method on the console, but is a method on the window. This means that if you try to use alert() in a JS file that isn’t loaded into a webpage, it will not work as there is no window object to speak of. When on a webpage, the method takes focus away from the webpage sending the alert, and runs whatever the browsers alert() function entails. Usually this is a pop-up box which displays the text fed into the alert() function.

In terms of use case they are different as well. console.log() is un-intrusive, as you need to go and seek out the console yourself to see the message that has been output. However alert() snaps focus away from the page and forces you to confirm you have seen it before interacting further.

For a live website the difference is clear, as alert has an actual use case you may wish to take advantage of if the situation calls for it. However you don’t want to overuse alert on a live website as that can easily get incredibly annoying for the end user. In contrast console.log() doesn’t really have a good use case. The best implementation I have seen on a live website is for preventing scams or for recruitment. Open up the console on either of these pages to see what I’m talking about. Generally though there isn’t much of a use case live, it’s more of a testing tool.


Hopefully that explanation covers what you wanted to know! If you have any other questions do let me know.

3 Likes

thanks for that! i see what you mean now, alert is like the message you get when you try to close multiple tabs, and console.log is more like normal text