Useful JavaScript Snippets For Our Everyday Problems

Useful JavaScript Snippets For Our Everyday Problems

1. Destructing assignment

We can easily unpack values from the array and assign them to other variables using the destructing method.

No alt text provided for this image

2. One-Line if-else Statement

For simple if-else statements in JavaScript, we can use a one-line approach.

No alt text provided for this image

3. Using the spread(...) operator

The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or object into another array or object.

No alt text provided for this image

4. Destructuring Assignment with the Rest Operator

The rest operator is commonly used as a prefix to the last variable of a destructuring assignment. Let's see an example to better understand

No alt text provided for this image

The rest operator (…) tells the system to fill an array with the rest of the user-supplied data. The array is then assigned to the?otherval?variable. As a result, only...otherval?will be considered a rest variable.

5. Split String to Array

If we ever want to split a string into an array we can use the following code snippet

No alt text provided for this image

6. Nullish coalescing operator

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.

No alt text provided for this image

7. Reverse a String

The following snippet can be used to reverse any String without using a loop.

No alt text provided for this image

8. Remove duplicates

In JavaScript, there is an easy approach to getting rid of duplicates from any input array. This is very handy when there are many elements in an array and maybe there are some duplicates. we can achieve this by using Set.

No alt text provided for this image

9. String interpolation

String interpolation?is replacing placeholders with values in a string literal.

The string interpolation in JavaScript is performed by template literals (strings wrapped in backticks?`) and?${expression}?as a placeholder. For example:

No alt text provided for this image

10. Remove last character from a String

We can remove the last character of the string using the slice method.

No alt text provided for this image

Thank you for checking this article!!

if you have any snippets for developer life easy don't forget to share.

Happy Coding.....




Rafin Utshaw

Software Engineer | React, Angular, VueJS, NodeJS, Flutter

2 年

Loved it! Thanks!

要查看或添加评论,请登录

社区洞察