Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Creating New Object

You can create a javascript object in a few different ways. You can define it hard-coded style (object literal) ...


// object literal
let Spaceship = { Designation : "NCC-1701", Name : "Enterprise" };
document.getElementById("demo1").innerHTML = Spaceship.Designation;

You can use a function and a constructor...


let color = "Red";
let speed = "Fast" ;
let car = new Car(color, speed);

function Car(color, speed)
{
    this.Color = color;
    this.Speed = speed;
}

 

Here is a more advanced version. It is an object in which the properties are functions. This is a kind of "utility" object.


const utils =
{
    // Sum an array
    sum: arr => arr.reduce((acc, curr) => acc + curr, 0),

    // create an array of numbers between min and max (edges included)
    range: (min, max) => Array.from({ length: max - min + 1 }, (_, i) => min + i),

    // pick a random number between min and max (edges included)
    random: (min, max) => min + Math.floor(Math.random() * (max - min + 1)),

    // Given an array of numbers and a max...
    // Pick a random sum (< max) from the set of all available sums in arr randomSumIn: (arr, max)=> {
    const sets = [[]];
    const sums = [];
    for (let i = 0; i < arr.length; i++)
    {
        for (let j=0, len=sets.length; j < len; j++)
        {
            const candidateSet=sets[j].concat(arr[i]);
            const candidateSum=utils.sum(candidateSet);

            if (candidateSum <=max)
            {
                sets.push(candidateSet); sums.push(candidateSum);
            }
        }
    }
    return sums[utils.random(0, sums.length - 1)];
    },
};