DEV Community

coses23298
coses23298

Posted on

Objects in JavaScript

Intro

Objects are a collection of properties

let james = {
name: 'james';
age: 30;
email: 'james@jamesmail.com';
location: 'Britan';
}
Enter fullscreen mode Exit fullscreen mode

so as you can see james here has multiple properties and that makes him an object.
we can also put strings equal things within objects

let james = {
name: 'james';
age: 30;
email: 'james@jamesmail.com';
location: 'Britan';
"Cup o'": 'joe';
}
Enter fullscreen mode Exit fullscreen mode

Accessing values

to access all the values is not that hard its just

console.log(james)
Enter fullscreen mode Exit fullscreen mode

and all of the values will show up
but lets say you only want to access one of the values and not all of them. well we use dot notaion for that

james.name
james.age
Enter fullscreen mode Exit fullscreen mode

this will show just the age and just the name

Adding Properties to an object

By using dot notation we can add variables

let Guitars = {
  Strings: 6;
  in stock: 70;
}

guitars.type = "acoustic";
Enter fullscreen mode Exit fullscreen mode

Bracket notation will also work
bracket notation is just dot notation but with different syntax

let Guitars = {
  Strings: 6;
  in stock: 70;
}

guitar["type"] = "acoustic";
Enter fullscreen mode Exit fullscreen mode

in the same way you can update certain properties and change them with dot and bracket notation

let Guitars = {
  Strings: 6;
  in stock: 70;
}

guitars.strings= 7;
Enter fullscreen mode Exit fullscreen mode

removing properties

using the keyword "Delete" you can delete certain properties

Property check

Checking for properties within objects is pretty easy with the command

prop in objectName
Enter fullscreen mode Exit fullscreen mode

within this you can check if a object has a certain value
so lets check in james

age in james
Enter fullscreen mode Exit fullscreen mode

this will show up as true because the variable age shows up in the object james

For properties in const we have a strange result
putting

const Guitars = {
  Strings: 6;
  in stock: 70;
}

guitars.strings= 7;
Enter fullscreen mode Exit fullscreen mode

this will cause an error, trying to change one of the variables but

let Guitars = {
  Strings: 6;
  in stock: 70;
}

guitars.type= "acoustic";
Enter fullscreen mode Exit fullscreen mode

we can add properties to it with no problem

Top comments (0)