Concepts you should know to be a master of JavaScript
Tags: majorleaguehacking, localhackday, mlh, javascript
Published: 2021-01-12 18:17:30

#MLH #MajorLeagueHacking #LocalHackDay

## How to use JavaScript
JavaScript is an amazing programming language. It is most popular as the browser's programming language, but that does not mean that's all it is good for. It is used for much more...backend development, desktop development, machine learning, and many more. 
For anything not in the browser, one way to compile and run JavaScript is [Node.js](https://nodejs.org/en/). 

### With the browser
In the browser, you can just add a file with the `.js` extension to your HTML using the `script` tag like this:

```html
<!DOCTYPE html>
<html>
  <head>
    <title>Page Title</title>
  </head>
  <body>

    <script defer src="path/to/file.js"></script>
  </body>
</html>
```
**Note**: Everything in the JavaScript file will be executed in the browser.

### With Node.js
In order to run a JavaScript file on your machine all you need to do is use the console like this:

```js
// script.js

console.log("Hello World!");
```

```
node script.js
```

## What you need to know to master JavaScript

### Data Structures
The concept of Data Structures is not specific to JavaScript. But there are some interesting features in JS for them.

#### Arrays
In JavaScript, arrays have special functions attached to them, called _Array Methods_.

The examples will use the following array: 

```js

var array = [18, 20, 22, 40, 15, 21, 16, 17, 96];

```

1.the `forEach` function:
```js

function callbackFunction(value, <index>) {
  sum = sum + value;
}

array.forEach(callbackFunction);

``` 

This will return the sum of all elements in the array, without creating a new array.
* The _value_ parameter has a specific element of the specified array.
* The _index_ parameter is optional and returns the current index.

2.the `map` function
```js

function callbackFunction(value, <index>) {
  sum = sum + value;
}

array.map(callbackFunction);

```

This does the same thing as the `forEach` function, but it generates a new array to work on.

3.the `filter` function
```js

function callbackFunction(value, <index>) {
  return value > 20;
}

array.filter(callbackFunction);

```

This function creates a new array with element that pass the test from the function passed as parameter.

4.the `reduce` function
```js

var sum = array.reduce(callbackFunction)

function callbackFunction(total, value) {
  return total + value;
}

```

This function will reduce the array to a single number. In this case it will reduce it to the sum of all elements within it.

The parameters are:
* `total` - initial value / previously returned value
* `value` - the current value

#### Objects
In JavaScript, objects are a collection of other elements of the language. I say _other elements_, because it can also contain functions and other objects.

Example: 
```js

const object = {
  elem1: "text", //a string
  elem2: 2,      //an integer
  elem3: function () {
                 // a function
    const a = 2, b = 3;
    return a + b;
  },
  elem4: {       // an object
    elem: "text2"
  }
};

```

##### How to access elements of an object
You can access an element from an object using the `.` notation.

```js

console.log(object.elem1);     //return "text"

console.log(object.elem2);     //return 2

console.log(object.elem3());   //return 5(2+3);

console.log(object.elem4.elem);//return "text2"

```

### Functions
In JavaScript there are 3 ways to declare functions:

* Named function
```js
function myFunction() {
  //code here
}
```

* Anonymous function

```js
function() {
  //code here
}
```

* Arrow functions

```js
const myFunction = () => {
  //code here
}
```

### There are different ways of using functions:

* Normal

```js
myFunction();
```

* IIFE (Instantly Invoked Function Expression)

```js
function myFunction() {
  //code here
}();
```
**Note**: As you can see the function is called _instantly_ after it is declared. We can tell by the parenthesis `()` at the end of the function declaration.

### Returning a function
A function can return another function, with the returned function being called a **Closure**. Here is an example:

```js
function parentFunction() {
  return {
    function returnedFunction() {
      //code here
    }
  }
}
```
```js
parentFunction().returnedFunction();
```

**Note: **This concept helps with encapsulation(technique for compartmentalizing information).
Example:
```js
function parentFunction() {
  function _privateFunction() {

    return "text to be returned"
  }
  return {
    function returnedFunction() {
      return _privateFunction();
    }
  }
}
```
```js
parentFunction().returnedFunction()  //"text to be returned"
```

### Promises
**Producing code** is code that can take some time. **Consuming code** is code that must wait for the result. A **Promise** is a JavaScript object that links producing code and consuming code.

```js
let myPromise = new Promise(function(resolve, reject) {
  resolve();  //when successful
  reject();   //when an error occurs
});
```

```js
myPromise
  .then(res => {
    //when the call is successful
    //we have access to the result via the res parameter
  })
  .catch(err => {
    //when an error occurs
    // we have access to the error via the err parameter
  })
```

### Async/await
* the 'async' keyword
When `async` is in front of the function declaration, the function will return a _Promise_. So:
```js
async function myFunction() {
  return "Hello World!"
}
```
is equivalent with:
```js
async function myFunction() {
  return Promise.resolve("Hello World!")
}
```

* the `await` keyword
The `await` keyword before a function makes the function wait for a promise.
```js
let result = await promise;
```

**Note: **The `await` keyword can only be used inside an `async`. function.

### Web API requests
Making requests to APIs is an essential part of JavaScript. Every developer is required to know this. For example:

* a front-end dev is required to know in order to access APIs to make the project more interactive(sending emails, saving in databases, etc.)
* a back-end dev needs to know this to be able to access existing services(Spotify API, Discord API, Twilio API, etc.), instead of coding the from 0(not reinventing the wheel)

There are 2 great ways to make API calls: 

* with the `fetch` function (included in the basic JavaScript installation) - no need to install anything
```js

const options = {
  method: "GET/POST/PUT/DELETE",
  headers: {}, //optional
  data: {},  //optional
  body: {},    //optional
}

const request = fetch('url/of/api', options); // this returns a promise so we could and should use the await keyword

const result = request.json(); // returns a JSON object
```

or

```js
const options = {
  method: "GET/POST/PUT/DELETE",
  headers: {}, //optional
  data: {},  //optional
  body: {},    //optional
}

fetch('url/of/api', options)
  .then(res => {
    //returns a JSON object
  })
  .catch(err => {
    //code for error here
    console.error(err);
  });
```
* with the `axios` function - _axios_ function needs to be installed

**Note: **You have to import the `axios` library like this:

```js
import axios from 'axios';
```

```js
const options = {
  headers: {}, //optional
  params: {},  //optional
};

axios.<get/put/post/delete>('url/to/api', options)
  .then(res => {
    // can access a JSON object
  })
  .catch(err => console.error(err));
```

or

```js
const options = {
  headers: {}, //optional
  params: {},  //optional
  method: "GET/POST/PUT/DELETE"
};

axios('url/to/api', options)
  .then(res => {
    // can access a JSON object
  })
  .catch(err => console.error(err));
```

## What helps in mastering anything code related
This next section is _important_, however it does not have any _technical explanations_. These are some tips on how to _grow as a developer_ and what helps when you are looking to get hired. If you're not interested you can skip this part.

1. Join a community
Communities of developers can help you meet new people interested in the same topics. It's not only fun but also leads to learning from other developer's experience.

2. Contribute to Open Source
Join GitHub. Find something interesting. Add value to that project. For more information, I recommend [Eddie Jaoude's Youtube channel](https://www.youtube.com/user/eddiejaoude). He has amazing content.

3. Participate in hackathons
Currently I am taking part in MLH's Local Hack Day: Build, and the challenges are great. They propose topics such as _Combine Two APIs_, _Use a Music API_ or _Use the Twilio API_, and many other interesting problems you can solve alone or with your guildmates. It is an amazing experience and I recommend it to anyone serious about development and coding. #MLH #MajorLeagueHacking #LocalHackDay