Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 39 ยท Getting Started

Modern JavaScript You Need for Ember

Review the JavaScript features Ember code uses every day - modules, classes, class fields, arrow functions, destructuring, async/await and decorators - with runnable examples.

Modern Ember is mostly ordinary JavaScript. If you are comfortable with a handful of features, Ember code will read naturally. This lesson reviews exactly those features and shows where each one appears in an Ember app. If you need a full course first, the JavaScript tutorial covers everything in depth.

ES modules: import and export

Every file in an Ember app is a module. You bring things in with import and expose them with export. Ember files usually have one default export: the route class, the component class, the service class.

JavaScript
// app/utils/format-price.js
export function formatPrice(cents) {
  return `$${(cents / 100).toFixed(2)}`;
}

// app/routes/cart.js
import Route from '@ember/routing/route';
import { formatPrice } from '../utils/format-price';

export default class CartRoute extends Route {}

Named exports are imported with braces; default exports are imported without. Framework features come from packages starting with @ember/, @glimmer/ or @ember-data/. Your own files can be imported by relative path or by the app name, for example my-app/utils/format-price.

Classes and this

Routes, components, services and models are classes. A class groups data (fields) and behavior (methods). extends inherits from a framework base class such as Component.

JavaScript
class Greeter {
  greeting = 'Hello';

  greet(name) {
    return `${this.greeting}, ${name}!`;
  }
}

Inside a method, this is the object the method is called on. This is where beginners trip, as the next section shows.

JS Classes, fields and this

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In Ember, you often pass a method to a template as an event handler. That is why you will see either an arrow-function field or the @action decorator, which binds the method for you.

Destructuring, spread and optional chaining

These three features tidy up code that handles objects, and you will see them in routes and components constantly.

JS Destructuring, spread, ?. and ??

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Template strings, arrow functions and array methods

Use `Hello ${name}` instead of string concatenation. Arrow functions (x) => x * 2 are short and do not have their own this. Array methods map, filter, find, some and reduce replace many loops, and Ember templates often work on arrays you prepare this way:

JavaScript
const posts = [
  { id: 1, title: 'Intro', published: true },
  { id: 2, title: 'Draft', published: false },
];
const visible = posts.filter((post) => post.published).map((post) => post.title);

Async code: promises and async/await

Loading data is asynchronous. A promise stands for a value that will arrive later. async functions let you write the waiting with await, and try/catch handles failures. Ember's route model() hook may return a promise; the router waits for it before rendering the page.

JS async/await with a fake server

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Decorators

A decorator is a function applied to a class member with an @ sign. Ember uses a few:

Decorator From What it does
@tracked @glimmer/tracking Marks a field so changing it updates the template.
@action @ember/object Binds a method to its instance so it can be a handler.
@service @ember/service Injects a service.
@attr, @belongsTo, @hasMany @ember-data/model Describe model fields and relationships.
JavaScript
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export default class Toggle extends Component {
  @tracked isOpen = false;

  @action
  toggle() {
    this.isOpen = !this.isOpen;
  }
}

Decorators are not yet available in browsers natively, so Ember's build tool compiles them. That is why the following block is a stand-in: it imitates what @tracked does by hand, wrapping a field with a getter and a setter that notify a listener. In real Ember the tracking system does this bookkeeping for you and re-renders only what changed.

JS What @tracked does, by hand

Press Run (or Ctrl + Enter) to see the console output here.

No output.

TypeScript note

You can write Ember in TypeScript, using .ts and .gts files. Everything in this track works the same way; types simply add checks. Start in plain JavaScript and add TypeScript later if your team wants it. See the TypeScript tutorial when you are ready.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the problem with passing counter.incrementMethod as a callback without binding?

    A regular method gets its this from the call. As a detached callback it loses the instance. Arrow fields, bind and Ember's @action solve this.
  2. 2. What does user.profile?.name ?? 'guest' return when profile is null?

    Optional chaining stops at null and yields undefined; the nullish coalescing operator then provides the fallback.
  3. 3. What does a route's async model() hook return to the router?

    The router resolves the promise first, then renders the template with the result, or shows an error state if it rejects.
  4. 4. Which decorator makes a field update the template when it changes?

    @tracked from @glimmer/tracking marks a field as reactive state. @action binds methods, @service injects services, @attr describes model fields.

Summary

  • Ember files are ES modules, usually with one default-exported class.
  • Routes, components, services and models are classes; beware of losing this when passing methods around.
  • Destructuring, spread, ?. and ?? keep data-handling code short.
  • async/await and promises power data loading in route hooks.
  • Decorators (@tracked, @action, @service, @attr) are compiled by Ember's build tool.

Next: Core Concepts of Ember Octane