12 JavaScript Snippets You Should Know For Everyday Use


We are going to cover 12 useful JavaScript snippets for web developers in this article. The information you learn here will make your development process faster and save you time!Destructing assignment
The destructing method of JavaScript allows you to unpack values from an array into other variables.


1. Destructing assignment

In JavaScript, you can use destructing method to unpack values from an array and assign them to other variables.

// Destructive Assignment
const data = ["Paul", "too old", "Software Engineer"]
const [name, age, job_title] = data

console.log(name, age, job_title) // Paul too old Software Engineer

2. Locate an object in an array

An array can be searched using the JavaScript find() method to find a specific object.

// Find an object in Array
const employess = [
    {name: "Paul", job_title: "Software Engineer"},
    {name: "Peter", job_title: "Web Developer"},
    {name: "Harald", job_title: "Screen Designer"},
let sen = employess.find(data => data.job_title === "Software Engineer")

console.log(sen) // { name: 'Paul', job_title: 'Software Engineer' }

3. How to reverse a string

You can reverse any String with the following snippet without using a loop.

// Reverse a String
const reverse = (input) => {
    return input.split("").reverse().join("");

console.log(reverse("Paul Knulst")) // tslunK luaP
console.log(reverse("Medium is awesome")) // emosewa si muideM

4. Inserting placeholders in template literals

The $[] method is used to include variables in Strings when you use template literals.

// Placeholder in Strings
let placeholder1 = "Engineer";
let placeholder2 = "Developer";

console.log(`I'm a Software ${placeholder1}`); // I'm a Software Engineer
console.log(`I'm a Software ${placeholder2}`); // I'm a Software Developer

5. One-Line if-else Statement

Using one line of code to execute an if-else statement in JavaScript is easy.

// One-Line if-else Statement

// normal
if (13 > 37) {
} else {
// One liner
13 > 37 ? console.log(true) : console.log(false)

6. Getting Rid of Duplicates

An easy way to remove duplicates from an array in JavaScript can be found here. In arrays where there are many elements and possibly duplicates, this can be very useful. The following snippet will show how to use the Set data type to achieve this.

// Get Rid of Duplicates
function removeDuplicates(array) {
    return [...new Set(array)];

const uniqueStr = removeDuplicates(["Paul", "John", "Harald", "Paul", "John"])
const uniqueNr = removeDuplicates([1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 9])
console.log(uniqueStr) // [ 'Paul', 'John', 'Harald' ]
console.log(uniqueNr) // [1, 2, 3, 4, 5, 6, 7, 9]

7. Split string into arrays

The following code snippet can be used to split a string into an array.

// Split String to Array
const randomString = "Software"
const newArray = [...randomString]

console.log(newArray) // ['S', 'o', 'f', 't', 'w', 'a', 'r', 'e']

8. Capture Right Click

If you are using JavaScript and would like to capture the right click of the user to execute some code.

// Capture Right Click
// only usable in HTML/JS
window.oncontextmenu = () => {console.log("Right Click is Pressed!")}

9. Looping through Keys and Values

To iterate over keys (or values) of dictionary data, this code snippet is useful. It is possible to accomplish this using the forEach function and retrieving the keys and values.

// Looping through Keys and Values
const programming_languages = {JavaScript: 1, Kotlin: 2, Python: 3};
Object.keys(programming_languages).forEach((key) => {
// JavaScript
// Kotlin
// Python
Object.values(programming_languages).forEach((key) => {
// 1
// 2
// 3

10. Smart data filtering

JavaScript’s built-in Filter method allows you to filter your data. When you have a large input array and you only require specific data from it, then this is important.

// Smart Data Filteration
const jobs = ["Frontend Developer", "Backend Developer", "Data Scientist", "Teacher"]
const filtered_jobs1 = jobs.filter(data => data.length < 10)
const filtered_jobs2 = jobs.filter(data => data.includes("Developer"))

console.log(filtered_jobs1) // [ 'Teacher' ]
console.log(filtered_jobs2) // [ 'Frontend Developer', 'Backend Developer' ]

11. Nullish coalescing operator

If its left-hand operand is null or undefined, the nullish coalescing operator (??) returns the right-hand operand, and otherwise it returns the left-hand operand.

// Nullish coalescing operator
const foo = null ?? 'default string';
const baz = 0 ?? 42;

console.log(foo); // default string
console.log(baz); // 0

12. Handling errors

Errors happen during the development process of a program. Use a try-catch statement In Programming, there are always Errors that happen during development. Try-catch statements can help you avoid program crashes. The runtime error catching syntax is well-established in all programming languages.

// Error Handling
function getRectArea(width, height) {
    if (isNaN(width) || isNaN(height)) {
        throw 'Parameter is not a number!';

try {
    getRectArea(3, "A")
} catch (err) {
    console.log(`There was an error: ${err}`)
} finally {
    console.log("This code block is executed regardless of try/catch results")
// Output:
// There was an error: Parameter is not a number!
// This code block is executed regardless of try/catch results

Closing Notes

You can use some of the snippets in this article during your development. I really hope you find it helpful. Please share any JavaScript snippets you have with other developers in the comments.


Post a Comment (0)
Previous Post Next Post