• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • JS Introduction
  • JS Getting Started
  • JS Syntax
  • JS Variables
  • JS Generating Output
  • JS Data Types
  • JS Operators
  • JS Events
  • JS Strings
  • JS Numbers
  • JS If Else
  • JS Switch Case
  • JS Arrays
  • JS Sorting Arrays
  • JS Loops
  • JS Functions
  • JS Objects
  • JS DOM Nodes
  • JS DOM Selectors
  • JS DOM Styling
  • JS DOM Get Set Attributes
  • JS DOM Manipulation
  • JS DOM Navigation
  • JS Window
  • JS Screen
  • JS Location
  • JS History
  • JS Navigator
  • JS Dialog Boxes
  • JS Timers
  • JS Date and Time
  • JS Math Operations
  • JS Type Conversions
  • JS Event Listeners
  • JS Event Propagation
  • JS Borrowing Methods
  • JS Hoisting Behavior
  • JS Closures
  • JS Strict Mode
  • JS JSON Parsing
  • JS Error Handling
  • JS Regular Expressions
  • JS Form Validation
  • JS Cookies
  • JS AJAX Requests
  • JS ES6 Features
Home >> javascript >> JS Objects

JS Objects

Welcome to another tutorial, here you will learn how to create and use objects in JavaScript.
 

What is an Object?

JavaScript is an object-based language and almost everything is an object or acts as an object in it. To achieve effective and efficient use of JavaScript, we

need to understand how objects work and also, how to create your objects and apply them.

In JavaScript named values are referred to as properties of the object, it is simply the collection of named values. From our previous tutorial on JavaScript arrays, you learned that an array is a collection of values. This set of values has an index (or numeric key) that starts from zero and increases by one for each value. Though, an object can be likened to an array but differs on the bases that you define the keys yourself, for instance, age, sex, and so on. 

The sections below will review a lot of things about objects in detail.
 

Creating Objects

In JavaScript, objects can be created with curly brackets {} with an optional list of properties. These properties are "key: value" pairs, where the key (known as property name) is always a string, and the value (also known as property value) can be any data type, like numbers, strings, Booleans, or complex data types like functions, arrays, and other objects. 

More so, properties with functions as their values are often called methods that will distinguish them from other properties. Below is an example of what a typical JavaScript object may look like;

var person = {
    name: "Peter",
    age: 28,
    gender: "Male",
    displayName: function() {
        alert(this.name);
    }
};

From the example above, an object called a person was created that has three properties name, age, and gender, and one method displayName().

The method displayName() displayed the value of this. name, which resolves to person. name. In JavaScript, it is the easiest and preferred way to create a new object, which is known as object literals syntax.

In general, property names do not need to be quoted except they are reserved words, if they contain spaces or special characters (anything other than letters, numbers, and the _ and $ characters), or if they start with a number, as shown in the illustration below:

var person = {
    "first name": "Peter",
    "current age": 28,
    gender: "Male"
};

Note: From ECMAScript 5, reserved words can be used as object's property names without quoting. But, you should avoid doing this for better compatibility with programmed language.

 

Accessing Object's Properties

To get access to the property of a value, you use the dot(.), or ([]) notation. This is shown in the example:

var book = {
    "name": "Harry Potter and the Goblet of Fire",
    "author": "J. K. Rowling",
    "year": 2000
};

// Dot notation
document.write(book.author);  // Prints: J. K. Rowling

// Bracket notation
document.write(book["year"]); // Prints: 2000

Try with example

 

The dot notation is simpler to read and write, however, it cannot always be used. This is because if the name of the property is not valid (meaning if it contains spaces or special characters), the dot notation cannot be used; so the bracket notation is what you can use. Let’s take a look at this example:

var book = {
        name: "Harry Potter",
        author: "J. K. Rowling",
        "publication date": "12 Aug 2022"
};

    // Bracket notation
    document.write(book["publication date"]); // Prints: 12 Aug 2022

Try with example

 

Note: The square bracket notation offers much greater flexibility than the dot notation. It makes it possible to property names as variables instead of just string literals, as shown in the following example below:

var person = {
    name: "Jervis",
    age: 28,
    gender: "Male"
};

var key = prompt("Enter any property name to get its value");
alert(person[key]); // Outputs: Peter (if enter "name")

Try with example


Looping Through Object's Properties

In looping, the for… in loop is used to iterate through the key-value pairs of an object. Below is an example 

var person = {
    name: "Peter",
    age: 28,
    gender: "Male"
};

// Iterating over object properties
for(var i in person) {  
    document.write(person[i] + "<br>"); // Prints: name, age and gender
}

Try with example


Setting Object's Properties

You can set the new properties or update the existing property by using the dot(.) or square bracket ([]) notation, as demonstrated in the example below:

var person = {
    name: "Peter",
    age: 28,
    gender: "Male"
};

// Setting a new property
person.country = "United States";
document.write(person.country); // Prints: United States

person["email"] = "[email protected]";
document.write(person.email); // Prints: [email protected]

// Updating existing property
person.age = 24;
document.write(person.age); // Prints: 24

person["name"] = "Justin Drake";
document.write(person.name); // Prints: Justin Drake

Try with example


Deleting Object's Properties

The property from an object can be deleted with the delete operator. It is the only way to remove a property from an object. However, setting the property to null or undefined only changes the value of the property, and does not remove the property from the object. 

var person = {
    name: "Justin",
    age: 26,
    gender: "Male",
    displayName: function() {
        alert(this.name);
    }
};

// Deleting property
delete person.age;
alert(person.age); // Outputs: undefined

Try with example

Note:  The delete operator does not affect variables or declared functions, it only removes an object property or array element. Usually, you avoid the use of the delete operator for deleting an array element, as it doesn't change the array's length, rather, it leaves a hole in the array.

 

Calling Object's Methods

An object's method is accessed the same way as you would access properties by making use of the square bracket notation or the dot notation. It is shown below.

var person = {
    name: "Peter",
    age: 28,
    gender: "Male",
    displayName: function() {
        alert(this.name);
    }
};

person.displayName(); // Outputs: Peter
person["displayName"](); // Outputs: Peter

Try with example

 

Manipulating by Value vs. Reference

JavaScript objects are reference types which means when you make copies of them, you end up copying the references to that object. But, original values like strings and numbers are assigned or copied as a whole value. The example below will help to better understand all this:

var message = "Hello World!";

var greet = message; // Assign message variable to a new variable
greet = "Hi, there!";

document.write(message);  // Prints: Hello World!
document.write(greet);  // Prints: Hi, there!

From the example above, we have made a copy of a variable message, while changing the value of that copy (i.e variable greet). The two variables remain distinct and separate, however, if we do the same thing with an object, we will get a different return. This is shown in the example here:

var person = {
    name: "Peter",
    age: 28,
    gender: "Male"
};

var user = person; // Assign person variable to a new variable
user.name = "Harry";

document.write(person.name);  // Prints: Harry
document.write(user.name);  // Prints: Harry

You can see, that any changes made to the variable user also change the person variable. This is experienced because both variables reference the same object. Therefore, you can understand that copying the object does not clone it, but copies the reference to that object.

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.