DEV Community

loading...
Cover image for Javascript in a Ninja Way

Javascript in a Ninja Way

deepanmania profile image Deepan ・Updated on ・3 min read

Hi Dev,

Today I'm gonna share my 7 favorite Javascript shorthand tips that will look cool and clean on your code.

Alright, Let's begin.

1) If Presence

Before getting into this shorthand, let me clear you about the Javascript falsy values.

A falsy value is something that evaluates to FALSE, for instance when checking a variable. There are only six falsy values in JavaScript: undefined, null, NaN, 0, "" (empty string), and false of course.
Other than these six everything is considered as a truthy value in Javascript.

When doing β€œif checks”, assignment operators can sometimes be omitted.

Shorthand Expression

if (myValue) // myValue can be any truthy value

The equivalent long hand expression will be

Longhand Expression

if (Boolean(myValue))

2) Decimal Values with trailing zeroes

const maxValue = 100000

Instead of writing numbers like this we can write those in a cooler way without trailing zeroes

const maxValue = 1e5 // 100000
1e0 === 1
1e1 === 10
1e2 === 100
1e3 === 1000
1e4 === 10000
1e5 === 100000

3) Function Return

In all Javascript functions, the default return value will be undefined. To return a value from a function we will use the return keyword. But in an arrow function with a single statement will implicitly return the result its evaluation (the function must omit the braces ({}) in order to omit the return keyword).

// longhand

const add = (a, b) => {
  return a + b
}

// shorthand

const add = (a, b) => (a + b)

4) Spread Operator

Of course, if we are talking about the shorthand tips, it won't be complete without spread operator. It's a ES6 syntax and its more fun and clean. It can be used to replace certain array functions. The spread operator is simply a series of three dots.

const a = [1, 2, 3]
/* To concat a with b*/

// longhand
const b = [4, 5, 6].concat(a)

// shorthand

const b = [4, 5, 6, ...a]

const c = [4, ...a, 5, 6] // You can use it anywhere inside an array

/* You can even use a spread operator to clone an array */

const copyOfA = [...a] // Traditional way is the use of slice method

5) Mandatory Parameter

Since javascript variables are loosely typed, we cannot validate for a mandatory parameter in a function. By default, javascript will take undefined for a function parameter if it isn't passed as an argument. To validate it you need to use an if clause or you can do a default required assignment as shown below.


// longhand
function foo(bar) {
  if(bar === undefined) {
    throw new Error('Missing parameter!!!');
  }
  return bar;
}

// shorthand

required = () => {
  throw new Error('Missing parameter!!!');
}

foo = (bar = required()) => {
  return bar;
}

6) '+': Integer typecasting

Among all these, this short is the one I'll use a lot. We overload '+' operator for string concatenation often. Another use of the '+' operator that I find most useful is for Integer typecasting.

// longhand
const num1 = parseInt("100")
const num2 =  parseFloat("100.01")

// shorthand
const num1 = +"100" // converts to int data type
const num2 =  +"100.01" // converts to float data type

7) '~': Bitwise IndexOf

Another favorite one among these here is the use of the '~' operator with the indexOf function. The usage of ~ (bitwise NOT) operator is, takes one number and inverts all bits of it.
The indexOf method will return the first index of the occurrence in an array or string. Since 0 is a falsy value in Javascript, we cannot use the indexOf method directly inside if clause. So for 0, '~' operator will return -1 and for -1 it will return 0.


// longhand
if(arr.indexOf(item) > -1) { // Confirm item IS found

}

if(arr.indexOf(item) === -1) { // Confirm item IS NOT found

}

// shorthand
if(~arr.indexOf(item)) { // Confirm item IS found

}

if(!~arr.indexOf(item)) { // Confirm item IS NOT found

}

Thanks for reading guys. Don't forget to comment on your favorite shorthand expression!!!

Happy Coding...:)

Discussion (18)

pic
Editor guide
Collapse
savagepixie profile image
SavagePixie

The equivalent long hand expression will be
if (myValue === true)

Wouldn't the equivalent longhand expression be if (myValue == true)? Your example will return false unless myValue is a boolean.

Other than that, all those are great features of JavaScript.

Collapse
blakemealey profile image
Blake Mealey

Came to the comments to say this πŸ˜ƒ

Collapse
patricklai profile image
Patrick

Yea I agree, that part is very misleading... its equiv to if (Boolean(myValue)) {...}

Collapse
deepanmania profile image
Deepan Author • Edited

Yeah, you are right. I'll change it right away. Thanks, patrik, Blake

Collapse
deepanmania profile image
Deepan Author

I assumed that it's a boolean. I was just trying to explain the truthy expressions.
I'll put appropriate comments. Thanks for the feedback.

Collapse
savagepixie profile image
SavagePixie

Oh, gotcha! I assumed you were checking that it was a truthy value.

Collapse
mlaufer profile image
Michael Laufer

I would never use "2) Decimal Values with trailing zeroes" and would strongly advise against using this in anything other than personal projects. The only benefit you get is confusing other developers, especially juniors.

Collapse
deepanmania profile image
Deepan Author

I think that up to one's perspective. We can easily see those expressions in mathematics.

Collapse
samholmes profile image
Sam Holmes • Edited

Cool trick for #5. You could even include parameters for require like so:

required = (f, p) => {
  throw new Error(`Parameter ${p} for ${f} required.`);
}

foo = (bar = required('foo', 'bar')) => {
  return bar;
}

Collapse
karataev profile image
Eugene Karataev

Nice list.
In the last example I prefer to use [1,2,3].includes(1) instead of ~[1,2,3].indexOf(1)

Collapse
juanfrank77 profile image
Juan F Gonzalez

Wow, guess I became a ninja and didn't even realize it... 6 out of 7 tricks. Not bad

Collapse
ristetloegpose profile image
jacobdo

Mandatory parameter seems very useful

Collapse
ryanpwalker profile image
Ryan Walker

const num1 = +"100" Does this shorthand work in all browsers?

Collapse
deepanmania profile image
Deepan Author

It's just usage of a unary operator '+'. So, I believe it will work the same on all browsers. But you cannot use const, instead of const use var since const is introduced in ES6.

Collapse
samholmes profile image
Sam Holmes • Edited

I think #6 is code smell (bad advice). Instead be concise and use parseInt, parseFloat, or Number for typecasting

Collapse
samholmes profile image
Sam Holmes • Edited

For #7 we could just use Array.prototype.includes() (developer.mozilla.org/en-US/docs/W...)

Collapse
vagoel profile image
Varun

I like the Mandatory Parameter way of throwing error for required fields.Its cool and enhances readability.
Thanks for sharing

Collapse
papidev profile image
Papidev

Uhm nice to know , but points 5,6 and 7 seem less readable to me. Personally I prefer longhand in those cases.