DEV Community

Cover image for 10 Mind-Blowing JavaScript Tricks Every Developer Should Know
Mene.tech
Mene.tech

Posted on • Edited on

10 Mind-Blowing JavaScript Tricks Every Developer Should Know

JavaScript is an incredibly versatile and powerful programming language that continues to evolve and amaze developers with its capabilities. Whether you're a pro JavaScript developer or just starting your journey, it's always beneficial to learn new tricks that can enhance your coding skills and make your projects more efficient.

In this article, we'll explore 10 mind-blowing JavaScript tricks with examples that every developer should know. Let's dive in!

Destructuring Assignment:

The destructuring assignment allows you to extract values from arrays or objects and assign them to variables in a concise way. It's a powerful technique that simplifies your code and improves readability.

// Example with arrays
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3

// Example with objects
const person = { name: 'John', age: 30 };
const { name, age } = person;
console.log(name); // Output: John
console.log(age); // Output: 30

Enter fullscreen mode Exit fullscreen mode

Default Parameters:

JavaScript allows you to set default values for function parameters. This feature is particularly useful when you want to handle missing or undefined values without writing extra code.

function greet(name = 'Anonymous') {
  console.log(`Hello, ${name}!`);
}

greet(); // Output: Hello, Anonymous!
greet('Alice'); // Output: Hello, Alice!
Enter fullscreen mode Exit fullscreen mode

Spread Syntax:
The spread syntax (three dots: ...) can be used to expand elements of an array or object. It's handy for tasks like merging arrays, creating copies, and passing multiple arguments to a function.

// Example with arrays
const numbers = [1, 2, 3];
const newArray = [...numbers, 4, 5];
console.log(newArray); // Output: [1, 2, 3, 4, 5]

// Example with objects
const person = { name: 'John', age: 30 };
const newPerson = { ...person, occupation: 'Developer' };
console.log(newPerson); // Output: { name: 'John', age: 30, occupation: 'Developer' }
Enter fullscreen mode Exit fullscreen mode

Object Shorthand:

With object shorthand notation, you can create objects in a more concise way by omitting redundant key-value assignments. This technique makes your code cleaner and easier to maintain.

const name = 'John';
const age = 30;

// Without object shorthand
const person = {
  name: name,
  age: age
};

// With object shorthand
const person = { name, age };
console.log(person); // Output: { name: 'John', age: 30 }
Enter fullscreen mode Exit fullscreen mode

Arrow Functions:

Arrow functions provide a shorter syntax for writing function expressions. They inherit the "this" value from the enclosing context, making them especially useful for event handlers and callbacks.

// Regular function
function add(a, b) {
  return a + b;
}

// Arrow function
const add = (a, b) => a + b;

console.log(add(2, 3)); // Output: 5

Enter fullscreen mode Exit fullscreen mode

Promises and Async/Await:

Promises and async/await are powerful features for handling asynchronous operations in JavaScript. They allow you to write more readable and maintainable asynchronous code compared to traditional callback-based approaches.

// Promises
const fetchData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Data fetched successfully!');
    }, 2000);
  });
};

fetchData()
  .then(data => console.log(data)) // Output: Data fetched successfully!
  .catch(error => console.error(error));

// Async/Await
const fetchDataAsync = async () => {
  try {
    const data = await fetchData();
    console.log(data); // Output: Data fetched successfully!
  } catch (error) {
    console.error(error);
  }
};

fetchDataAsync();
Enter fullscreen mode Exit fullscreen mode

Template Literals:

Template literals provide a convenient way to concatenate strings and include dynamic variables. They support multi-line strings and can be tagged with functions for advanced string manipulation.

const name = 'John';
const age = 30;

const message = `My name is ${name} and I'm ${age} years old.`;
console.log(message); // Output: My name is John and I'm 30 years old.
Enter fullscreen mode Exit fullscreen mode

Array Methods (Map, Filter, Reduce):

JavaScript's array methods like map, filter, and reduce are incredibly useful for manipulating arrays. They enable you to perform complex operations on arrays with concise and expressive const numbers = [1, 2, 3, 4, 5];

// Map
const squaredNumbers = numbers.map(num => num ** 2);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

// Filter
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]

// Reduce
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 15
Enter fullscreen mode Exit fullscreen mode

DRY (Don't Repeat Yourself) with Higher-Order Functions:

Higher-order functions like map, filter, and reduce can help you follow the DRY principle by reducing code duplication. They allow you to encapsulate common operations and apply them to different data sets.

const numbers = [1, 2, 3, 4, 5];

// Duplicated code
const squaredNumbers = [];
for (let i = 0; i < numbers.length; i++) {
  squaredNumbers.push(numbers[i] ** 2);
}
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

// Using higher-order function (map)
const squaredNumbers = numbers.map(num => num ** 2);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

Modules and ES6 Imports/Exports:

ES6 introduced a module system in JavaScript, making it easier to organize and share code between different files. By using imports and exports, you can create modular and maintainable codebases.

// module.js
export const greet = name => console.log(`Hello, ${name}!`);

// main.js
import { greet } from './module.js';

greet('John'); // Output: Hello, John!
Enter fullscreen mode Exit fullscreen mode

JavaScript is a powerful language with numerous features and tricks that can significantly improve your development workflow.

By mastering these 10 mind-blowing JavaScript tricks, you'll become a more efficient and effective developer. Happy coding!

Remember, the JavaScript tricks mentioned in this article are just the tip of the iceberg.

Keep exploring, experimenting JavaScript ecosystem to become a JavaScript ninja!

Top comments (12)

Collapse
 
maxart2501 profile image
Massimo Artizzu

These "tricks" all marked as "1." are actually basic JavaScript syntax that's been available for years, except the one about DRY that has actually nothing to do with duplicated code.

AI slop is slop.

Collapse
 
mene_demogul profile image
Mene.tech

Totally fair. These aren’t some deep hacks, just basic JavaScript stuff that a lot of us (me included) forget or overlook when we’re learning. And yeah, DRY isn’t just about using map, but things like that help reduce the same repetitive loop logic everywhere.
I actually wrote this draft in 2023 and just posted it without thinking much of it. Didn’t expect it to get more than 50 views, but here we are.

But hey, if it’s AI slop, at least the slop’s got reach

Collapse
 
mene_demogul profile image
Mene.tech • Edited

I’ve also corrected the numbering, honestly something I overlooked. Maybe my headline was a little overboard too
And just to say, I’m a big supporter of AI, but calling my post "AI slop" is a stretch. Maybe go with more constructive criticism next time?

You said the code has nothing to do with DRY, but I’d disagree. The whole point of DRY (Don't Repeat Yourself) is to avoid writing the same logic over and over and that includes patterns like looping and pushing inside arrays manually. Using map, filter, or reduce helps encapsulate that logic in a cleaner, reusable way.

// Repetitive pattern
const squaredNumbers = [];
for (let i = 0; i < numbers.length; i++) {
  squaredNumbers.push(numbers[i] ** 2);
}

// DRY version
const squaredNumbers = numbers.map(num => num ** 2);

Enter fullscreen mode Exit fullscreen mode

It’s literally the same result, but the second approach is less code, less repetition, and more readable. That’s a textbook DRY improvement not just about copy-pasting blocks, but reducing repeated patterns.

Not saying it's revolutionary, but to say it has "nothing" to do with DRY feels like a reach.

Thread Thread
 
escornwell profile image
Eric Cornwell

I think there's room for semantic disagreement there. But to me this is more an example of imperative vs. declarative implementations.

Thread Thread
 
mene_demogul profile image
Mene.tech

That’s fair. It’s definitely more declarative than imperative. But I’d still argue it touches DRY too, since you’re reducing repeated logic patterns. Maybe it sits in both worlds. Appreciate the perspective though!

Collapse
 
strange_dev profile image
Abdulbasit Alabi
const watched = new Proxy({}, {
  get(target, prop) {
    console.log(`Accessing ${prop}`);
    return target[prop];
  },
  set(target, prop, value) {
    console.log(`Setting ${prop} = ${value}`);
    target[prop] = value;
    return true;
  }
});
watched.name = 'Basit'; // Logs: Setting name = Basit
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mene_demogul profile image
Mene.tech

This is clean. I love how you used Proxy to log property access and updates. Super handy for debugging or even building out simple reactivity. Appreciate you dropping this here.

Collapse
 
leob profile image
leob

LOL "mind blowing tricks" - all of this is just elementary ES6 basics ... and what's with the "numbering"? If you're not able or willing to get the numbering right, then maybe stick with unnumbered bullet points ;-)

Collapse
 
mene_demogul profile image
Mene.tech

Thank you for your input🙂🙏

Collapse
 
strange_dev profile image
Abdulbasit Alabi
Array.prototype.last = function () {
  return this[this.length - 1];
};
[1, 2, 3].last(); // this would give 3
Enter fullscreen mode Exit fullscreen mode

This patching built-ins

Collapse
 
mene_demogul profile image
Mene.tech

I like this , makes the code feel way cleaner. I’m usually a bit cautious with patching built-ins, but for quick scripts or personal projects, this hits. Thank you so much for your inputs means a lot🙏

Collapse
 
strange_dev profile image
Abdulbasit Alabi

Really?