DEV Community

Cover image for 7 neat tricks for JS that you probably did not know
Tapajyoti Bose
Tapajyoti Bose

Posted on • Updated on

7 neat tricks for JS that you probably did not know

Got tired of learning and want to get some cool tricks up your sleeve to earn the right to show off? You have come to the right place. Here are neat tricks that can even make your life easier!

1. Readable numbers

Ever run into an unreadably long number where you had to put your finger on the screen to read it? Luckily, there is an easy solution to that by using _ within the bounds of the number.

const number = 123_456_789;
Enter fullscreen mode Exit fullscreen mode

You can put _ anywhere within a number to make it easier to read, without hampering the number itself.

2. Truncate the end of arrays

Most people use Array.length as a getter function. A little-known fact is: that it can also be used as a setter.

let array = [1, 2, 3, 4, 5];

console.log(array); // [1, 2, 3, 4, 5]
console.log(array.length); // 5

array.length = 3;

console.log(array); // [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

3. Short circuit evaulation

short-circuit

No, we are NOT talking about those short circuits.

The && and || operators can be easily used to check for conditions and return values in a single line, which is known as short circuit evaluation.

Use case of &&

const showUserData = true;
const data = "not so secret data";

// will display false if showUserData is false
console.log(showUserData && data);
Enter fullscreen mode Exit fullscreen mode

Use case of ||

const fallbackData =
  "nothing to see folks";
const data = "random data";

// will display `fallbackData` if
// data is false-ish (eg: null, undefined, '', etc)
console.log(data || fallbackData);
Enter fullscreen mode Exit fullscreen mode

4. Optional chaining

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid

It's a simple solution to get a deeply nested property without having to check the validity of each reference in the chain.

// usage (will return undefined if any of the items is not defined)
user.data?.name;
user.data?.addressList?.[0];
user.greet?.(time);
Enter fullscreen mode Exit fullscreen mode

5. Get unique values in an array

Accessing the unique values in an array is a pretty common operation. There's a usual way, and there's a smart way of doing it

// USUAL WAY
// O(n^2) time complexity & O(n) space complexity
const uniqueValues = array.filter(
  (value, index, self) =>
    self.indexOf(value) === index
);

// SMART WAY
// complexity: O(n) time & space
const uniqueValues = [
  ...new Set(array),
];
Enter fullscreen mode Exit fullscreen mode

6. Nullish coalescing

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

Nullish coalescing is extremely useful when you want to return a default value when a variable might contain a null-ish value.

const getUserName = (user) => {
  return user?.name ?? "Anonymous";
};
Enter fullscreen mode Exit fullscreen mode

7. Replace all

The string.replace method is typically used to replace the first occurrence of a substring, but there is a simple way to turn it into a function that can replace all occurrences by using a regular expression with a global flag.

const replace_string =
  "Visit replacesoft. replacesoft is a software company";

console.log(
  replace_string.replace(
    /replace/,
    "Micro"
  )
); // "Visit Microsoft. replacesoft is a software company"

console.log(
  replace_string.replace(
    /replace/g,
    "Micro"
  )
); // "Visit Microsoft. Microsoft is a software company"
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Finding personal finance too intimidating? Checkout my Instagram to become a Dollar Ninja

Thanks for reading

Need a Top Rated Front-End Development Freelancer to chop away your development woes? Contact me on Upwork

Want to see what I am working on? Check out my Personal Website and GitHub

Want to connect? Reach out to me on LinkedIn

I have moved to Bali, Indonesia as a Digital Nomad. Follow me on Instagram to check out what I am up to.

Follow my blogs for Weekly new Tidbits on Dev

FAQ

These are a few commonly asked questions I get. So, I hope this FAQ section solves your issues.

  1. I am a beginner, how should I learn Front-End Web Dev?
    Look into the following articles:

    1. Front End Development Roadmap
    2. Front End Project Ideas
  2. Would you mentor me?

    Sorry, I am already under a lot of workload and would not have the time to mentor anyone.

Top comments (15)

Collapse
 
decker67 profile image
decker • Edited

Think about 0 and "" with && and ||, the are also falsy and sometimes you do not want that. Thats the reason for ?? I would think.

Also sometimes nice but dangerous: monkey patching.

const array = [1, 2, 3]
array.x = 42
Enter fullscreen mode Exit fullscreen mode

Gives also no error for value types like string and number, but looses the value.

Better forget it, its bad style. ;-)

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

Yeah I agree, it's NOT a recommended approach of resizing arrays. Added that just to showcase that it's also a setter which most people don't know

Collapse
 
innocentdevii profile image
Dipesh Raichana

I think it is a best way to make the array empty. This can be used array.length = 0 in place of array = []because prior one is faster than the later one.

Thread Thread
 
decker67 profile image
decker

We should not use the fastes method but the method who is understood.

Collapse
 
decker67 profile image
decker

Thats not monkey patching.

Collapse
 
r4e profile image
Richie Permana

Wth? length is also a setter?
My whole life is a lie...

Collapse
 
devfarouqk profile image
Umar Sulaiman Mailafiya

Man...
You never know. 😂Life is a lie in general. But we move..

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

For "Replace all" you can also just use the replaceAll method - which could be considered more readable.

Collapse
 
umamahesh_16 profile image
Umamaheswararao Meka

_Readable numbers _ is something which I never knew about, thanks a lot for that !!!

Collapse
 
tusharshahi profile image
TusharShahi • Edited

One more :
Swapping 2 array elements.

const arr = [1,2];
[arr[1],arr[0]] = [arr[0],arr[1]];
console.log(arr); //[2,1]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
incrementis profile image
Akin C.

Hi Tapajyoti Bose,

thank you for your article.
I already knew two of the 7 tricks when reading your article.
The other five are pretty neat in my opinion :D!

Collapse
 
vishal590 profile image
vishal

first one is called grouping integers

Collapse
 
citronbrick profile image
CitronBrick

The array length setter was really surprising.

Collapse
 
crossroadspharmacy profile image
Marian Davis

Hi! Very useful tips.
Thank you very much for sharing. 🙏
Already used some of your advises...

Collapse
 
ili profile image
iliya khoshnodi

It's great