Skip to main content

Objects In JS

Objects in Javascript

Objects in Javascript

Codepen with examples for you to practice with below!

Objects in Javascript

Codepen with examples for you to practice with below!

The Object Type

The object is a data structure that stores other data, similar to how an array stores elements.

Javascript simple types:

  • numbers (has object-like methods but they are immutable)
  • strings (has object-like methods but they are immutable)
  • booleans (has object-like methods but they are immutable)
  • null
  • undefined

All other values are objects including arrays and functions.

Objects are class free, can contain other objects and can inherit properties from their prototypes (which can reduce object initialisation time and memory consumption).

In other programming languages, objects are referred to as, “dictionaries”, “maps”, or “associative arrays”.

  • Objects are indexed with keys instead of numbers.
  • Order is not guaranteed within an Object.
  • Objects are defined by using curly braces {}
  • You can think of Objects as tables.
Fun Fact: Objects are affectionately known as POJO’s (Plain Old Javascript Objects)

Setting Keys and Values

  • If we try to access a key that has not yet been assigned within an object we will output undefined.
  • The preferred method for checking to see if an object exists at a key is to use the operator.

Using Variables as Keys

Using Different Notations

Bracket Notation vs Dot Notation

Easier To Read

You can use variables as keys!

Easier To Write b/c do not need Quotations.

Okay to use variables and Strings that start with numbers.

Cannot access with Variables

Keys cannot contain numbers as their first character

  • When accessing object keys: Bracket notation needs to refer to that key in quotations, dot notation doesn’t.
  • When accessing object keys via a variable: Bracket notation can refer to that key w/o use of quotations, dot notation can’t do this at all.

Putting it All Together

You can put an object together in a single statement.

Operator Precedence Revisited

Iterating Through Objects

Because objects store unordered key-value pairs, we do not rely on indices to access values; instead we rely on our keys.

Methods vs Functions

A is a function that belongs to an object. Every method is a function, but not every function is a method.

Useful Object Methods

  • Object.keys() : A method that allows us to iterate through keys, it accepts an obj as the argument and returns an array of the keys.
  • Object.values() : Method that accepts an object as the argument and returns an array of the values.

Iterating through an Object’s keys & values

References vs Primitives

Primitives vs Objects

So far we have learned about 6 different data types:

  • Primitive : Boolean, Null, Undefined, Number, String.
  • Reference : Object (Arrays are a type of object)
  • Remember that primitive types are immutable!

Immutability

  • When we reassign primitives we simply have our variable point elsewhere in memory.
  • In a nutshell, immutability cannot change values in memory, but only reassign where our variables are pointing to.

Mutability

Rest and Spread

Using the Spread Operator and Rest Parameter Syntax
Accepting Arguments

  • Just keep in mind that function will still run even if it is not passed any arguments.
  • Parameters will take just as many arguments they need even if more than enough are offered.
  • We will encounter an error if there are not enough parameters ( > 0).

Utilizing Rest Parameters

  • Rest Parameter Syntax : Allows us to capture all of a function's incoming arguments into an array.
  • Only the last parameter can be a rest parameter.

Utilizing Spread Syntax

  • Takes a data type (i.e. array, obj) and spreads the values of that type where elements are expected.
  • Takes iterable data and spreads the elements of that type where arguments are expected.

Destructuring

Swapping Variables using destructuring

Destructuring objects into variables

Destructuring and the Rest Pattern

Destructuring Parameters

We can also destructure incoming parameters of a function.
 This is very useful when we’re passing objects around to different functions.


Object Literals

  • An object literal is zero or more comma-separated name/value pairs surrounded by curly braces {}
let empty_object = {};
let today = {
day: "Wednesday",
month: "April",
year: 2014,
weather: { //objects can contain nested objects like this one
morning: "sunny",
afternoon: "cloudy"
}
}

Retrieval

  • Can be done with either dot notation today.weather.morning or with square brackets today['month']
  • Or operand (||) can be used to fill in default values for nonexistent data to prevent and undefined error: var weath = today.weather.evening || "unknown"

Update

  • Assigning a property value to an object overwrites any existing property values with that property name

Reference

  • Objects refer to each other, they don’t hold duplicate copies of data

Prototype

  • Every object has a prototype object from which it inherits properties
  • Object.prototype comes standard with Javascript and is almost like a ‘root parent’
  • The Object.create method is now available in ES5 (but the method is in the book if required for older versions)
  • If an object does not have a property you ask it for, it will keep looking up the prototype chain until it finds it
  • If the property does note exist anywhere in the chain, it will return undefined
  • A new property is immediately visible to all of the objects below it in the chain once created

More details in Chapter 6

Reflection

  • Determining what properties an object has
  • Using typeof includes all properties in the prototype chain including functions
  • To avoid inherited properties, use hasOwnProperty(type); which returns true if that property exists only in that object itself (not the chain)
today.hasOwnProperty(‘number’) //will return true today.hasOwnProperty(‘constructor’) //will return false

Enumeration

  • Best way to enumerate all the properties you want is a for loop:
let i;
let properties = [ ‘day’, ‘month’, ‘year’ ];
for (i = 0; i < properties.length; i++) {
document.writeIn(properties[i] + ‘:’ + today[properties[i]]);
}
  • This ensures you get the properties you want (i.e. not up the prototype chain) and in the order you want, as opposed to a for in loop which achieves neither of these

Delete

  • Removes property from object, but also reveals property from further up the prototype chain if it exists
  • Format: delete today.month

Global Abatement

  • One way to mitigate the risks of global variables is to create a single global variable which then contains your whole application
let MYAPP = {}
MYAPP.today = {
day: "Wednesday",
month: "April",
year: 2014,
weather: { //objects can contain nested objects like this one
morning: "sunny",
afternoon: "cloudy"
}
}
//Making sure all other variables (like today) are contained within this one global variable (MYAPP) means none of them have global scope and therefore the risk of naming conflicts, etc in your application is reduced

Comments

Popular posts from this blog

Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms.

Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms. Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms. “JavaScript’s global scope is like a public toilet. You can’t avoid going in there, but try to limit your contact with surfaces when you… Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms. Photo by Florian Olivo on  Unsplash “ J avaScript’s global scope is like a public toilet. You can’t avoid going in there, but try to limit your contact with surfaces when you do.” ― Dmitry Baranowski Here’s another (much) more simple article I wrote on the subject: Closures In Javascript Answer A closure is a function defined...

links

links Absolutely Everything You Could Need To Know About How JavaScript TOC & Condensed Links **** **** **** **** **** 1 2 3 4 5 leonardomso/33-js-concepts *This repository was created with the intention of helping developers master their concepts in JavaScript. It is not a…*github.com Call stack - MDN Web Docs Glossary: Definitions of Web-related terms MDN *A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its…*developer.mozilla.org Understanding Javascript Function Executions — Call Stack, Event Loop , Tasks & more *Web developers or Front end engineers, as that’s what we like to be called, nowadays do everything right from acting as…*medium.com Understanding the JavaScript call stack *The JavaScript engine (which is found in a hosting environment like the browser), is a single-threaded interpreter…*medium.freecodecamp.org Javascript: What Is The Execution Context? ...

Bash Proficiency

Bash Proficiency In Under 15 Minutes Bash Proficiency In Under 15 Minutes Cheat sheet and in-depth explanations located below main article contents… The UNIX shell program interprets user commands, which are… Bash Proficiency In Under 15 Minutes Cheat sheet and in-depth explanations located below main article contents… The UNIX shell program interprets user commands, which are either directly entered by the user, or which can be read from a file called the shell script or shell program. Shell scripts are interpreted, not compiled. The shell reads commands from the script line per line and searches for those commands on the system while a compiler converts a program into machine readable form, an executable file. LIFE SAVING PROTIP: A nice thing to do is to add on the first line #!/bin/bash -x I will go deeper into the explanations behind some of these examples at the bottom of this article. Here’s some previous articles I’ve written for more advanced users. Bash Commands That Sa...