Sign in
Log inSign up
Understanding The Basics Of Objects In JavaScript

Understanding The Basics Of Objects In JavaScript

Maureen Anyanwu's photo
Maureen Anyanwu
·Feb 28, 2021·

3 min read

An object is a collection of properties. It is also known as hashtable.This property has a key value pair. The values can be any of the data types in JavaScript like string, number, Boolean etc.

For example, We can have a phone with several properties like phone name, phone version, phone battery capacity and so on These properties are what define the phone object.

Phone = {
       “name” : “tecno”,
       “version”:“android 10”,
        “battery”:“3000mAh”
}

This is known as JSON meaning JavaScript Object Notation.

There are several ways used to declare objects in JavaScript but two will be treated here;

1. Using the “new “ keyword

This helps to create a new instance of a JavaScript object

const ObjectName= new Object()
e.g
const Phone= new Object();
Phone.name= “tecno”;

2. The key value pair method

Key represents the name of property while value is the value of that property.

const ObjectName = { 
          “key1” : “value1”,
          “key2” : “value2”
};

In order to access an object’s property, we use the ObjectName.Key to access the value attached to the specific key

console.log(Phone.name);
//logs “tecno” to the console

Or

ObjectName[“Key”]

console.log(Phone[“name”]);
//logs “tecno” to the console

Methods are actions that can be performed on an object. They are simply functions stored as properties of object. Examples of these methods include;

1. Object.keys()

This returns an array containing the keys of an object.

const Phone = {
       “name” : “tecno”,
       “version”:“android 10”,
        “battery”:3000mAh”
};

console.log(Object.keys(Phone));
//logs [“name”, “version”, “battery”]

2. Object.values()

This returns an array containing the values of an object.
const Phone = {
       “name” : “tecno”,
       “version”:“android 10”,
        “battery“:”3000mAh”
};

console.log(Object.values(Phone));
//logs [“tecno”, “android 10”, “3000mAh”]

To find out more about these object methods, visit (developer.mozilla.org/en-US/docs/Web/JavaS…)

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct