DEV Community

FADHILI Josue
FADHILI Josue

Posted on

11 JavaScript Tricks You Probably Didn't Know About

JavaScript is a versatile language with a myriad of features and quirks. While many developers are familiar with the basics, there are some lesser-known tricks that can enhance your coding prowess. In this article, we'll explore 11 JavaScript tricks that might surprise you and prove useful in your development journey.

1. Destructuring with Aliases

const person = { firstName: 'John', lastName: 'Doe' };
const { firstName: first, lastName: last } = person;
console.log(first); // Output: John
console.log(last); // Doe
Enter fullscreen mode Exit fullscreen mode

2. Converting Strings to Numbers

This concise trick converts a string to a number using the unary plus operator. It's a concise alternative to parseInt() or Number().

const num = +"42";
console.log(typeof(num)) // number
console.log(+"asdf") // NaN

Enter fullscreen mode Exit fullscreen mode

3. Numeric Separators

You can now easily separate numbers with just an _ . This will make life of developers working with large numbers more easier.

//old syntax
let number = 1243134123

//new syntax
let number = 1_243_134_123
console.log(number) // 1243134123
Enter fullscreen mode Exit fullscreen mode

4. Get unique values from an array

We can extract unique values from an array i.e removing duplicate values in an array by simply using the Set object and Spread operator.

let array_values = [1, 3, 3, 4, 5, 6, 6, 6,8, 4, 1]
let unique_values = [...new Set(array_values )];
console.log(unique_values );
// [1,3, 4, 5, 6, 8]
Enter fullscreen mode Exit fullscreen mode

5. Swapping Variables

This one-liner elegantly swaps the values of two variables. It leverages array destructuring to achieve a simple and readable swap operation.

// longhand
let a = 10;
let b = 20;

// Swapping variables using a temporary variable
let temp = a;
a = b;
b = temp;

console.log(a, b); // Output: 20 10


// shorthand
let a = 10;
let b = 20;

[a, b] = [b, a];

console.log(a, b); // Output: 20 10
Enter fullscreen mode Exit fullscreen mode

6.Shuffling an Array

A quick way to shuffle the elements of an array.

const array = [23,3,34,3454,5,435,4343,33,343,3];
const shuffledArray = array.sort(() => Math.random() - 0.5); // [ 435, 23, 3454, 3, 33, 5, 3, 343, 34, 4343 ]
// you may get a different shuffle from mine because it is made randomly

Enter fullscreen mode Exit fullscreen mode

7.Optional Chaining (Nullish Coalescing Operator)

Safely access nested properties without worrying about null or undefined.

const value = obj?.prop ?? 'default';
Enter fullscreen mode Exit fullscreen mode

8. Using Function.prototype.bind()

this is a method available on all JavaScript functions. It allows you to create a new function with a fixed this value and possibly pre-set arguments

const module = {
  x: 42,
  getX: function () {
    return this.x;
  },
};

const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// Expected output: undefined

const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// Expected output: 42
Enter fullscreen mode Exit fullscreen mode

Partial Function Application

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

const add2 = add.bind(null, 2);

const result = add2(3); // Output: 5
Enter fullscreen mode Exit fullscreen mode

Partially apply functions for more flexible code. In this example, add2 is a new function that always adds 2 to its argument.

9.Detecting the Environment (Browser or Node.js)

const isBrowser = typeof window !== 'undefined';
const isNode = typeof process !== 'undefined' && process.versions && process.versions.node;
Enter fullscreen mode Exit fullscreen mode

10. Currying Functions

Currying is a functional programming technique that allows you to transform a function with multiple arguments into a sequence of functions, each taking a single argument. This can make functions more flexible and composable.

code examples:

Example 1: Basic Currying

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

const add2 = add(2);
const result = add2(3); // Output: 5
Enter fullscreen mode Exit fullscreen mode

In this example, we have a add function that takes one argument a and returns a function that takes another argument b. This inner function adds a and b. When add(2) is called, it returns a new function add2 which adds 2 to any value passed to it.

Example 2: Currying with Multiple Arguments

const multiply = (a) => (b) => (c) => a * b * c;

const multiplyByTwo = multiply(2);
const multiplyByTwoAndThree = multiplyByTwo(3);
const result = multiplyByTwoAndThree(4); // Output: 24
Enter fullscreen mode Exit fullscreen mode

Example 3: Real-world Use Case (Formatting Dates)

const formatDate = (format) => (date) => {
  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  const day = date.getDate();
  const month = months[date.getMonth()];
  const year = date.getFullYear();

  switch (format) {
    case 'dd-mm-yyyy':
      return `${day}-${month}-${year}`;
    case 'mm-dd-yyyy':
      return `${month}-${day}-${year}`;
    case 'yyyy-mm-dd':
      return `${year}-${month}-${day}`;
    default:
      return 'Invalid format';
  }
};

const formatAsDdMmYyyy = formatDate('dd-mm-yyyy');
const formattedDate = formatAsDdMmYyyy(new Date()); // e.g., Output: '07-Nov-2023'

Enter fullscreen mode Exit fullscreen mode

In this example, formatDate is a curried function that takes a format argument and returns a function that takes a date argument. It formats the date based on the provided format. This allows for easy reuse of the formatting function with different formats.

11. Promise.all() for Parallel Execution

Using Promise.all() for parallel execution is a technique in JavaScript that allows you to concurrently run multiple asynchronous tasks and handle their results collectively. This is particularly useful when you have a set of independent asynchronous operations that can be executed simultaneously for improved performance.

const fetchUserData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const user = { id: 1, name: 'John Doe' };
      resolve(user);
    }, 2000); // Simulating an asynchronous operation
  });
};

const fetchPosts = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const posts = [{ id: 1, title: 'Post 1' }, { id: 2, title: 'Post 2' }];
      resolve(posts);
    }, 1500); // Simulating an asynchronous operation
  });
};

const fetchComments = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const comments = [{ id: 1, text: 'Comment 1' }, { id: 2, text: 'Comment 2' }];
      resolve(comments);
    }, 1000); // Simulating an asynchronous operation
  });
};

Promise.all([fetchUserData(), fetchPosts(), fetchComments()])
  .then(([userData, posts, comments]) => {
    console.log('User Data:', userData);
    console.log('Posts:', posts);
    console.log('Comments:', comments);
  })
  .catch(error => {
    console.error('Error:', error);
  });
Enter fullscreen mode Exit fullscreen mode

conclusion

Thank you for making it to the end! 🎉 i think you found this article insightful, and if so please share it to other people who can find it useful. Feel free to give a suggestion or send me a message on twitter or Linkedin.

Top comments (6)

Collapse
 
dionarodrigues profile image
Diona Rodrigues

I really like this type of article. Sometimes we tend to think that we need a complex solution when some simple and ready-to-use technique can solve our problem.

Collapse
 
fadhilijosue profile image
FADHILI Josue

thank you @dionarodrigues

Collapse
 
wraith profile image
Jake Lundberg

nice list of tips! 😃 i always forget about the + to parse a string to a number lol

Collapse
 
kirilldedeshin profile image
Kirill Dedeshin

Good list of tips! Thanks a lot

Collapse
 
fadhilijosue profile image
FADHILI Josue

my pleasure @wraith

Collapse
 
qubyte7 profile image
MUGISHA SHAMI INNOCENT

nice article, it's to helpfull