|JavaScript| JavaScript: Functions
Tags: javascript, html, css, webdev
Published: 2020-12-07 01:44:25

---
title: |JavaScript| JavaScript: Functions
published: true
description: 
tags: javascript, html, css, webdev
//cover_image: https://direct_url_to_image.jpg
---



              -Intro to Functions
              -Arguments Intro
              -Function with Multiple Arguments
              -The Return Keyword
              -Function Scope
              -Block Scope
              -Lexical Scope
              -Function Expressions
              -Higher Order Functions
              -Returning Functions
              -Defining Methods
              -The Keyword 'this'
              -Using Try/Catch 
      

###Intro to Functions
Functions are reusable procedures. 
Functions allow us to write reusable, modular code.
We define a "chunk" of code that we can then execute at a later point. We use them all the time. 


syntax 

function functionName() {
do something here 
}

```javascript 

function singSong() {
  console.log("Do"); 
  console.log("RE"); 
  console.log("MI"); 
}

singSong()
singSong()
singSong()

```

the out put of the code would be 
DO RE MI 



###Arguments Intro

An argument allows us to write functions that accept inputs. 

Code with no inputs
```javascript 
"hello".toUpperCase(); 
```
Code with inputs 
```javascript 

"hello".indexOf('h'); 
"hello".indexOf('o'); 
```
The main point of arguments is that they allow something to happen within the code to change the outcome by using inputs. 




###Function with Multiple Arguments

```javascript 

function greet(firstName, lastName) {
 console.log(`Hey there, ${firstName}! ${lastName}.`)
}
```
The code has two parameters defined that is separated by a comma. 


```javascript 

greet('Jane','John');

```
the output would be 

Hey there, Jane, John. 

 

###The Return Keyword
The return keyword is a built-in methods that returns values when we call them. 

```javascript 

function repeat(str, numTimes) {
  let result = '';
  for (let i = 0; i < numTimes; i++) {
    result += str; 
  }
  console.log(result); 
}

function add(x, y) {
  let sum = x + y; 
  return sum;
}
```
Return statement ends functions execution and specifies the value to be returned by that function. 


###Function Scope

Scope variable "visibility" is the location where a variable is defined dictates where we have access to that variable.  


###Block Scope

A block includes things like conditionals as well as loops. 




```javascript 

let radius = 8; 
if (radius > 0) {
   const PI = 3.14; 
   let circ = 2 * PI * radius; 
}


console.log(radius); 
console.log(msg); 

```

The console.log statements are outside the block level scope, therefore the console.log statements will not run. 

The code between the { will run accordingly because they are in the block level scope. 

PI and circ are scoped to the block level. 




```javascript 

let bird = 'mandarin duck';

function birdWatch() {

let bird = 'golden pheasant';
bird; 
}

bird; 

```

bird is scoped to birdWatch function 



###Lexical Scope

Lexical Scope is when an inner function nested inside of some parent function has access to the scope or to the variables defined in the scope of that outer function. 



```javascript 

function bankRobbery() {
  const heroes = ['Spiderman', 'Wolverine',]
function cryForHelp() {
 for (let hero of heros) {
  console.log(`Please help us, ${hero.toUpperCase()}

   }
  }
   cryForHelp(); 
}

```

Nested or inner function has access to the same stuff as the parent function or grandparent or how many levels up. 


###Function Expressions
A function is just a value that can be stored in a variable. 


```javascript 

const sqaure = function (num) {
  return num * num; 
}

sqaure(7); 

```

```javascript 

const add = function (x, y) {
  return x + y; 
}

```


###Higher Order Functions
Functions that operate on/with other functions. 
They can accept other functions as arguments and return a function. 

```javascript 

function callTwice(func) {
  func(); 
  func(); 
}

function laugh() {
  console.log("Hahahah"); 
}

callTwice(laugh)

```
The function called callTwice is going to expect a function to be passed in. 





###Returning Functions

```javascript 

function makeMysteryFunc() {
 const rand = Math.random(); 
 if (rand > 0.5) {
 return function () {
 console.log("Congratz, I am a good function!")
 console.log("You win a million dollars!!")
} else {
  return function() {
 alert("This is a popup message to annoy you")
   }
  }
 }
}
```

Returning a function as a value. 


###Defining Methods
Methods are functions as properties on objects.

```javascript 

const math = {
  multiply : function(x ,y) {
 return x * y; 
}, 
   divide : function(x ,y) {
 return x / y; 
}, 
   square : function(x) {
 return x * x; 
}, 
 
}; 

```

###The Keyword 'this'

The keyword 'this' is used to access other properties on the same object. 

```javascript 

const person = {

 first: 'Robert', 
 last: 'Herjavec', 
 fullName() {
 return `${this.first} ${this.last}`
 }
}

person.fullName(0; 
person.last = "Plant"; 
person.fullName(); 

```


###Using Try/Catch 
 Try/Catch is used for errors or exceptions in JavaScript. They have to do with catching errors or preventing them from breaking or stopping the execution of code. 

Sometimes it is necessary to anticipate where something might go wrong and plan for that in a way that will keep the code from breaking. 

 ```javascript 

try {

  hello.toUpperCase(); 
} catch {
  console.log("Error!!")
}
hello.toUpperCase(); 

console.log("After"); 

```
```javascript 

function yell(msg) {
  try {
   console.log(msg.toUpperCase().repeat(3)); 
  } catch (e) {
  console.log("Please pass a string next time!")
  }
}

```