Family Magazine

What Are Objects in Javascript? [2023]

By Geoff Griffiths @mmatraining1980

Notes taken from the Udemy Course – the Complete JavaScript Course which you can enroll on here.

I’ve also robbed some screenshots from other sites, but linked to them in the “source”.

  • An object is a collection of properties
  • A property is an association between a name (key) and a value
  • A property’s value can be a function (but then it’s called a “method” for some reason)
What are objects in Javascript? [2023]

Source

Objects provide a way to group values together in an organised fashion.

Objects can store lots of different types of data.

Objects can contain variables, functions or both.Variables found in objects are properties, while functions are methods.

What are objects in Javascript? [2023]

In objects we define key-value pairs. The key is also called the “property name”.

Objects are normally declared within culry braces:

What are objects in Javascript? [2023]

firstName is a “key” and the “value” is “Jonas”.

The name and the value, create a “key value pair”.

There are many ways of creating objects in JavaScript.

Using curly braces is called the “object literal syntax” because you’re writing down the literal object.

The order you write down objects doesn’t matter, unlike in arrays.

How do we get data from an object?

Dot Notation

Screenshot source

The first way to access data in an object is to use “dot notation”:

What are objects in Javascript? [2023]

Dot notation is the most popular method to access the properties of an object.

let obj = {
  boxer: 'jab',
  muayThai: 'kick'
};
let strike = obj.boxer;
console.log(strike);
// jab

The dot notation in the example above is – let strike = obj.boxer;

Specify the name of the object, then add a dot, followed by the property name.

The syntax is objectName.propertyName;

What are objects in Javascript? [2023]

Source

Bracket Notation

let obj = {
  boxer: 'jab',
  muaythai: 'kick'
};
let strike = obj['boxer'];
console.log(strike);
// jab
What are objects in Javascript? [2023]

You can read a much better article about dot and bracket notation – here –> codeburst.io or here —> plainenglish.io

What are objects in Javascript? [2023]

How do you create objects?

It is a common practice to declare objects with the const keyword.

What are objects in Javascript? [2023]
What are objects in Javascript? [2023]

There are two methods by which you can create an object: an object literal and the object constructor. 

What are objects in Javascript? [2023]
What are objects in Javascript? [2023]

Source

let’s create an object named myCup and give it properties named color, volume, and weight as follows:

let myCup = new Object();
myCup.color = "transparent";
myCup.volume = 1;
myCup.weight = 0.5;

We can write the same object in a shorter notation. Comma-delimited list of  pairs of property names and associated values, enclosed in curly braces:

let myCup = {
 color: "transparent",
 volume: 1,
 weight: 0.5
}


Above, we declare a variable in the same way with: let myCup equals and then curly brace.

source

If you are making multiple objects, it’s best to use the object constructor.

You can use a constructor to create a new object by calling the constructor with the new keyword. The new keyword will create an instance of an object and bind the this keyword to the new object.

The this keyword is a reference to the object itself.

function Fighter(name, age, nationality) { 
    this.name = name; 
    this.age = age; 
    this.nationality = nationality; 
    this.bio = function () { 
        console.log(`My name is ${this.name}. I'm ${this.age} years old. I'm from ${this.nationality}`) 
    } 
};

const oladele = new Profile("Izzy", 29, "Nigeria" );
console.log(oladele.bio()); //My name is Izzy. I'm 29 years old. I'm from Nigeria

More info about constructors at Freecodecamp.org

Here’s another example, using the this keyword from w3schools

<script>
// Constructor function for Person objects
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

// Create a Person object
const myFather = new Person("John", "Doe", 50, "blue");

// Display age
document.getElementById("demo").innerHTML =
"My father is " + myFather.age + "."; 
</script>

The above code gives the output “my father is 50”. (which is printed to the paragraph with the id of “demo”)

Adding a method to an object

We can add a method simply by adding another property that is a function. This function will be able to read the values of the object and work with them.

We will add an example that will print out the color of the table.

myTable.whatIsMyColor = function() {
 console.log("My color is: " + this.color);
};
What are objects in Javascript? [2023]

source

What are objects in Javascript? [2023]
What are objects in Javascript? [2023]

source

Adding a new property to an object

In JavaScript you can add a property to an object after it has been created.

The following statement adds the age property to the fighter object and assigns 22 to it:

fighter.age = 22;






Deleting a property of an object

Simply use the delete operator

delete fighter.age;

Checking if a property exists

To check if a property exists in an object, you use the in operator:

propertyName in objectName

The in operator returns true if the propertyName exists in the objectName.

The following example creates an employee object and uses the in operator to check if the ssn and employeeId properties exist in the object:

let employee = {
    firstName: 'Peter',
    lastName: 'Doe',
    employeeId: 1
};

console.log('ssn' in employee);
console.log('employeeId' in employee);Code language: JavaScript (javascript)

Output:

false
true

Source


Back to Featured Articles on Logo Paperblog