Creating Objects in JavaScript Using Object Literals
Object literals are one of the most common ways to create objects in JavaScript. They are a collection of name-value pairs, where the property names and values are specified as strings, numbers, booleans, or functions. Object literals are enclosed in curly braces, and the property names and values are separated by commas. Here is an example of an object literal:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
var myObject = { name: 'John', age: 30, isMarried: true };
[/dm_code_snippet]
In this example, we created an object called myObject with three properties: name, age, and isMarried. We assigned the property values to strings, numbers, and a boolean. You can also create objects with functions as values, which are known as methods.
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
var myObject = { name: 'John', age: 30, isMarried: true, sayHello: function() { console.log('Hello, my name is ' + this.name); } };
[/dm_code_snippet]
In this example, we added a fourth property, sayHello, which is a function. This is known as a method because it is a function that is associated with an object. In this case, when we call myObject.sayHello(), it will log the string “Hello, my name is John” to the console.
Object literals are a great way to create objects in JavaScript. They are easy to read and can be used to quickly create objects with properties and values. They are also relatively easy to modify, as you can easily add or remove properties and values as needed.