99% of JavaScript Developers don’t know these tricks!

Adarsh gupta
4 min readSep 29, 2023

JavaScript is a weird language, but if we dig deeper, you’ll discover that things don't simply happen out-of-the-box. There is always some rational explanation for it.

Here we will look at some of the JavaScript tricks that really come in handy at some point in time. So let's get started!

1. Proxy Objects

Proxy in JavaScript is an object that wraps another object and intercepts fundamental operations like property access, assignment, or function invocation.

const validator = {
set(target, key, value) {
if (key === 'age' && !Number.isInteger(value)) {
throw new TypeError('Age must be an integer.');
}
target[key] = value;
return true;
}
};

const person = new Proxy({}, validator);
person.age = 30; // Valid
person.age = 'thirty'; // Throws an error

Proxies are often used for tasks like data validation, logging, and implementing advanced features like lazy loading.

2. Remove white space from left and right of a string

For this, you can use the String.prototype.trimStart() and String.prototype.trimEnd() property

const text = '   Hello, world!   ';
const trimmed = text.trimStart().trimEnd();

3. Symbol Data type

Symbol data type is a unique and immutable primitive value that was introduced in ECMAScript 6 (ES6).

// Creating a symbol
const mySymbol = Symbol('description');

// Using the symbol as an object property key
const obj = {};
obj[mySymbol] = 'This is a symbol property';

// Accessing the symbol property
console.log(obj[mySymbol]); // Output: This is a symbol property

Symbols are typically used as unique keys for object properties. They are guaranteed to be unique, which means no two symbols will ever be the same, even if they have the same description (a string that can be provided when creating a symbol).

4. Using the 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.

const name = null;
const defaultName = name ?? "default";

console.log(defaultName); // "default"

The nullish coalescing operator can be used in a variety of situations to avoid errors when a variable might be null or undefined. It is an extremely useful trick that is often overlooked. But please don’t use it unless and until you know what you are doing in life, sorry I mean in JavaScript🤓

5.Web Workers for Multithreading

Web Workers enable running JavaScript in the background to improve performance.

They allow you to run JavaScript code in the background, separate from the main thread, which is the thread responsible for handling the user interface (UI) and user interactions.

//main.js
// Creating a Web Worker
const worker = new Worker('worker.js');

// Sending data to the worker
worker.postMessage({ data: 'To be processed' });

// Listening for messages from the worker
worker.onmessage = (e) => {
const result = e.data;
console.log('Result from worker:', result);
};

//worker.js
// Listening for messages from the main thread
self.onmessage = (e) => {
const inputData = e.data.data;

// Perform some time-consuming task
const result = processData(inputData);

// Sending the result back to the main thread
self.postMessage(result);
};

function processData(data) {
// Perform data processing here
return data.toUpperCase();
}

6. Using the spread operator (…)

This is right now a relatively old trick, but really comes handy at some point.

The spread operator (…) is an operator that can be used to spread the elements of an array or object into a list.

const array1 = [1, 2, 3];

console.log(...array1); // 1 2 3

7. Function Currying

Function currying and partial application are techniques that allow you to create new functions from existing functions with fewer arguments.

// Currying function for calculating the total price
function calculateTotal(price) {
return function(tax) {
return function(quantity) {
return price * quantity * (1 + tax);
};
};
}

// Create a curried function for a specific product
const calculateTotalForProduct = calculateTotal(10.99); // Set the base price

// Calculate the total price for a specific product with 8% tax and 3 quantity
const total = calculateTotalForProduct(0.08)(3);
console.log(`Total Price: $${total.toFixed(2)}`);

If you found this useful, be sure to like and share. What lesser-known JavaScript tips do you use? Let me know in the comments!

Conclusion

We have looked into some lesser-known tricks in JavaScript that can save you time and boost productivity:

  • Proxy Objects
  • Remove white space from left and right of a string
  • Symbol Data type
  • Using the nullish coalescing operator (??)
  • Web Workers for Multithreading
  • Using the spread operator (…)
  • Function Currying

Thanks for reaching this far, you are a fantastic reader!

If you are an aspiring Frontend developer, checkout this Tailwind CSS E-book. Worth a shot.

Follow me here

as well as on Twitter.

--

--

Adarsh gupta

Software Engineer | JavaScript developer | Technical Writer . Work with me? adarshguptaworks@gmail.com Connect with me? twitter.com/adarsh____gupta/