# Function

* Similar to JavaScript functions&#x20;
* Have some additional features...
  * types
  * default parameters
  * rest parameters&#x20;
  * lambdas

```javascript
function greet(){
    alert("Hello world.");
}
```

## Function Types

* Types describe what is returned by a function

```javascript
function getCountry() : string {
    return "Canada";
}
var c : string = getCountry(); // ok
var c : number = getCountry(); // compile-time error
```

## Optional Parameters

```javascript
function sayHappyBirthday(name?: string){
    console.log("Happy Birthday " + name);
}

sayHappyBirthday(); // OK
sayHappyBirthday("Hemant"); // OK
```

## Default Parameters

```javascript
function sayHappyBirthday(name?: string = "Buddy!"){
    console.log("Happy Birthday " + name);
}

sayHappyBirthday(); // Happy Birthday Buddy!
sayHappyBirthday("Hemant"); // Happy Birthday Hemant
```

## Rest Parameters

* In JavaScript list of all arguments are provided in the mysterious arguments variable&#x20;
* it's real array ( so we can use array methods push, pop etc on it unlike arguments )

```javascript
function roleCall(master: string, ...names : string[]){
    console.log("Master is "+ master); // Master is Hemant
    console.log(names);  // ["Rickon", "Sansa", "Robb", "Arya"]
};
roleCall("Hemant","Varun","Vinay","Sasis","Arya");
```

## Lambdas ( arrow function )

* A different kind of function invocation where the value of this is not changed&#x20;
* Works similar to function but has a preferable syntax&#x20;
* Also known as an arrow or a fat arrow function

```javascript
var superhero = {
    name: "Hemant",
    greet: function() {
        setTimeout(() => {
            console.log(this.name); // Hemant
        }, 500);
    }
};

superhero.greet();
```
