12 Things EVERY JavaScript Developer Should Know 🕛
Tags: javascript, beginners, webdev, node
Published: 2022-08-15 12:05:14

There's no **better feeling** than mastering a programming language. In today's post, we'll explore 12 things you should know if you're serious about JavaScript 😎

## [1. `includes()` Over `indexOf()`](https://www.youtube.com/watch?v=7M6Hg2YSHrg)
Rather than checking for `-1` to see if an array contains the given element, try using `includes()` instead, which returns a clean `true` or `false`:
```js
const numbers = [3, 8, 2, 4];
const containsEight = numbers.includes(8);

// containsEight == true 😉
```
## [2. Using the `defer` Attribute](https://www.youtube.com/watch?v=7dwyMSyd_00)
If you include your `<script>` tag at the end of your `<body>` tag, it's time to stop. Seriously. Instead, place your `<script>` tag in your `<head>` and use the `defer` attribute.

This will load the script **asynchronously** (speed ⚡) and more importantly, **only execute the script once the document has finished parsing**:
```html
<!DOCTYPE html>
<html>
    <head>
        <title>Subscribe to "dcode" on YouTube 🤨</title>
        <script src="js/main.js" defer></script>
    </head>
</html>
```
## [3. `const` Over `let`](https://www.youtube.com/watch?v=RE6qf3As-XU)
This is one of my favourites. Guess what? I hardly ever use `let` - because in most cases, **you don't need to**.

`let` should only be used when you know a variable will be reassigned (in other words, using the `=` sign). In all other cases, use `const`! 🤓
```js
const myButton = document.getElementById("myButton");
const numbers = [4, 0, 2, 3, 1];

// NOT reassignment
myButton.appendChild(someOtherDiv);

// NOT reassignment. It's a method call
numbers.push(5);
```
## 4. [Template Literals (Strings)](https://www.youtube.com/watch?v=-RWaq07BOWg)
If you're trying to build up strings dynamically, there's almost never a reason to use `'`'s or `"`'s as of recent years. Instead, build strings in a clean manner using template literals (backtick):
```js
const hour = "12";
const minute = "35";
const amPm = "pm";
const time = `It is ${minute} minute(s) past ${12}${amPm}`;

// time == It is 35 minute(s) past 12pm 😧
```
## 5. [Logical OR (`||`) for Defaults](https://www.youtube.com/watch?v=VAV61ASDo1s)
Most of you may already know this one, but it surprises me how often I **don't** see it being used. Let me keep it simple.

Replace this:
```js
let username = localStorage.getItem("username");

// Can't find username, use a default
if (!username) {
    username = "Unknown";
}
```
With this:
```js
const username = localStorage.getItem("username") || "Unknown";
```
Not only is it a single line of code, you also use `const` over `let` 😲👆
## [6. Using `classList` Over `className`](https://www.youtube.com/watch?v=XYzSyPlY7_E)
What if I told you there was a smart way to interact with the classes on an HTML element? Well, you can with `classList`.

Let's have a look at a few examples:
```js
const myButton = document.getElementById("myButton");

// Add a class
myButton.classList.add("color-primary");

// Remove a class
myButton.classList.remove("is-disabled");

// Toggle a class
myButton.classList.toggle("visible");

// Check if a class exists
myButton.classList.contains("border");

// Replace a class
myButton.classList.replace("color-warn", "color-success");

😏
```
## [7. Object Destructuring](https://www.youtube.com/watch?v=G4T2ZgJPKbw)
JavaScript offers an intelligent way to take values from an object and reference them as variables or parameters - it's done through object destructuring:

```js
const person = {
    name: "Dom",
    age: 28,
    occupation: "Software Developer",
    country: "Australia"
};

// Take the `name` and `country` from the `person` object
const {name, country} = person;

// Dom is from Australia
alert(`${name} is from `${country}`);
```
And with function parameters:
```js
function showMessage({name, country}) {
    alert(`${name} is from `${country}`);
}

showMessage(person);

🦘
```
## [8. Array Destructuring](https://www.youtube.com/watch?v=fsybVOVcNg0)
Similar to object destructuring, JavaScript offers the same thing for arrays, but it works through the index of an element:
```js
    const color = [0, 149, 120];
    const [red, green, blue] = color;
```
## [9. Array `map()`](https://www.youtube.com/watch?v=djiHm61y8P4)
This is probably one of the most **under-used methods of JavaScript**. It's called `map()` and is used to transform the elements of an array.

Let's take this `numbers` array and create a new array, which each number **doubled**:
```js
const numbers = [4, 2, 8, 10];
const doubled = numbers.map(number => {
    return number * 2;
});
```
This code is really simple - we pass a function into the `.map()` method, and it will run for each element in an array. The return value of this function is the **new** value for that element in the array.
## [10. Element `closest()`](https://www.youtube.com/watch?v=Eb5lyRn7lgk)
**PAY ATTENTION** because this DOM method is my favourite. It comes handy very often, especially when building user interfaces or using a third-party library.

This method gives you context of a child element's parent element by searching up the DOM tree until it finds an ancestor matching the given selector.

In the example below, we are within a `click` event but we don't know where the event target (*element that was clicked on*) is in the document:
```js
someUnknownButton.addEventListener("click", e => {
    const container = e.target.closest(".container");
});

/*
    The DOM tree might look like this:

    <div id="app">
        <div class="container">
            <div class="float-right">
                <button>Click</button>
            </div>
        </div>
        <div class="container"> <!-- ⬅️ end up here -->
            <div class="float-right">
                <button>Click</button> <!-- 👈 CLICKED -->
            </div>
        </div>
        <div class="container">
            <div class="float-right">
                <button>Click</button>
            </div>
        </div>
    </div>
*/
```
## [11. Fetch API Over AJAX](https://www.youtube.com/watch?v=ZTQcJWixB1k)
It's time to stop using AJAX. Use `fetch()` for your client-side HTTP requests instead, it's a modern way to fetch data from your backend or API. As a bonus, you'll also **get comfortable with promises**.

Let's see how we can use `fetch()` over a traditional jQuery AJAX request:
```js
// jQuery AJAX
$.get("/data/users.json", function(users) {
    console.log(users);
});

// Fetch API
fetch("/data/users.json").then(response => {
    return response.json();
}).then(users => {
    console.log(users);
});
```
The Fetch API does look a little more complicated, but it's native to the browser, avoids **callback hell** and gives you easy access to the `response` object (to check status codes, content type etc.) ✈️
## [12. Async Await](https://www.youtube.com/watch?v=1Okmw8ggD1Q)
Many developers are afraid to jump into the world of `async/await`, but trust me, give it a good shot - it really isn't too complicated.

To put it simply, `async/await` offers you an alternative way to deal with promises. You can avoid the verbose `.then()` syntax and make your code look more sequential.

Let's have a 2nd look at the previous Fetch API code example but using `async/await` over `.then()`:
```js
async function fetchAndLogUsers() {
    const response = await fetch("/data/users.json");
    const users = await response.json();

    console.log(users);
}
```
You can see here, the `await` keyword breaks up each `.then()`, and if you wanted to, you can use `try...catch` to handle errors as opposed to `catch()` 😧.

# Video Guide
To see this post in video form, have a look on my YouTube channel, [dcode](https://www.youtube.com/c/dcode-software)

{% youtube Kr6juLquyNk %}

# JavaScript DOM Crash Course
You can find a complete course on the JavaScript DOM which goes over some of the topics covered in this post at the link below 👇
https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1
![Course Thumbnail](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/769cuap96tu5s653bzld.jpg)

**Keep learning 💪**