JavaScript Objects
July 9, 2021 · 5 min read
If you have any questions, feel free to comment below. Click the block can copy the code.
And if you think it's helpful to you, just click on the ads which can support this site. Thanks!
Objects are a JavaScript data type. We have already learned about numbers, strings, booleans, and undefined. An object can be understood as a collection of data. It consists of properties and methods.
Syntax #
Declaring a variable of the object type is essentially no different from declaring a numeric or string variable.
// Declare a string variable
let str = 'hello world!'
// Declare a numeric variable
let num = 199
// Declare an object variable using a pair of curly braces
// user is now an object; it is currently empty
// {} is an object literal
let user = {}
Properties and Access #
Descriptive data is called a property, such as a person’s name, height, age, or gender. Properties are generally nouns.
- Properties come in pairs consisting of a property name and value, separated by a colon (
:). - Multiple properties are separated by commas (
,). - A property is a variable attached to an object.
- Property names can be enclosed in
""or''; the quotes are usually omitted unless the name contains special characters such as spaces or hyphens.
// Describe a person's data with an object
// person is an object containing a name property
// Properties come in name-value pairs, separated by a colon (:)
let person = {
name: 'Xiao Ming', // Describe the person's name
age: 18, // Describe the person's age
stature: 185, // Describe the person's height
gender: 'male', // Describe the person's gender
}
After declaring an object and adding properties, you can use . or [] to obtain the corresponding property values. This is called property access.
<script>
// Describe a person's data with an object
// person is an object containing a name property
// Properties come in name-value pairs, separated by a colon (:)
let person = {
name: 'Xiao Ming', // Describe the person's name
age: 18, // Describe the person's age
stature: 185, // Describe the person's height
gender: 'male', // Describe the person's gender
};
// Access the person's name
console.log(person.name) // Result: Xiao Ming
// Access the person's gender
console.log(person.gender) // Result: male
// Access the person's height
console.log(person['stature']) // Result: 185
// Or
console.log(person.stature) // Also results in 185
</script>
Extension: You can also add properties to an object dynamically. This is equivalent to defining them directly, but offers more flexible syntax.
// Declare an empty object (with no properties)
let user = {}
// Add properties dynamically
user.name = 'Xiao Ming'
user['age'] = 18
// Adding them dynamically is equivalent to defining them directly, but offers more flexible syntax
Methods and Calls #
Behavioral information is called a method; a method is essentially a function.
- A method consists of a method name and a function, separated by a colon (:).
- Multiple properties are separated by commas (
,). - A method is a function attached to an object.
- Method names can be enclosed in
""or''; the quotes are usually omitted unless the name contains special characters such as spaces or hyphens.
<script>
// A method is a function attached to an object
let person = {
name: 'Xiao Hong',
age: 18,
// A method consists of a method name and a function, separated by a colon (:)
singing: function () {
console.log('Two tigers, two tigers, running fast, running fast...')
},
run: function () {
console.log('I run very fast...')
}
}
</script>
After declaring an object and adding methods, you can use . or [] to call its functions. This is called a method call.
<script>
// A method is a function attached to an object
let person = {
name: 'Xiao Hong',
age: 18,
// A method consists of a method name and a function, separated by a colon (:)
singing: function () {
console.log('Two tigers, two tigers, running fast, running fast...')
},
run: function () {
console.log('I run very fast...')
}
}
// Call the object's singing method
person.singing()
// Call the object's run method
person.run()
</script>
Extension: You can also add methods to an object dynamically. This is equivalent to defining them directly, but offers more flexible syntax.
<script>
// Declare an empty object (with no properties or methods)
let user = {}
// Add properties dynamically
user.name = 'Xiao Ming'
user.['age'] = 18
// Add a method dynamically
user.move = function () {
console.log('Move a little distance...')
}
</script>
Note: If properties or methods in the same object share a name, the later one overwrites the earlier one.
Multiword Properties and Properties Containing Hyphens #
Dot notation does not work for multiword property names or names containing characters such as hyphens.
Instead, use object['property']; either single or double quotes will work.
let person = {
'user-name' : 'timerring',
}
console.log(person.user-name) // NaN
console.log(person['user-name']) // timerring
null #
null is also a JavaScript data type. It is usually used only to represent a nonexistent object. When checked with typeof, its type is object.
Iterating Over Objects #
Objects do not have a length property like arrays, so you cannot determine their length that way. An object’s key-value pairs are unordered (their order does not affect the relationships between them), unlike the regular numeric indexes of an array.
<script>
// We do not recommend using for...in to iterate over arrays
let arr = ['pink', 'red', 'blue']
for (let k in arr) {
console.log(k) // Array index, but it is a string such as '0'
console.log(arr[k]) // arr[k]
}
// 1. Iterate over an object with for...in
let obj = {
uname: 'Teacher Pink',
age: 18,
gender: 'male'
}
// 2. Iterate over the object
for (let k in obj) {
console.log(k) // Property name, such as 'uname' or 'age'
// console.log(obj.k)
// This would mean console.log(obj.'uname'), which is invalid; use another approach:
// console.log(obj['uname']) 'uname' === k
console.log(obj[k]) // Output the property value: obj[k]
}
</script>
⚠ Using for…in to iterate over arrays is discouraged because k is a string. Remember:
kgives the object’s property name, andobjectName[k]gives its value.
Built-in Objects #
Recall that we have used console.log. console is a built-in JavaScript object with a method called log; console.log() calls that method.
Besides console, JavaScript has other built-in objects.
Math #
Math is a built-in JavaScript object called the math object. It contains properties as well as many methods.
Properties #
- Math.PI gives the value of pi.
// Pi
console.log(Math.PI);
Methods #
Math.random(): a random number between 0 and 1, including 0 but excluding 1 ([0, 1)).Math.ceil(3.4): discards the fractional part and increases the integer part by 1 (rounds up).Math.floor(4.68): discards the fractional part without changing the integer part.Math.round(4.849): rounds to the nearest integer.Math.max(10, 21, 7, 24, 13): finds the largest number in a group.Math.min(24, 18, 6, 19, 21): finds the smallest number in a group.Math.pow(4, 2): calculates 4 to the power of 2.Math.sqrt(16): calculates the square root.
References
Related readings
- JavaScript Functions
- JavaScript Arrays
- JavaScript Operators and Control Flow
- JavaScript Fundamentals
- HTML Basics
If you want to follow my updates, or have a coffee chat with me, feel free to connect with me: