JavaScript: Objects and Functions

The two JavaScript types that are not primitive values.

aliciachao
2 min readJul 13, 2020

--

JavaScript is comprised of 9 fundamental types of values. Of the 9 types, 7 are primitive. My last article covered the importance of understanding primitive values here. The remaining 2 types are Objects and Functions, and I will go into detail about them here.

  • Objects ({}, []) used to group related data and code.
  • Functions (x => x * 2), used to refer to code.

Objects

When you think about objects, you typically think curly braces {} but arrays, dates, regular expressions and any other non-primitive values are objects as well. You can check using the typeof() operator.

typeof({}); // “object”
typeof([]); // “object”
typeof(new Date()); // “object”
typeof(/(water|soda)); // “object”
typeof(Math)); // "object"

Let’s take a look at a few examples to understand an objects traits.

Objects are mutable. Their values can be changed and reassigned.

let name = {first: 'Paisley'}  
name // {first: 'Paisley'}
name = {first: 'Eloise'}
name // {first: 'Eloise'}

[New] objects are created using the {} object literal (including arrays, dates, etc). Their properties can be accessed using dot . or bracket notation [].

let name = {first: 'Paisley'} 
name.first // 'Paisley'
name['first'] // 'Paisley'

Now let’s go deeper…

let name = {first: 'Paisley'} 
let paisley = {first: 'Paisley'}
name === paisley; // false

Why is the output false? The first variable name created a new object. The second variable paisley created another new object. These two variables are pointing to two completely independent objects and are therefore not equal to one another. Test it out in the console for yourself (Mac : cmd+option+j).

Functions

When run, a function creates a new function value. Technically, they are objects that have capabilities unique to them.

// Simple syntax
function() {}
// function given the name Hello
function Hello() {
return 'Hello'
}
// Written as an anonymous function
let hello = function() { return 'Hello'}

Takeaway

  • Objects ({}, []) create a new value for each object literal run.
  • Functions (x => x * 2), create a new value for each expression run.

--

--