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">
    <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>
    /*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() {

    /*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*/
        /*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)*/

Link your website to this page! Copy and paste the URL below:
Copyright 2018. All Rights Reserved.