DEV Community

Cover image for JavaScript Ninja Part 1
Adnan Babakan (he/him)
Adnan Babakan (he/him)

Posted on • Updated on

JavaScript Ninja Part 1

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

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

Logging trick

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:

console.log('name: ' + name);
Enter fullscreen mode Exit fullscreen mode

This can be shortened like this:

console.log({ name });
Enter fullscreen mode Exit fullscreen mode

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!

Merging objects

Merging objects used to be kind of hard but this is going to change your life!

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"
                }
};
Enter fullscreen mode Exit fullscreen mode

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

let doctorWho = { ...series, ...actors };
Enter fullscreen mode Exit fullscreen mode

Merging arrays

This one works exactly like the previous one.

If you have two arrays like this:

let programmingLanguages = ["JavaScript", "PHP", "Go", "Java"];
let spokenLanguages = ["English", "Turki", "Persian", "Hindi"];
Enter fullscreen mode Exit fullscreen mode

You can merge them like this:

let allLanguages = [...programmingLanguages, ...spokenLanguages];
Enter fullscreen mode Exit fullscreen mode

Destructuring aliases

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:

let coordinates = { x: 80, y: 120 };
Enter fullscreen mode Exit fullscreen mode

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:

let x = coordinates.x;
let y = coordinates.y;
Enter fullscreen mode Exit fullscreen mode

This is OK, but have a look at the code below:

let { x } = coordinates;
let { y } = coordinates;
Enter fullscreen mode Exit fullscreen mode

This is the exact same code as the one above!

You can also name your variables differently:

let { x: theX } = coordinates;
let { y: theY } = coordinates;
Enter fullscreen mode Exit fullscreen mode

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

Ternary conditions

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:

let age = 20;
if(age > 18) {
    let ageStatus = 'eligible';
} else {
    let ageStatus = 'not eligible';
}

console.log('You are ' + ageStatus + '!');
Enter fullscreen mode Exit fullscreen mode

But instead, you can use ternary to shorten your code:

let age = 20;
console.log('You are ' + (age > 18?'eligible':'not eligible') + '!');
Enter fullscreen mode Exit fullscreen mode

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

Short-circuiting

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:

let me = { age: 19 };
let myName = me.name || 'Anonymous';
Enter fullscreen mode Exit fullscreen mode

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:

let me = { age: 19 };

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

me.name || showError();
Enter fullscreen mode Exit fullscreen mode

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:

let isAdnanHome = true;

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

isAdnanHome && knockTheDoor();
Enter fullscreen mode Exit fullscreen mode

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

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:

let myNum = "10";
console.log(myNum - 2); // 8
Enter fullscreen mode Exit fullscreen mode

But what about this?

let myNum = "10";
console.log(myNum + 2); // 102
Enter fullscreen mode Exit fullscreen mode

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:

let myNum = "10";
myNum = Number.parseInt(myNum);
console.log(myNum + 2); // 12
Enter fullscreen mode Exit fullscreen mode

This is true, but check this ninja way out:

let myNum = +"10";
console.log(myNum + 2); // 12
Enter fullscreen mode Exit fullscreen mode

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!

console.log(typeof +true); // equal to 1 so it is number
console.log(typeof +false); // equal to 0 so it is a number
Enter fullscreen mode Exit fullscreen mode

Convert to string

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!

let myString = 4 + "";
Enter fullscreen mode Exit fullscreen mode

or

let myString = "" + 4;
Enter fullscreen mode Exit fullscreen mode

Convert float to integer

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:

let myNum = 10.2 | 0;
console.log(myNum); // 10
Enter fullscreen mode Exit fullscreen mode

This can also work on negative numbers:

let myNum = -8.8 | 0;
console.log(myNum); // -8
Enter fullscreen mode Exit fullscreen mode

Convert to boolean

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:

console.log(typeof 0); // number
Enter fullscreen mode Exit fullscreen mode

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.

console.log(typeof !!0); // boolean
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)