DIV Contents

5 Ways to print arrays to the browser console window in javascript?

This tutorial talks about how to display an array of javascript objects to console logs for debugging. It also includes how to print primitive values to the console. There are many ways we can print the javascript array into the console.

In javascript, We have console object, which has the following things used for printing

if you have an array with either objects or primitives, printed using console.log, it always gives [object, object] that does not help debug.

let employees = [  id: 1, name: "kiran" >,  id: 2, name: "franc", >, ]; console.log(employees);

Let’s see an example for printing arrays in javascript

Читайте также:  Java database programming with jdbc

How to print an array of primitive types in javascript

In this, we have an array of primitives like numbers, and strings.

We can do it in multiple ways using javascript loops and object methods.

using for-of loop

  • Array of strings is created inline using square brackets
  • print the array at once using console.log — [ ‘one’, ‘two’, ‘three’ ]
  • Used for-of loop to iterate and print using console statements
let stringArray = ["one", "two", "three"]; console.log(stringArray); for (let str of stringArray)  console.log(str); >

using forEach with a callback function

each method in the array iterated with each element is applied with a callback function.

let stringArray = ["one", "two", "three"]; stringArray.forEach(function (str)  console.log(str); >);

Object keys with the map method

An object is a class in javascript which has the keys method accepts a string array, and returns an array of strings of enumerable properties. callback in the map is called for each element.

Object.keys(stringArray).map((str) => console.log(stringArray[str]));

An array can contain multiple objects. Each object contains key and value pairs enclosed in .

There are multiple ways we can display object arrays.

SON.stringfy

Using JSON.stringfy is used to print the object in json string format. JSON is available in every browser.

let employees = [  id: 1, name: "kiran" >,  id: 2, name: "franc", >, ]; console.log(employees); console.log(JSON.stringify(employees));
[  id: 1, name: "kiran" >,  id: 2, name: "franc" >, ][( id: 1, name: "kiran" >,  id: 2, name: "franc" >)];

using the console.table

console object has a table method introduced in the latest javascript.

It prints a beautiful table format with each object in an array representing each row.

It supports all browsers and also nodes introduced since the V10+ version.

let employees = [  id: 1, name: "kiran" >,  id: 2, name: "franc", >, ]; console.table(employees);
┌─────────┬────┬─────────┐  (index) │ id │ name │ ├─────────┼────┼─────────┤  0  1  'kiran'   1  2  'franc'  └─────────┴────┴─────────┘

Conclusion

Printing arrays give an object, an object which does not help debug. It covers multiple ways to print an array into the console.

Источник

How to print object in JavaScript? [SOLVED]

Everything in JavaScript is an object. So simply, in order to print objects in JavaScript, you will need to use the console.log() method. This method takes an object as input and prints it to the console. In this article, we will show the different ways to use the console.log() method with objects to print objects.

Method-1: Use console.log to print an Object in JavaScript

The way to log (or print data) in JavaScript is via the console.log() method. So, if you want to print an object, you can by passing it to the console.log() method. This will print the object in its entirety. For example, the obj binding links to an object with four properties, and then passed to the console.log() method, it prints all the properties within curly braces.

const obj = < name: "Femi", status: "Junior", age: 23, isActive: true, >; console.log(obj); 

Method-2: Use object.propertyName notation to print Object values in JavaScript

However, if you only need specific properties within the object, you can by passing the property name to the console.log() method. So, if we want to print only the isActive property, we can via the object.propertyName dot notation.

const obj = < name: "Femi", status: "Junior", age: 23, isActive: true, >; console.log(obj.isActive); 

You can also print multiple properties of an object by passing in an array of property names as you would with strings.

const obj = < name: "Femi", status: "Junior", age: 23, isActive: true, >; console.log(obj.isActive, obj.age); 

Method-3: Use stringify() to print objects in JavaScript

If you want to print an object in a more readable format, you can use the JSON.stringify() method. This method takes an object as input and returns a JSON-formatted string. Using the same obj binding as an example, the below code illustrates the behavior of the JSON.stringify() method.

console.log(JSON.stringify(obj)); 

The above output is a string with a JSON format.

Method-4: Use for loop to print object values in JavaScript

We can print out all the object values by looping through the object. The for. in loop will be effective in looping through the object, and obtaining the values to be logged.

const obj = < name: "Femi", status: "Junior", age: 23, isActive: true, >; for (const value in obj)

Method-5: Use Object.values() method to print object values in JavaScript

If we need the values within the object as an array, we can make use of the instance method called Object.values() . This method takes an object and returns an array of the object’s property values. Let’s illustrate this by passing the obj binding to the method.

const obj = < name: "Femi", status: "Junior", age: 23, isActive: true, >; console.log(Object.values(obj)); 

Summary

The only way to print (or log) an object is via the popular console.log() method. There are different approaches such as printing the object in its entirety, printing only the object properties, printing the object as a JSON-formatted string, or printing the object’s property values as an array.

References

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment Cancel reply

JavaScript Tutorial

  • Beginner Guide
    • Define Global Variable
    • Working with Object Literals
    • Working with Template Literals
    • Classes Overview
    • Subclass Examples
    • Iterators and Generators
    • Error Handling
    • Date Formatting
    • parseFloat()
    • Array.pop()
    • Array.slice()
    • Array.unshift()
    • Array.join()
    • Array.findIndex()
    • Array Slicing Methods
    • Remove Element from Array
    • Check Array is Empty
    • Create Unique Array of Objects
    • Convert Array to String
    • String.toLowerCase()
    • String.toString()
    • String.trimEnd()
    • String.trim()
    • String.replaceAll()
    • String.startsWith()
    • replaceWith()
    • String.indexOf()
    • replaceAll() with regex
    • Check if String is Number
    • Check string contains spaces
    • Convert String to Boolean
    • Check String contains Substring
    • Compare Strings
    • Math.acos()
    • Math.abs()
    • Math.asin()
    • Math.atan()
    • Math.cbrt()
    • Math.ceil()
    • Math.cos()
    • Math.floor()
    • Math.fround()
    • Math.hypot()
    • Math.log()
    • Math max()
    • Math.power()
    • Math.random()
    • Math.toRadians()
    • Nested Function
    • Arrow Function
    • Optional Parameters
    • The arguments Object
    • Calling Vs Invoking a Function
    • Call a function every second
    • Using function as Values
    • Chaining Functions
    • if statement
    • Handling Special Characters
    • hide() Method
    • Set.add()
    • Remove Element from Set
    • DOM Selector Methods
    • Find Elements in DOM
    • Remove DOM Element
    • Replace DOM Element
    • Get DOM Element Width
    • addEventListener()
    • querySelector()
    • getBoundingClientRect()
    • NodeList
    • Node.insertBefore()
    • Event Bubbling
    • Parse JSON File
    • Parse YAML File
    • Parse CSV File
    • async function
    • await
    • Exponentiation (**)
    • Bitwise XOR (^)
    • Nullish Coalescing Operator (??)
    • Double Exclamation Mark (!!)
    • Spread Operator (. )
    • Destructuring assignment
    • instanceof Operator
    • Access map with index
    • Check map size
    • Sort map by value
    • Sort by date
    • Add days to date
    • date/time field value out of range
    • Promise Thenable Object
    • Promise.all()
    • Promise.resolve()
    • Promise.race()
    • Promise.reject()
    • Chaining Promises
    • Keyboard Events
    • Mouse Events
    • Singleton Pattern
    • Mediator Pattern
    • Observer Pattern
    • Factory Pattern

    Источник

    JavaScript/Vue.js print object in the console

    If you’re a web developer like me, you probably use console a lot. We use it to debug JavaScript code, to print out the contents of an object etc.

    I use built-in Chrome tools, which is enough for most of the cases. I also use a Vue Devtools extension, when I build Vue.js apps, and I love it.

    Here is a short and sweet tip on how to print JavaScript object using console.log() .

    How to print out the content of the JavaScript object

    Suppose you have a JavaScript object:

    To print out the content of person, you first need to stringify it using JSON.stringify() method.

    str = JSON.stringify(person, null, 2); // it will also indent the output

    Then pass it to console.log()

    Your console output will be

    JavaScript print object in console

    If you need to reverse the operation use JSON.parse() method

    Hi, I’m Renat 👋

    Bonus console tips

    #1 console.clear()

    When your console log becomes too long you can clear its content using console.clear()

    console.clear() function

    #2 console.count()

    If you want to count how many times your function has been called, you can use the console.count() function. It also takes an optional parameter “label”. Here is an example:

    let user = ""; function greet() < console.count(user); return "hi " + user; >user = "bob"; greet(); user = "alice"; greet(); greet(); console.count("alice");

    You’ll see output like this:

    console.count() function

    #3 console.table()

    This one is my favourite, you can print a proper table with the objects using console.table() function.

    var people = [ < name: "Nedd", surname: "Stark" >, < name: "Robb", surname: "Stark" >] console.table(people) 

    You’ll see this beautiful table inside the console.

    console.table() function

    If you find this post useful, please let me know in the comments below.
    Cheers,
    Renat Galyamov

    Источник

    JavaScript Print to Console | Object | Div | Page | Button

    What is the way JavaScript Print the content (data)? This can be confusing because in another language (Java, Python, etc) print means, print statements in console only. But in JavaScript Print can use a browser to print a page by the printer. OR Print the data in an HTML div tag. In this tutorial, we will discuss how JavaScript uses a “Print Keyword“.

    JavaScript Print to Console Object Div Page Button

    • How to print to console – Hello World
    • Print page Using Button
    • A print page on load
    • Javascript print object
    • Print div

    JavaScript Print to console chrome & Other browsers

    Use a console.log() method to print message in the console. It is use full for developing purposes.

    Visible console tab in browser press F12 button. Or you can go through Right click -> inspect element -> console

          

    JavaScript Print in console

    Output: A screenshot of Safari browser, for another browser it may look different.

    JavaScript Print to console chrome & Other browsers

    JavaScript Print Page | Button

    There is a shortcut keyboard for the javascript print page is ctrl+p. But you can also provide a Button for the print page. Where popup will show with print option.

    JavaScript help to use a print function of the window object. You just need to call a window.print() prints the current web page. Let’s see the example code.

    Use input tag where value=”print” attribute. Also adding a tag for which will not show a confirmation popup after click the print button.

        

    JavaScript Print Button

    Output: See GIF image output of the safari browser.

    JavaScript Print Page Button safari

    JavaScript Print Page chrome

    You can just add line window.print() in tag to JavaScript print web page on load. See below line of code.

        

    JavaScript Print Button

    Can Javascript Print Object

    Like if you a JSON or other type object and want to print the value for dubbing or another purpose. Then you can do it using -> console.dir(obj). See a complete example of it.

        

    JavaScript Print Object

    Output: Below screenshot of inspect element -> console (Safari Browser)

    Javascript Print Object

    How JavaScript Print Div Content

    Some time HTML div tag need to print the content of it, or any specific tag. You can do it like this example.

          
    Hello i want print this line.

    Output: Below screenshot of safari browser.

    JavaScript Print Div Content

    Follow this tutorial link for JavaScript Print Hello World using function Example- https://tutorial.eyehunts.com//js/javascript-hello-world-alert-function-print-example/

    Do comment if you have any doubt, suggestions or questions on this topic.

    Note: The JavaScript Print to Console Examples are tested on Safari browser (Version 12.0.2).
    OS: macOS 10.14 Mojave
    Version: HECMAScript 2018

    Источник

Оцените статью