In JavaScript the console.log () method displays a message in the browser console. This message can be a simple text string or one or more variables or even a JavaScript data structure.
In fact, this method is often used by web developers to test portions of code.
It will soon become our best friend in JavaScript!
JavaScript console log – first example
Let’s take examples of using the following method.
We create a program that tests if a number is positive, displaying the message in the browser console.
So, we initialize the variable a to a positive value, for example 13 and after, with a simple conditional statement we test if this value is positive or not.
We display the relevant message using the JavaScript console.log method.
var a = 13;
if(a > 0) {
console.log('The number is positive');
} else {
console.log('The number isn't positive');
}
In the browser console I can also print the variable a, concatenating it with the text string.
I can use the + symbol, as in the example below:
console.log('The number ' + a + ' is positive');
In JavaScript console.log we can use also the comma:
console.log('The number ', a ,' is positive');
In the console I can also print a Boolean value, such as the test I entered in the if.
In our case:
console.log(a > 0);
In the console we will have the boolean value true.
JavaScript console log – second example
We create an array of numbers and display the result in the browser console.
To tackle this example, we must therefore know the arrays presented in this lesson: introduction to arrays in JavaScript.
var numbers = [14, 8, 2, 11, 6, 7];
console.log(numbers);
In the console we will see our array as shown below:
Similarly, for example, I might want to print an object:
var car = {
modell: 'fiat',
color: 'white'
};
console.log(car);
In the console we will see our object as shown in the figure below:
Conclusion
As we have seen in JavaScript the console.log method allows you to print messages, variables and data structures. It is therefore useful for developers to do quick tests on the written code. In the next few lessons, I will explain other basic concepts of the JavaScript language.