---
title: Use Lazy Values to Speed Up Your JS Apps
description: Learn how to use the Object.defineProperty API to create lazy values and speed up the time it takes for your application to load.
image: https://www.bitovi.com/hubfs/Banner_Images/lazy-cats.jpg
---

- ![AI implementation](https://www.bitovi.com/hubfs/AIConsultingIcon.svg)
  
  [AI implementation](https://www.bitovi.com/services/ai-consulting)
- ![Systems engineering](https://www.bitovi.com/hubfs/icon%20-%20backend.svg)
  
  [Systems engineering](https://www.bitovi.com/services/systems-engineering-consulting)
- ![Project Management](https://www.bitovi.com/hubfs/icon%20-%20PM.svg)
  
  [Project Management](https://www.bitovi.com/services/agile-project-management-consulting)
- ![Product Design](https://www.bitovi.com/hubfs/icon%20-%20design.svg)
  
  [Product Design](https://www.bitovi.com/services/product-design-consulting)
- ![Frontend development](https://www.bitovi.com/hubfs/icon%20-%20frontend.svg)
  
  [Frontend development](https://www.bitovi.com/services/frontend-development-consulting)
- [View more
  
  →
  
  ](https://www.bitovi.com/digital-consulting-services)

We're Experts in...

- [JavaScript](https://www.bitovi.com/services/frontend/javascript-consulting)
- [AI training](https://www.bitovi.com/ai-training-for-software-engineers)
- [Angular](https://www.bitovi.com/services/frontend/angular-consulting)
- [Design systems](https://www.bitovi.com/services/axure-figma-migration)
- [React](https://www.bitovi.com/services/frontend/react-consulting)
- [Temporal](https://www.bitovi.com/services/backend/temporal-consulting)
- [React Native](https://www.bitovi.com/services/frontend/react-consulting/react-native)
- [Node.js](https://www.bitovi.com/services/backend/nodejs-consulting)

Showcase

![Yum! Brands](https://www.bitovi.com/hubfs/yum-showcase-link-1.png)

[View case study](https://www.bitovi.com/en/bitovi-yum-case-study)

More Projects

- [![Levi's](https://www.bitovi.com/hubfs/levis.svg)](https://www.bitovi.com/web-application-consulting-work/levis-ecommerce-responsive-redesign)
- [![Christie's International Real Estate](https://www.bitovi.com/hubfs/christies.svg)](https://design.bitovi.com/christies)
- [![BAFS](https://www.bitovi.com/hubfs/bafs.svg)](https://www.bitovi.com/ux-design-consulting/ux-case-studies/bafs-ppp)
- [View more
  
  →
  
  ](https://www.bitovi.com/our-software-consulting-work)

Open Source Tools

We build powerful tools and open source them to support the community.

[See what we've built →](https://www.bitovi.com/open-source)

- [![Blog](https://www.bitovi.com/hubfs/icon%20-%20blog.svg)
  
  BlogWe post about delivering products and solving problems.
  
  ](https://www.bitovi.com/blog)
- [![Partnerships](https://www.bitovi.com/hubfs/Handshake-1.svg)
  
  PartnershipsLearn about Bitovi's technology partners
  
  ](https://www.bitovi.com/partnerships)
- [![Academy](https://www.bitovi.com/hubfs/icon%20-%20academy%20(4).svg)
  
  AcademyFree courses to build delivery skills
  
  ](https://www.bitovi.com/academy)
- [![Open source tools](https://www.bitovi.com/hubfs/icon%20-%20open%20source.svg)
  
  Open source toolsUse or contribute to our community
  
  ](https://www.bitovi.com/open-source)

Let's Connect

- [![Discord](https://www.bitovi.com/hubfs/DiscordLogo.svg)
  
  Discord
  
  ](https://discord.gg/J7ejFsZnJ4)
- [![LinkedIn](https://www.bitovi.com/hubfs/LinkedinLogo.svg)
  
  LinkedIn
  
  ](https://www.linkedin.com/company/bitovi/)
- [![GitHub](https://www.bitovi.com/hubfs/GithubLogo.svg)
  
  GitHub
  
  ](https://github.com/bitovi/)

![Eggbot](https://www.bitovi.com/hubfs/build_assets/bitovi-limbo-cms-react/338/js_client_assets/assets/eggbot-LTGhdSGL.png)

Name *

Work Email *

Phone

What's your project?

Send

### Contact Us

(312) 620-0386contact@bitovi.com

 October 10, 2017

# Use Lazy Values to Speed Up Your JS Apps

 Learn how to use the Object.defineProperty API to create lazy values and speed up the time it takes for your application to load.

![Kevin Phillips](https://app.hubspot.com/settings/avatar/d2b9499fdabb775938188c33d09da7e8)

 Kevin Phillips

 Director of Backend Development

Share:

[![Twitter](https://www.bitovi.com/hubfs/limbo-generated/_astro/twitter-white.os3xLc3C_Z2nW4or.svg) ](https://twitter.com/intent/tweet?text=) [![Reddit](https://www.bitovi.com/hubfs/limbo-generated/imgs/icons/reddit.png) ](http://reddit.com/submit?url=)

Defining properties with "lazy values" is a technique you can use to improve performance in Object-Oriented JavaScript. It is especially beneficial because it can improve application load time, which can greatly impact important metrics like bounce rate and revenue.

In this article, we’ll answer:

- What is a Lazy Value?
- How do Lazy Values work?
- Should you use Lazy Values?

## What is a Lazy Value?

Normally when a property is created on an object, the expression that defines its value is evaluated *eagerly*. Eager evaluation means that the `getUniqueId` function in the following example is called immediately to compute the value for `id` whenever `MyObj` is called:

```
function getUniqueId() {
    // some magic to create an ID
}

function MyObj() {
    this.id = getUniqueId();
}
var obj1 = new MyObj();
console.log(obj1); // -> { id: 1 }
```

The `getUniqueId` function is called even if the `id` property is never used in the rest of the code. Lazy Values avoid this evaluation. Lazy Values are not computed until the first time the property is read:

```
var obj2 = new MyObjWithLazyId();
console.log(obj2); // -> { }
console.log(obj2.id); // -> 2
console.log(obj2); // -> { id: 2 }
```

## How do Lazy Values work?

The key to setting up Lazy Values is [Object.defineProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). This API lets you define properties and gives you lots of control over how they behave.

To define a Lazy Value, first we define the property as a [getter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Custom_Setters_and_Getters):

```
Object.defineProperty(MyObjWithLazyId.prototype, 'id', {
    get: function() {
        return getUniqueId()
    }
});
```

> Notice how we're adding this to the `prototype` of our `MyObjWithLazyId` constructor. This allows us to define this property once and have it used by any instance of `MyObjWithLazyId`.

This gets us part of the way there, but with just this, the `id` property would change every time it is read:

```
var obj3 = new MyObjWithLazyId();
console.log(obj3.id); // -> 2
console.log(obj3.id); // -> 3
console.log(obj3.id); // -> 5
console.log(obj3.id); // -> 8 
```

To make this work correctly, we first define the property using a getter, but when the getter is called, we use `Object.defineProperty` again to redefine the property as a value:

```
Object.defineProperty(MyObjWithLazyId.prototype, 'id', {
    get: function() {
        var id = getUniqueId();
    	
        Object.defineProperty(this, 'id', {
            value: id
        });
 
        return id;
    }
}); 
```

Redefining the property as a value means that the next time it is read, the value will be returned without any function needing to be called.

## Should you use Lazy Values?

The benefit of using Lazy Values is that they don't have to be computed during the initialization of your app. As you can see from this [benchmark](https://jsbench.github.io/#3da95139f6e8599bd44386e958220621), the performance of  Lazy Values (the orange bar below) is very close to the performance of constructing a completely empty object, which is shown in the blue bar (larger is better):

![](https://lh6.googleusercontent.com/ivc_D5KWaFAUCURLN19lZeO4eCEzZePrDRZuQSIJYbxTcZfoOUoxOeoynW8G50tlHCYIPmPDjT7iJLPeHwPVVZ6qe5UD5k9K0D-brg3_GY3sUZeo4TLCtdq5KD0ph7EdqXAj1geu)

If you're building a module that will only be used in a few places in your application, the benefits of using this technique are probably outweighed by the complexity you're adding for yourself the next time you read this code. Make sure to performance test in your app to see if the benefits are worth any decrease in readability.

  

[![Learn Javascript with Bitovi. We offer advanced training at an affordable price.](https://no-cache.hubspot.com/cta/default/2171535/070d202f-dbe2-450f-8a16-cb0694260d3c.png)](https://cta-redirect.hubspot.com/cta/redirect/2171535/070d202f-dbe2-450f-8a16-cb0694260d3c)

 If the code you're writing will be used many times throughout your application or you are building a [world-class JavaScript library](https://canjs.com), it is likely that your users will benefit from the performance improvement Lazy Values provide.

 

If you want to use this technique, we just published [can-define-lazy-value](https://canjs.com/doc/can-define-lazy-value.html) to make it very easy to get started. You can install it from [npm](https://www.npmjs.com/package/can-define-lazy-value) and take a look at its [25 lines of code](https://github.com/canjs/can-define-lazy-value/blob/4c8529d566f33eb6566bbb9da93e003192545e85/dist/cjs/define-lazy-value.js) to see exactly how it works.

[![Tag for development](https://www.bitovi.com/hubfs/limbo/icons/tag.svg) development ](https://www.bitovi.com/blog/topic/development)

 Previous Post

![donejs-banner.jpg](https://www.bitovi.com/hs-fs/hubfs/donejs-banner.jpg?height=117&name=donejs-banner.jpg) [ September 2017 DoneJS Community Update ](https://www.bitovi.com/blog/september-2017-donejs-community-update)

  

 Next Post

![](https://www.bitovi.com/hs-fs/hubfs/sketching/battleshipgame.jpg?height=117&name=battleshipgame.jpg) [ Finding Ideas Through Sketching ](https://www.bitovi.com/blog/finding-ideas-through-sketching)

```json
{
  "@context" : "http://schema.org",
  "@type" : "Organization",
  "address" : {
    "@type" : "PostalAddress",
    "addressCountry" : "United States",
    "addressLocality" : "Libertyville",
    "addressRegion" : "IL",
    "postalCode" : "60048",
    "streetAddress" : "1134 Pine Tree Lane "
  },
  "alternateName" : "Bitovi",
  "areaServed" : {
    "@type" : "GeoCircle",
    "geoMidpoint" : {
      "@type" : "GeoCoordinates",
      "latitude" : "41.8781",
      "longitude" : "87.6298"
    },
    "geoRadius" : "5000 km"
  },
  "description" : "Bitovi is a UX, UI design and front-end JavaScript development consulting company",
  "email" : "contact@bitovi.com",
  "image" : "https://www.bitovi.com/hubfs/bitovi-logo-x2.png",
  "logo" : "https://www.bitovi.com/hubfs/bitovi-logo-23-1.svg",
  "mainEntityOfPage" : {
    "@id" : "https://www.bitovi.com/blog/lazy-values-to-speed-up-your-js-app",
    "@type" : "WebPage",
    "description" : "Learn how to use the Object.defineProperty API to create lazy values and speed up the time it takes for your application to load."
  },
  "naics" : "541511",
  "name" : "Bitovi Web App Consulting",
  "sameAs" : [ "https://www.facebook.com/BitoviLLC/", "https://twitter.com/bitovi", "https://www.linkedin.com/company/bitovi" ],
  "telephone" : "312-620-0386",
  "url" : "http://bitovi.com"
}
```

```json
{
  "@context" : "http://schema.org",
  "@type" : "BlogPosting",
  "author" : {
    "@type" : "Person",
    "name" : "Kevin Phillips"
  },
  "dateModified" : "October 10, 2017, 7:39:34 PM",
  "datePublished" : "2017-10-10 19:24:33",
  "description" : "Learn how to use the Object.defineProperty API to create lazy values and speed up the time it takes for your application to load.",
  "headline" : "Use Lazy Values to Speed Up Your JS Apps",
  "image" : {
    "@type" : "ImageObject",
    "url" : "https://www.bitovi.com/hubfs/Banner_Images/lazy-cats.jpg"
  },
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "url" : "https://www.bitovi.com/hubfs/bitovi-logo-23-1.svg"
    },
    "name" : "Bitovi"
  }
}
```