Categories
JavaScript

console.log()

The console.log() method outputs a message to the web console.

Syntax

console.log(obj1 [, obj2, …, objN]);
console.log(msg [, subst1, …, substN]);

Output single value / object

let x = 1;
console.log(x);

let someObject = { str: "Some text", id: 5 };
console.log(someObject);

Note: what you get logged on the console is a reference to the object, which is not necessarily the ‘value’ of the object at the moment in time you call console.log(), but it is the value of the object at the moment you open the console.

Output multiple values

let x = 1
let y = 2
let z = 3

// method 1: with , the arguments are passed separately to the log method
console.log("x:", x, "y:", y, "z:", z);

// method 2: +(string concatenation) = toString()
console.log( x + ' ' + y + ' ' + z );

// method 3: template literal
console.log(`${x} ${y} ${z}`);

 Using string substitutions

// object => %o or %O
// Outputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
let user = {
  name: 'Jesse',
  contact: {
    email: 'codestackr@gmail.com'
  }
}
console.log("user is %o.", user);

// Integer => %d or %i
// String => %s
console.log("%s is %d years old.", "John", 29);

// floating-point value => %f
console.log("Foo %.2f", 1.1);

Styling console output

// %c directive
// The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.

console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");

reference:

https://developer.mozilla.org/en-US/docs/Web/API/console/log

https://www.freecodecamp.org/news/javascript-console-log-example-how-to-print-to-the-console-in-js/

https://developer.mozilla.org/en-US/docs/Web/API/console#outputting_text_to_the_console

https://stackoverflow.com/questions/33339688/why-comma-and-plus-log-the-console-output-in-different-pattern

Leave a comment