DEV Community

Terry Threatt
Terry Threatt

Posted on

All About Javascript Objects

What are objects

objects

Objects are things we can perceive with our senses like an iPhone, Apple Watch, or AirPods.

In programming, objects are a representation of these very real things.

// this car variable is an object
car = πŸš—
Enter fullscreen mode Exit fullscreen mode

In Javascript, an object contains a collection of grouped behavior and characteristics called properties & methods that identifies the object.

The Javascript language is made up of mostly objects with the exception of some primitive types(Numbers, Strings, Booleans, Undefined, Null, BigInts, and Symbols).

Object Oriented Programming

Objected-Oriented Programming (OOP for short) is a programming paradigm of using classes of objects to implement large and scaling programs. This includes utilizing an object that interfaces with other objects to execute a task.

// Two objects working together 
laptop = πŸ’» 
money = πŸ’³ 

// We can build a program to order burritos with objects!!!
burrito 🌯 = πŸ’» + πŸ’³  
Enter fullscreen mode Exit fullscreen mode

How to work with objects in Javascript

// Two ways of creating javascript objects

// 1. Object Literal
const person = {
    name: "Jane Javascript", 
    age: 26
}

console.log(person.name) // output: Jane Javascript 

// 2. Object Constructor: completes a template for a person
function Person(name, age) {
  this.name = name // points to current instance of object
  this.age = age
}

// Instantiates a new person object from the person template
const jack = new Person("Jack Javascript", 26)

console.log(jack.name) // output: Jack Javascript

// Jack does indeed derive from the Person object
console.log(jack instanceof Person) // output: true

// Adding a new property
jack.job = "developer" 

console.log(jack.job) // output: developer 

// Adding a method
function Car(model, year) {
  this.model = model 
  this.year = year
} 

const myCar = new Car("tesla", 2020) 

myCar.drive = function () {
  console.log("Vroooom")
} 

myCar.drive() // output: Vroooom

// Delete a property
delete myCar.year

console.log(myCar.year) // output: ERROR undefined

// A Javascript Built-In Method
// toUpperCase: uppercases all strings 
console.log(myCar.model.toUpperCase()) // output: TESLA

Enter fullscreen mode Exit fullscreen mode

Let's chat about objects

This was an exploration of objects in Javascript. If you enjoyed this post feel free to leave a comment about your thoughts and experiences working with objects in Javascript.

Happy Coding,
Terry Threatt

Latest comments (0)