console log object js

Console Log Object in JavaScript

When working with JavaScript, it is common to use objects to store and manipulate data. To debug and test your code, it is helpful to know how to log objects in the console. This can provide you with valuable information about the state of your program and help you identify any issues that may be present.

Using console.log()

The simplest way to log an object to the console is by using the console.log() method. This method allows you to log any variable or expression to the console, including objects.

const myObject = {
  name: "John",
  age: 30,
  city: "New York"
};

console.log(myObject);

The above code creates an object called myObject and logs it to the console using console.log(). When you run this code in your browser's console, you will see the object logged as a collapsible tree, which allows you to inspect the object and its properties.

Using JSON.stringify()

If you need to log an object in a more readable format, you can use the JSON.stringify() method. This method converts a JavaScript object into a JSON-formatted string, which can be logged to the console.

const myObject = {
  name: "John",
  age: 30,
  city: "New York"
};

console.log(JSON.stringify(myObject, null, 2));

The JSON.stringify() method takes three arguments: the object to convert, a replacer function (which we are not using in this example), and the number of spaces to use for indentation. In this example, we are using a value of 2 for indentation, which makes the output more readable.

Using console.dir()

The console.dir() method is similar to console.log(), but it provides a more detailed output for objects. When you log an object using console.dir(), you will see a list of its properties and methods, along with their values and types.

const myObject = {
  name: "John",
  age: 30,
  city: "New York"
};

console.dir(myObject);

The above code logs the myObject object to the console using console.dir(). When you run this code in your browser's console, you will see a detailed output for the object, including its properties and methods.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe