Image for post
Image for post

JavaScript: Objects and Functions

The two JavaScript types that are not primitive values.

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.

  • 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 name = {first: 'Paisley'}  
name // {first: 'Paisley'}
name = {first: 'Eloise'}
name // {first: 'Eloise'}
let name = {first: 'Paisley'} 
name.first // 'Paisley'
name['first'] // 'Paisley'
let name = {first: 'Paisley'} 
let paisley = {first: 'Paisley'}
name === paisley; // false

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.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store