js property code example

Example 1: object literal javascript

// Object literals are defined using the following syntax rules:
// A colon separates property name from value.
// A comma separates each name-value pair from the next.
// There should be no comma after the last name-value pair.

// If any of the syntax rules are broken, such as a missing comma or colon or curly brace,
// an error will be thrown.

var myObject = {
    sProp: 'some string value',
    numProp: 2,
    bProp: false
};

Example 2: add property to object javascript

let yourObject = {};

//Examples:
//Example 1
let yourKeyVariable = "yourKey";
yourObject[yourKeyVariable] = "yourValue";

//Example 2
yourObject["yourKey"] = "yourValue";

//Example 3
yourObject.yourKey = "yourValue";

Example 3: how to a property from a JavaScript object

delete myObject.regex;
// or,
delete myObject['regex'];
// or,
var prop = "regex";
delete myObject[prop];


/** Demo */
var myObject = {
    "ircEvent": "PRIVMSG",
    "method": "newURI",
    "regex": "^http://.*"
};
delete myObject.regex;

console.log(myObject);

Example 4: Add New Properties to a JavaScript Object

var myDog = {
  "name": "Happy Coder",
  "legs": 4,
  "tails": 1,
  "friends": ["freeCodeCamp Campers"]
};

myDog.bark = "woof";
// or
myDog["bark"] = "woof";

Example 5: add property with value in js

var myObject = {
    sProp: 'some string value',
    numProp: 2,
    bProp: false
};