Home | SkillForge Blog | How to create a JavaScript Object

How to create a JavaScript Object

JavaScript, Web Design

In JavaScript, there is a thing called an object.  It’s something that can contain a value that is equal to something else.  Those are called key/value pairs.  There’s a key that is equal to some value.  It’s a way that you can have a variable equal to many different items that can be used as functions, values, etc.  It gives the programmer a lot of flexibility on how they can get their job done.  The most simple way in JavaScript to create an object is like this:

var jsObj = {};

We just created an empty object there that could be filled in later.  Let’s continue with that and put some key/values in there:

var jsObj = {

firstName: “Dave”,

lastName: “Kidd

}

Here I created an object that has two keys: firstName and lastName.  Those keys have the values of Dave for firstName and Kidd for lastName.  To access those values I can use dot notation or a square bracket method.  Here is the dot notation method:

jsObj.firstName

jsObj.lastName

If alerted to the page, that would return Dave and then Kidd.  The other way you can access these key’s value is using the square bracket notation like so:

jsObj[“firstName”]

jsObjp[“lastName”]

That does the same thing as the dot notation, they are just two different ways to extract the values from the keys in objects.

Objects come from all over.  You can create them yourself as we did above, and there are a lot of built-in objects in JavaScript as well.  An example is the Math object which allows you to do things like generating a random number between 0 and 1 with Math.random().  Or the Date object that allows you to pull the time/day/month from the user’s computer.  Overall, objects are a very important aspect of any programming language.  If you’d like to learn more be sure to check out our JavaScript Training.  Have an amazing day!