JavaScript Ninja Part 1
Tags: javascript, tutorial
Published: 2020-03-03 17:04:09

Hey there DEV.to community!

I had an idea of sharing some tricks and ways of JavaScript that are cool which either I know them myself or I collected them from other posts (I will include the source link).

This is going to be a series but I don't know how many posts it will include.

Keep in mind that some tricks might not work in ES5!

So Let's get started.

#Table of Content
* [console.table](#console-table)
* [Logging trick](#logging-trick)
* [Merging objects](#merging-objects)
* [Mergin arrays](#merging-arrays)
* [Destructuring Aliases](#destructuring-aliases)
* [Ternary conditions](#ternary-conditions)
* [Short-circuiting](#short-circuiting)
* [Ninja way data conversion](#ninja-way-data-conversion)
    * [Convert to number](#convert-to-number)
    * [Convert to string](#convert-to-string)
    * [Convert float to integer](#convert-float-to-integer)
    * [Convert to boolean](#convert-to-boolean)

---

## console.table <a name="console-table"></a>

Most JavaScript developers use `console.log` to see what there is in their object.

I present `console.table` to you!

See the difference:

![console.table](https://dev-to-uploads.s3.amazonaws.com/i/8v6cahb49pl7g47hnq5o.png)

## Logging trick <a name="logging-trick"></a>

Sorry I had no other idea to name this one. LOL

To print something with its name in the console developers usually do something like this:
```js
console.log('name: ' + name);
```

This can be shortened like this:

```js
console.log({ name });
```

This literally means an object that has a member named `name` which includes the value of a variable named `name`. (I wish I chose another name than `name` LOL)


I know these two tricks thanks to this post from Benjamin Mock!

{% link https://dev.to/benjaminmock/some-tips-on-using-the-js-console-console-log-console-table-47c8 %}

## Merging objects <a name="merging-objects"></a>

Merging objects used to be kind of hard but this is going to change your life!
```js
let series = {
                name: "Doctor Who",
                year: 2005
};
let actors = {
                "The Doctor": "Jodie Whittaker",
                companions: {
                    "Graham O'Brien": "Bradley Walsh",
                    "Ryan Sinclair": "Tosin Cole",
                    "Yasmin Khan": "Mandip Gill"
                }
};
```

Well, now that you have these two objects (YES I'M A DOCTOR WHO FAN!) you can merge all these together like this:

```js
let doctorWho = { ...series, ...actors };
```

## Merging arrays <a name="merging-arrays"></a>

This one works exactly like the previous one.

If you have two arrays like this:
```js
let programmingLanguages = ["JavaScript", "PHP", "Go", "Java"];
let spokenLanguages = ["English", "Turki", "Persian", "Hindi"];
```

You can merge them like this:
```js
let allLanguages = [...programmingLanguages, ...spokenLanguages];
```

## Destructuring aliases <a name="destructuring-aliases"></a>

This is one of the most known and used ones but in case if you don't know what this is, check out the code below:
```js
let coordinates = { x: 80, y: 120 };
```

Now imagine you want to have two variables called `x` and `y` representing the `x` and `y` from your `coordinates` respectively.

This is what you can do normally:
```js
let x = coordinates.x;
let y = coordinates.y;
```

This is OK, but have a look at the code below:
```js
let { x } = coordinates;
let { y } = coordinates;
```

This is the exact same code as the one above!

You can also name your variables differently:
```js
let { x: theX } = coordinates;
let { y: theY } = coordinates;
```

This code will declare two variables named `theX` and `theY` and assign `coordinates.x` and `coordinates.y` to them respectively.

## Ternary conditions <a name="ternary-conditions"></a>

This is also one of the most well-known ninja tricks.

Imagine you want to have a string with a part of it rendered conditionally. What you do normally is like this:
```js
let age = 20;
if(age > 18) {
    let ageStatus = 'eligible';
} else {
    let ageStatus = 'not eligible';
}

console.log('You are ' + ageStatus + '!');
```

But instead, you can use ternary to shorten your code:
```js
let age = 20;
console.log('You are ' + (age > 18?'eligible':'not eligible') + '!');
```

Not only your code gets shorter but it looks even more professional!

# Short-circuiting <a name="short-circuiting"></a>

This one is really cool! Even cooler than the ternary conditions.

You can use `||` and `&&` operators to return the first truly value and falsely values respectively.

Look at this code:
```js
let me = { age: 19 };
let myName = me.name || 'Anonymous';
```

This means if the `me.name` value is falsely (for instance in this case undefined) `myName` should have the value `Anonymous` instead.

As you see `||` returns the first true value.

This can be also used to invoke functions:
```js
let me = { age: 19 };

function showError() {
    console.log('Something went wrong!');
}

me.name || showError();
```

Since `me.name` is undefined the `showError()` will be called.

On the other hand `&&` returns the first falsely value.

This can have multiple use cases as well.

Check this code out:
```js
let isAdnanHome = true;

function knockTheDoor() {
    console.log('Knock knock!');
}

isAdnanHome && knockTheDoor();
```

As you see `isAdnanHome` is set to true, well this is not false so we proceed to the other side and call our function! This can come in handy in many situations.

## Ninja way data conversion <a name="ninja-way-data-conversion"></a>

JavaScript is of those languages which you rarely might need data conversion but this can still happen. There are several ways of converting data but there are some cooler ways in which they turn you into a JavaScript Ninja!

### Convert to number

In JavaScript, if you have a string only containing digits you can use it as a number as well.

Like this:
```js
let myNum = "10";
console.log(myNum - 2); // 8
```

But what about this?
```js
let myNum = "10";
console.log(myNum + 2); // 102
```

This won't return 12 as a number, but 102 as a string since `+` is an operator common between strings and numbers.

In order to use `+` so, you need to convert your string to number first:
```js
let myNum = "10";
myNum = Number.parseInt(myNum);
console.log(myNum + 2); // 12
```

This is true, but check this ninja way out:
```js
let myNum = +"10";
console.log(myNum + 2); // 12
```

Adding a `+` before your string will convert your string to a number!

As you know booleans are also numbers in disguise, `true` is equal to `1` and `false` is equal to `0`, so you can also convert these guys to numbers!
```js
console.log(typeof +true); // equal to 1 so it is number
console.log(typeof +false); // equal to 0 so it is a number
```

### Convert to string <a name="convert-to-string"></a>

Opposite of what is discussed above is also possible.

If you have a number that you want to act as a string you can prepend or append an empty string to it!
```js
let myString = 4 + "";
```
or
```js
let myString = "" + 4;
```

### Convert float to integer <a name="convert-float-to-integer"></a>

JavaScript doesn't literally care about floats or integers since they are both said to be numbers but still you can use them with full power!

In order to convert a float number to a number without decimals, you can use a function such as `Math.floor()`, but there is an easier way which is by using `| 0`, like this:
```js
let myNum = 10.2 | 0;
console.log(myNum); // 10
```

This can also work on negative numbers:
```js
let myNum = -8.8 | 0;
console.log(myNum); // -8
```

### Convert to boolean <a name="convert-to-boolean"></a>

As you know values other than `false`, `0`, `NaN`, `""`, `null` and `undefined` are considered to be `true` in JavaScript.

As we know `0` is false but its data type is still number:
```js
console.log(typeof 0); // number
```

If you absolutely want to convert the type to boolean you can add two `!` symbols in front of `0`!

As you know `!` is the `logical not` operator, so adding two of this symbol will return the initial boolean value but will convert the data type to boolean as well.

```js
console.log(typeof !!0); // boolean
```

---

I hope you enjoyed! Let me know what I'm missing here so I can also add them to the next part of this series!