---
title: Bitovi Academy - Functions
description: Learn how to annotate functions parameters and return values, use different parameter types, and bind `this`.
---

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

We're Experts in...

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

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?hsLang=en-us)

More Projects

- [![Levi's](https://www.bitovi.com/hubfs/levis.svg)](https://www.bitovi.com/web-application-consulting-work/levis-ecommerce-responsive-redesign?hsLang=en-us)
- [![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?hsLang=en-us)
- [View more
  
  →
  
  ](https://www.bitovi.com/our-software-consulting-work?hsLang=en-us)

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?hsLang=en-us)

- [![Blog](https://www.bitovi.com/hubfs/icon%20-%20blog.svg)
  
  BlogWe post about perfecting software delivery
  
  ](https://bitovi.com/blog)
- [![Partnerships](https://www.bitovi.com/hubfs/Handshake-1.svg)
  
  PartnershipsLearn about Bitovi's technology partners
  
  ](https://www.bitovi.com/partnerships?hsLang=en-us)
- [![Academy](https://www.bitovi.com/hubfs/limbo/icons/icon-academy.svg)
  
  AcademyFree courses to build delivery skills
  
  ](https://www.bitovi.com/academy/?hsLang=en-us)
- [![Open source tools](https://www.bitovi.com/hubfs/icon%20-%20open%20source.svg)
  
  Open source toolsUse our tools or contribute to our open source mission.
  
  ](https://www.bitovi.com/open-source?hsLang=en-us)

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

- [ Advanced JavaScript ](https://www.bitovi.com/academy/learn-advanced-javascript.html?hsLang=en-us)
- [ DOM and jQuery ](https://www.bitovi.com/academy/learn-dom-jquery.html?hsLang=en-us)
- [ Debug JavaScript ](https://www.bitovi.com/academy/learn-to-debug-javascript.html?hsLang=en-us)
- [ Learn TypeScript ](https://www.bitovi.com/academy/learn-typescript.html?hsLang=en-us) 
    - [ Why TypeScript ](https://www.bitovi.com/academy/learn-typescript/why-typescript.html?hsLang=en-us)
    - [ IDE Support ](https://www.bitovi.com/academy/learn-typescript/ide-support.html?hsLang=en-us)
    - [ Setting Up Your Environment ](https://www.bitovi.com/academy/learn-typescript/setting-up-your-environment.html?hsLang=en-us)
    - [ Modules ](https://www.bitovi.com/academy/learn-typescript/modules.html?hsLang=en-us)
    - [ Types ](https://www.bitovi.com/academy/learn-typescript/types.html?hsLang=en-us)
    - [ Functions ](https://www.bitovi.com/academy/learn-typescript/functions.html?hsLang=en-us)
    - [ Classes ](https://www.bitovi.com/academy/learn-typescript/classes.html?hsLang=en-us)
    - [ Interfaces ](https://www.bitovi.com/academy/learn-typescript/interfaces.html?hsLang=en-us)
    - [ Keyof and Typeof ](https://www.bitovi.com/academy/learn-typescript/keyof-typeof.html?hsLang=en-us)
    - [ Generics ](https://www.bitovi.com/academy/learn-typescript/generics.html?hsLang=en-us)
    - [ Utility Types ](https://www.bitovi.com/academy/learn-typescript/utility-types.html?hsLang=en-us)
- [ Learn React Native ](https://www.bitovi.com/academy/learn-react-native.html?hsLang=en-us)
- [ Learn Web Components ](https://www.bitovi.com/academy/learn-web-components.html?hsLang=en-us)
- [ Agile Program Management With Jira ](https://www.bitovi.com/academy/learn-agile-program-management-with-jira.html?hsLang=en-us)
- [ Learn RxJS ](https://www.bitovi.com/academy/learn-rxjs.html?hsLang=en-us)
- [ Giving a Training ](https://www.bitovi.com/academy/training.html?hsLang=en-us)
- [ Learn Technology Consulting ](https://www.bitovi.com/academy/learn-technology-consulting.html?hsLang=en-us)
- [ Learn React ](https://www.bitovi.com/academy/learn-react.html?hsLang=en-us)
- [ Learn NgRx ](https://www.bitovi.com/academy/learn-ngrx.html?hsLang=en-us)
- [ Learn Graphql ](https://www.bitovi.com/academy/learn-graphql.html?hsLang=en-us)
- [ Learn Docker ](https://www.bitovi.com/academy/learn-docker.html?hsLang=en-us)
- [ Learn CanJS ](https://www.bitovi.com/academy/learn-canjs.html?hsLang=en-us)
- [ Learn Angular ](https://www.bitovi.com/academy/learn-angular.html?hsLang=en-us)
- [ Advanced TypeScript ](https://www.bitovi.com/academy/advanced-typescript.html?hsLang=en-us)

[View More Courses](https://www.bitovi.com/academy/#courses) [ ]

# Functions `page`

Learn how to annotate functions parameters and return values, use different parameter types, and bind `this`.

## Overview

In this part, we will:

- Annotate functions parameters and return values.
- Use optional parameters & rest parameters.
- Update a function with TypeScript annotations.
- Understand `this` in TypeScript.

## Objective 1: Annotate functions

### Annotating function parameters

In TypeScript, we’re able to annotate function parameters to better guard our code.

In the following example, the `add` function is called with two parameters that are not numbers, so TypeScript’s compiler will throw an error when compiled:

```
function add(x: number, y: number) {
  return x + y;
}

add(1, "three");
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.ts(2345)

```

### Annotating function return values

We can also annotate what a function should return.

```
function returnNumber(): number {
  return "1";
}
// Error: Type 'string' is not assignable to type 'number'.ts(2322)

```

Of course, this works when fixed:

```
function returnNumber(): number {
  return 1;
}
// Works!

```

### Optional parameters

Sometimes when writing functions, we don’t need every parameter to be satisfied. TypeScript allows us to mark optional parameters (or properties) with a `?` so the compiler will not error if an optional param isn’t passed.

```
function buildDinosaur(name: string, breed: string, teeth?: number): void {
  if (teeth) {
    console.info(`${name} is a ${breed} and has ${teeth} teeth.`);
  } else {
    console.info(`${name} is a ${breed}.`);
  }
}

let newDino = buildDinosaur("Blue", "Velociraptor", 80);
// Works
let otherDino = buildDinosaur("Delta", "Velociraptor");
// Also works
let otherOtherDino = buildDinosaur("Charlie");
// Expected 2-3 arguments, but got 1.ts(2554)
// Error: An argument for 'breed' was not provided.

```

### Rest parameters

Rest parameters are a way to pass in an unknown number of arguments to a function. Rest params are signaled to the transpiler by passing an ellipsis (`...`) followed by the parameter name.

```
function buildDinosaur(breed: string, ...dna: string[]): void {
  console.info(`The ${breed} has dna from ${dna.join(", ")}`);
}

buildDinosaur(
  "Indominous Rex",
  "Velociraptor",
  "Tyrannosaurus rex",
  "Therizinosaurus",
  "cuttlefish",
);
// Logs "The Indominous Rex has dna from Velociraptor,
//      Tyrannosaurus rex, Therizinosaurus, cuttlefish"

```

### Setup 1

✏️ Create **src/functions/dnaCost.ts** and update it to be:

```
export function dnaCost(baseCost, sequence) {
    return baseCost + sequence.length;
}

let raptorCost = dnaCost(5000,"CGGCA");

console.log(raptorCost);
// Logs 5005

```

### Verify 1

✏️ Create **src/functions/dnaCost.test.ts** and update it to be:

```
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { dnaCost } from "./dnaCost";

describe("Functions: dnaCost", () => {
  it("can be called with two arguments", () => {
    assert.equal(dnaCost(2500, "abc"), 2503);
  });

  it("can be called with many arguments", () => {
    assert.equal(dnaCost(2500, "abc", "de", "f"), 2506);
  });
});

```

### Exercise 1

The `dnaCost` function in `dnaCost.ts` calculates the cost of synthesizing a DNA sequence to make a dinosaur. It calculates the cost by adding a `baseCost` plus the length of the DNA sequence.

Now scientists want to mix the DNA of multiple dinosaurs. Open the `dnaCost.ts` file and modify this function to:

1. Take an unknown amount of sequences.
2. Return the sum of `baseCost` and the length of each sequence.

**Have issues with your local setup?** You can use either [StackBlitz](https://stackblitz.com/fork/github/bitovi/academy/tree/main/exercises/typescript/07-functions/01-problem?file=src/functions/dnaCost.ts) or [CodeSandbox](https://codesandbox.io/p/devbox/github/bitovi/academy/tree/main/exercises/typescript/07-functions/01-problem?file=src/functions/dnaCost.ts) to do this exercise in an online code editor.

### Solution 1

If you’ve implemented the solution correctly, the tests will pass when you run `npm run test`!

Click to see the solution

✏️ Update `dnaCost.ts` to add each sequence to the base cost. This solution uses [Array.prototype.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce):

```
export function dnaCost(baseCost: number, ...sequences: string[]) {
  return sequences.reduce((sum, sequence) => {
    return sum + sequence.length;
  }, baseCost);
}

```

You’ll notice that specifying a return type is not necessary. This is because TypeScript can infer the return value from the arguments.

The following is another valid solution:

```
export function dnaCost(baseCost: number, ...sequences: string[]) {
  let sum = baseCost;
  sequences.forEach(sequence => {
    return sum += sequence.length;
  });
  return sum;
}
```

**Have issues with your local setup?** See the solution in [StackBlitz](https://stackblitz.com/fork/github/bitovi/academy/tree/main/exercises/typescript/07-functions/01-solution?file=src/functions/dnaCost.ts) or [CodeSandbox](https://codesandbox.io/p/devbox/github/bitovi/academy/tree/main/exercises/typescript/07-functions/01-solution?file=src/functions/dnaCost.ts).

## Objective 2: Use `this` in TypeScript

### Understanding `this`

The value of this within a function depends on how the function is called:

- Global context: If a function is called in the global scope, `this` refers to the global object (`window` in browsers, `global` in Node.js). However, in strict mode, `this` will be `undefined`.
- Object context: When a function is called as a method of an object, `this` refers to the object.
- Class context: In a class, `this` refers to the instance of the class.
- Event handlers: In DOM event handlers, `this` typically refers to the element that received the event, unless the function is an arrow function, which does not bind its own `this`.
- Arrow functions: Arrow functions do not bind their own `this`; they inherit `this` from the enclosing execution context.

The dynamic nature of this means that its value can change based on how and where a function is called. This can lead to issues, especially when functions that use this are passed around as callbacks.

For instance:

```
const dog = {
  name: "fido",
  bark: function () {
    console.info(this.name + "says woof");
  },
};
const address = { street: "2 State St" };

dog.bark.call(dog); // Logs "fido says woof";
dog.bark.call(address); // Logs "undefined says woof"
```

In the example above, `dog.bark` is called with two very different types of objects, the second of which (`address`) doesn’t have a `name` property.

### Using `strictBindCallApply`

Compiling with the `--strictBindCallApply` flag allows you to specify the `this` type:

```
const dog = {
  name: "fido",
  bark: function (this: { name: string }) {
    console.info(this.name, "says woof");
  },
};
const address = { street: "2 State St" };

dog.bark.call(dog);
dog.bark.call(address);

```

Line 10 will error with:

```
Property 'name' is missing in type '{ street: string; }' but required in type '{ name: string; }'.
```

## Next steps

Next, let’s take a look at [classes](https://www.bitovi.com/academy/learn-typescript/classes.html?hsLang=en-us) in TypeScript.

###### On this page...

###### Get help

If you need [help](https://discord.gg/J7ejFsZnJ4) with an exercise, please reach out to us on [Discord](https://discord.gg/J7ejFsZnJ4)

If you find a bug, please [create an issue](https://github.com/bitovi/academy/issues/new) or email [contact@bitovi.com](mailto:contact@bitovi.com?Subject=Training%20Suggestion)

## Join the Bitovi Newsletter

 Do you want to receive updates about new Bitovi Academy courses, Bitovi open source projects, and dev community news? If so, please provide your email. We won’t spam you or give it away for any reason!  
*By providing your email you agree to receive communications from Bitovi*

![](https://bitovi.github.io/academy/static/img/close.svg)

```json
{
     "@context": "http://schema.org",
     "@type": "Organization",
     "mainEntityOfPage":{
          "@type":"WebPage",
          "@id":"https://www.bitovi.com/academy/learn-typescript/functions.html",
          "description": "Learn how to annotate functions parameters and return values, use different parameter types, and bind `this`. 
"
     },
     "url": "http://bitovi.com",
     "logo": "https://www.bitovi.com/hubfs/bitovi-logo-23-1.svg",
     "image": "https://www.bitovi.com/hubfs/bitovi-logo-x2.png",
     "name": "Bitovi Web App Consulting",
     "alternateName": "Bitovi",
      "naics": "541511",
      "description": "Bitovi is a UX, UI design and front-end JavaScript development consulting company",
     "address": {
          "@type": "PostalAddress",
          "streetAddress": "1134 Pine Tree Lane ",
          "addressLocality": "Libertyville",
          "addressRegion": "IL",
          "addressCountry": "United States",
          "postalCode": "60048"
     },
     "areaServed": {
          "@type": "GeoCircle",
          "geoMidpoint": {
               "@type": "GeoCoordinates",
               "latitude": "41.8781",
               "longitude": "87.6298"
          },
          "geoRadius": "5000 km"
     },
     "telephone": "312-620-0386",
     "email": "contact@bitovi.com",
     "sameAs": [
          "https://www.facebook.com/BitoviLLC/",
          "https://twitter.com/bitovi",
          "https://www.linkedin.com/company/bitovi"
     ]
}
```