Browser console and console.log

An indispensable tool when working with JavaScript is the browser console, which allows you to debug the program. Many modern browsers have a similar console. For example, to open the console in Google Chrome, we need to go to the More Tools menu -> Developer tools :

After that, a console will open at the bottom of the browser:

We can directly enter JavaScript expressions into the browser console and they will be executed. For example, let’s enter the following text in the console:

 alert("Hello world"); 

The alert() function displays a message box in the browser. As a result, after entering this command and pressing the Enter key, the browser will execute this function and display a window with a message:

To display various kinds of information in the browser console, the special function console.log() is used . For example, let’s define the following web page:

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascript Tutorials</title>
</head>
 
<body>
    <script>
        var a = 15 + 18;
        console.log("Operation result");
        console.log(a);
    </script>
</body>
 
</html>

In the JavaScript code, using the var keyword , a variable is declared a, which is assigned the sum of two numbers 15 and 18:

  var a = 5 + 8; 

Next, using the method console.log(), a message is displayed on the browser console

  console.log("result"); 

And at the end, also using the method console.log(), the value of the variable a is displayed on the browser console.

  console.log(a); 

And after launching the web page in the browser, we will see the result of the code execution in the console:

What is very useful, in the browser console you can also notice the line numbers of the code where exactly the output to the console was performed.

In the future, we will often access the console and use the console.log function.

Moreover, we could enter a similar code in the console itself:

We also sequentially enter the instructions and after entering each instruction, press Enter.

If we need the code in the console to wrap to a new line without being executed, then at the end of the JavaScript expression, press the key combination Shift + Enter . After entering the last instruction to execute the entered JavaScript code, press Enter.