Javascript Basics - Looping Over Keys in an Object

Looping Over Keys in a Javascript Object

Usage: Copy and paste the code below into a .html page on your local server and call the page. From there you'll need to open the Devtools (or whatever panel your browser uses) so that you can display and interact with the Javascript console. The code is commented to help you understand as much as possible, so be sure to utilize the comments in context, it will help everything make better sense.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Javascript test document</title>
    
    <script>
    
    /*loop over the keys in an object, display just the key name and/or the 
    value of the key as well*/
    
    /*This is a Javascript object called "Circle", it has a property called radius 
    (which the object accepts as an argument when the object gets instantiated) and a 
    method called draw which when called simply logsto the console the 
    string 'draw' */

    function Circle(radius) {
        this.radius = radius;
        this.draw = function() {
            console.log('draw');
        }
    }

    /*Create a new instance of the Circle above, let's creatively call and reference it 
    as circle*/
    const circle = new Circle(10);

    //Enumerate (loop) over the properties in the Circle object using Javascript's for loop
    for (let key in circle) {
        if (typeof circle[key] !== 'function') 
        /*optional: added this "if" to only flag the functions in the Circle object*/
        
        console.log(key,circle[key]); 
        /*use the bracket notation to access the value of the key, logout to the console*/
    }

    const keys = Object.keys(circle); 
    /*Object.keys() is an internal method that returns all of the keys in the passed
     in object (here it's the circle object)*/
    console.log(keys);
    </script>
    </head>
    <body>
    test
    </body>
    </html>
    

Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/javascript/javascript-basics-looping-over-keys-in-an-object/
Copyright 2018. All Rights Reserved.