Javascript Tips for Beginners
Tags: javascript, productivity, webdev, beginners
Published: 2020-11-22 11:08:58

This is a list of 7 useful Javascript tips intended to improve your productivity and overall experience when using Javascript. These tips are for beginner and intermediate Javascript programmers. These tips will be arranged in no particular order. Let's move on to the tips!

### 1. Conditionals Without If Statements

The most common way to use conditionals in Javascript is if statements. In an if statement you can run a block of code if a specified condition is true. Also, you can add elses and else ifs for if the specified condition is false or the first specified condition is false and the next specified condition is true. This is how you would do a normal if statement in Javascript:

```javascript
let x = 10;
if (x === 10) {
  // this block of code will run if x is 10
  console.log("x is 10");
} else if (x === 9) {
  // this block of code will run if x is not 10 and is 9
  console.log("x is 9");
} else {
  // this block of code will run if x is not 10 or 9
  console.log("x is not 10 or 9");
}
```

To make this even better, we can make if, else statements even shorter using the ternary operator.

```javascript
let x = 10;
x === 10 ? console.log("x is 10") : console.log("x is not 10");
``` 

The statement above says if `x === 10` then (specified by a question mark) do this code block (`console.log("x is 10")`) or (specified by a colon) do this code block (`console.log("x is not 10")`). You might be thinking that this is great, concise, and intuitive, but where is the else if? What if I told you that you could do an else if in a ternary operator. 

```javascript
let x = 10;
x === 10 ? console.log("x is 10") : (x === 9 ? console.log("x is 9") : console.log("x is not 10 or 9"));
```

This way we have the if, else if, and else in a single line of code, cool! Let me show you an even shorter way in a React example!

```jsx
function App() {
  const show = true;
  return show && (
    <div>
      show is true!
    <div>
  )
}
```

In this case, the message "show is true!" will only render on the screen if the variable `show` is true. This way you can do something if the specified condition is true. This has lots of great use cases but as you can see it does have some limitations. 

### 2. Levels of Console Messages

To print or display things in the console, most of us use the plain `console.log("this will be printed in the console")` but there are other ways to do it. Don't do this: `console.log("ERROR:", error)`, there is a better way.

```javascript
console.info("I am information you need to know!")
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mw9w3klrmtbpwghhdqlq.png)

`console.info` gives the same `console.log` effect but is more specific and concise code. This shows the person reading your code that you are putting information in the console.

```javascript
console.warn("I am a warning!")
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tpepq6a9nq97m9748474.png)

`console.warn` gives the message you specified in a warning format, like above. This is a great way to put a warning in the console and to show the person reading your code that you are doing just that!

```javascript
console.error("There is an error!")
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/j9zfr3ijehgttzxr81ho.png)

`console.error` gives the message you specified in a red error message. This is the best way to write errors into the console.

### 3. Spread Operator

This is the best way to merge objects and arrays. The spread syntax specifies all of the items in the object/array.

Merging an Object:

```javascript
const favouriteFoods = {
  firstFood: "pizza",
  secondFood: "ice cream",
  thirdFood: "ramen"
};
const favouriteDrinks = {
  firstDrink: "ice lemon tea",
  secondDrink: "iced water",
  thirdDrink: "ginger ale"
};
// spread operator: ...objectOrArray
const myFavourtieFoodAndDrinks = {
  ...favouriteFoods,
  ...favouriteDrinks
};
```

This way we can efficiently and effectively merge my favourite foods and drinks using the spread operator. 

Merging an Array:

Merging an array is very similar to merging an object, but I'll show it anyway.

```javascript
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArr = [...arr1, ...arr2];
```

Using the spread operator, we can merge `arr1` and `arr2` to a different array (`mergedArr`). 

### 4. Arrow Functions

Arrow functions are a substitute to functions declared by the keyword `function`. Arrow functions have become very popular, taking over the React world (most functional components use arrow functions). 

Function declared by the keyword `function`:

```javascript
function introduce(name) {
  console.log("Hello, I am " + name);
}
```

Arrow Function:

```javascript
const introduce = (name) => {
  console.log("Hello, I am " + name);
}
```

As you can see, these are very similar but the arrow function looks slightly cleaner (personal opinion). Where arrow functions really shine are as parameters to other functions. 

```javascript
function add(addFunction, num1, num2) {
  console.log(addFunction(num1, num2));
}

add((num1, num2) => num1 + num2, 2, 3);
```

As you can see, the arrow function is very intuitive and looks much cleaner than functions declared by the `function` keyword when passed as a parameter would. 

### 5. Template Strings

Have you ever found yourself in the position where you need to print/log more than two things? Instead of doing this: `console.error("Error: " + error)` or `console.error("Error:", error)`, use template strings. Template strings allow you to embed variables into strings. Take a look at some examples:

```javascript
let x = 10;
console.info(`X is equal to ${x}`);
```

```javascript
console.info(`2 + 2 is equal to ${2 + 2}`);
```

This will give us "X is equal to 10". Cool! Firstly, this string is initialized with different strings than what normal strings have (not double quotes or single quotes). Also, everything inside ${} <- that is Javascript. You can put variables in there or execute Javascript, anything you would like. 

### 6 & 7. Different Types of Comments & Good Comments

In my opinion, one of the most important parts of your code is readability. As the name suggests, readability is the ability to read your code efficiently. Comments are one of the best ways to improve the readability of your code. Remember, all code in a comment doesn't get executed. 

The most simple way to use comments:

```javascript
// wow, this is a comment
```

This way (single-line comments) is the most standard and is commonly used for comments which only need one line.

Bad single-line comment example:

```javascript
// this code puts information into the console, more specifically puts 1+1 into the console. Also, the code is ended with a semicolon. I worked very hard on this line of code. Did I mention, that it ends with a semicolon?
console.info(1 + 1);
```

This is a very bad example of a single-line comment. Good comments don't describe what the code looks like but what it does. A good test that I like to use when seeing if my comment is necessary is: if this comment wasn't there, could the person reading my comment still understand it? If the answer to that question is no, keep the comment, otherwise remove it. Let's have a look at a good comment example.

Good single-line comment example:

```javascript
const myFunction = (num) => {
  // check if its a prime number
  for(let i = 2; i < num; i++)
    if(num % i === 0) return false;
  return num > 1;
}
```

Since this code is not quite readable, this comment really helps to improve the readability of this code. Let's explore different types of comments. 

The multiline comment is declared with this `/* */`. 

Multiline comment example:

```javascript
/* 
I am a multiline comment.

This is still a comment.

Still a comment here...
*/
```

Multiline comments are great for comments which take up more than one line. Usually, multiline comments are used with the <a href="https://jsdoc.app/">JSDoc</a> syntax which helps to create functions more readable. JSDoc comments add the functions usage, parameters + their type, and the return value + their type. 

JSDoc Comment Example:

```javascript
/**
 * Returns a string introducing the name passed.
 *
 * @param {string} a name of a person
 * @return {string} a string introducing the name passed
 */
const introduce = (name) => {
  return `My name is ${name}.`
}
```

As you can see, this makes your function very readable so that the person reading your code can easily understand what this function does. 

### Conclusion

I hope you have learnt some Javascript tips that will improve your productivity and future code. If you think that I missed out on any Javascript tips, I would love to hear them in the comments section.

**Henry**