What is console.log?

Asked

Viewed 49,363 times

61

I see this in some Javascript files:

console.log(algumaCoisa);
console.log("alguma coisa");

What it’s for and how it works?

I’m trying to make a log() customized for a Userscript (see How can I log information without using Alert in Userscripts) and I realized I don’t know what’s behind the console.log.

  • Some tips: You can use Colors to have a Better view of: console.log('%c Sample Text', 'color:green;'); Or add some VAR in the text using: console.log(`Sample ${variable}`, 'color:green;'); When you have some objects, you can show using some table: https://www.w3schools.com/jsref/met_console_table.asp

4 answers

54


Console object

The console is effectively an object with several associated methods.

The object console provides access to the browser debugging console. The operation of this object varies from browser to browser but there are certain methods that are viewed as a standard. One of these methods is the log().

Log method

The method log() exists essentially to allow sending data to the browser debug console. Any information can be sent, usually for the purpose of debugging code.

Example of Firefox console:
inserir a descrição da imagem aqui Priming Ctrl + shift + k to call it in Firefox.

Considerations

As this object varies and there is still no standard governing the functioning and methodology of it, there are some considerations to have:

// Exemplo a enviar algo para a consola do navegador
var s = "bubu";
console.log(s);

Potential problems:

  • User may have turned off the console;
  • The browser may not have a web console;
  • The method we are using may not work in a particular browser.

In Javascript, an execution failure can result in a blocking of all other Javascript. If for example we make use of the console.log(X) when console does not exist or method log() does not exist, we will have an error in our code.

Alternative:

We can make use of a try...catch to try to send to the console and in case of failure to act otherwise:

function consola(s) {
    try { console.log(s); } catch (e) { alert(s); }
}

And so if it goes well, the information will be on the console, if it goes wrong, a alert() with information that would go to the console.

Of course we can do nothing or send an Ajax call to a server with the error if it is critical and has to be logged "hurt who it hurts".

/* Enviar algo para a consola do navegador com fallback 
 * fazendo uso da função já declarada conforme visto em cima
 */
var s = "bubu";
consola(s);

Consoles

As explained, there is not exactly a standard for the web console, so there are some references to each one’s help pages:


Note: Response to evolve within a few days as soon as you finish compiling more relevant information on this subject.

  • 8

    Yes! StackExchange.resposta.carimbar('Canônica')

51

This writes any message in the browser’s LOG, which can be viewed at any time.

These messages can be used for various purposes:

  • assist in programming (like when you give a alert just to see if a method has been called... works the same, but without interrupting the flow)
  • library usage instructions... imagine that a function has become obsolete, and you want people to stop using the function, but without launching an exception... although in this case, other functions can be used: console.warn would be more recommendable.

Other existing LOG methods:

  • console.info
  • console.warn
  • console.error
  • console.debug

They all serve to write messages, the difference between the methods is precisely in the meaning of the message. See how the messages look with each of these methods:

inserir a descrição da imagem aqui

    (example: Chrome console window)

  • 3

    +1 by showing the other methods of the console object

  • 1

    I didn’t know about the other methods besides log. Excellent answer! + 1

25

console.log is one method among several others available for the browser debug console.

List of other console methods.

console.log is used to issue registration information in general. For example:

var algumObjeto = {
  str: "Algum texto",
  id: 5
};
console.log(algumObjeto);

Exit:

({str:"Algum texto", id:5})

var algumObjeto = {
  str: "Algum texto",
  id: 5
};
console.log(algumObjeto);
Observar a saída no console do navegador!

You can also use string substitution and other arguments with this method. For example:

for (var i=0; i<5; i++) {
  console.log("Olá, %s. Você me chamou pela %dª vez.", "João", i+1);
}

Exit:

Olá, João. Você me chamou pela 1ª vez.
Olá, João. Você me chamou pela 2ª vez.
Olá, João. Você me chamou pela 3ª vez.
Olá, João. Você me chamou pela 4ª vez.
Olá, João. Você me chamou pela 5ª vez.

for (var i = 0; i < 5; i++) {
  console.log("Olá, %s. Você me chamou pela %dª vez.", "João", i + 1);
}
<p>Observar a saída no console do navegador!</p>

Limitations and lack of support

This feature may not be available or active in the browser, so you should always test its existence before trying to use it:

// verifica se o objeto window.console existe
if (window.console){
    window.console.log("Log isto");
}

Important remarks

In addition to the above, older versions of EI, or < IE9, do not present this method in the form previously presented (with the same name/signature) or do not present, as cited in these references:

Source: MDN Console

6

a way to debug your code. This command will show in your browser console what is written in the log function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.