Be At The Top Of Your Game With These 12 JavaScript Tricks

Peace Adekoya
5 min readJun 13, 2023
Photo by Walling on Unsplash

Whether you are a newbie or an experienced developer, there is always room for improvement in your coding skills. JavaScript, being one of the most popular programming languages for web development, offers a wide array of techniques and tricks that can take your development game to the next level.

This article highlights twelve JavaScript tricks that will help you become a better developer. Whether you are looking to optimize your code, write more concise and elegant solutions, or enhance your problem-solving skills, these JavaScript tricks will serve as valuable tools in your development toolkit.

Pre-requisites

  • Basic Understanding of HTML and CSS
  • Javascript basics

Destructuring Assignment

Destructuring assignment allows you to extract values from arrays or objects and assign them to variables in a concise manner. It simplifies the process of extracting and manipulating data, making your code more readable. For example:

const [first, second, …rest] = myArray;
const { name, age } = person;

Spread Syntax

The spread syntax allows you to expand an iterable (like an array or a string) into individual elements. It is handy when you need to concatenate arrays, clone objects, or pass multiple arguments to a function. Here’s an example:

const newArray = […oldArray];
const mergedArray = […array1, …array2];

Arrow Functions

Arrow functions provide a concise syntax for writing function expressions. They automatically bind the context of this and have implicit return statements for one-liner functions. Arrow functions are particularly useful when working with callbacks or in situations where lexical scoping is desired. Here’s an example:

const sum = (a, b) => a + b;

Template Literals

Template literals offer a convenient way to concatenate strings and embed expressions in JavaScript. They use backticks () instead of single or double quotes and allow multi-line strings. Template literals also support expression interpolation using ${}`. Here’s an example:

const name = 'Helen';
const message = `Hello, ${name}!`;

Optional Chaining

Optional chaining (?.) is a powerful feature that allows you to safely access nested properties of an object without causing errors if any intermediate property is null or undefined. It simplifies the process of handling potentially undefined values and prevents unnecessary error checks. For example:

const address = person?.address?.street;

Nullish Coalescing Operator

The nullish coalescing operator (??) provides a concise way to select a default value when dealing with null or undefined. It returns the right-hand side operand if the left-hand side operand is null or undefined; otherwise, it returns the left-hand side operand. Here’s an example:

const name = username ?? 'Guest';

Promises

Promises are a built-in feature of JavaScript that simplify asynchronous programming and help manage callbacks. Promises provide a cleaner and more readable way to handle asynchronous operations, making your code easier to understand and maintain. Here’s a basic example:

const fetchData = () => {
return new Promise((resolve, reject) => {
// Async operation
if (data) {
resolve(data);
} else {
reject('Error fetching data');
}
});
};

Async/Await

Async/await is like a lump of syntactic sugar on top of promises that provides a more synchronous-looking code structure while handling asynchronous operations. It allows you to write asynchronous code in a more sequential manner, making it easier to read and reason about. Here’s an example:

const fetchData = async () => {
try {
const data = await fetch('https://api.medium.com/data');
return data.json();
} catch (error) {
console.error('Error fetching data')

Object.assign()

Object.assign() is a method that copies all enumerable properties from one or more source objects to a target object. It can be used to clone objects, merge objects, or create new objects with specific properties. Object.assign() provides a more concise way to manipulate objects, reducing the need for manual property copying. Here’s an example:

const obj1 = { name: 'Helen' };
const obj2 = { age: 45 };
const obj3 = Object.assign({}, obj1, obj2);

Array Methods

JavaScript provides a rich set of array methods that simplify working with arrays. These methods include map(), filter(), reduce(), find(), and forEach(). These methods provide a more concise and efficient way to manipulate arrays, making your code more readable and performant. Here’s an example:

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((num) => num * 2);
const evenNumbers = numbers.filter((num) => num % 2 === 0);
const sum = numbers.reduce((acc, num) => acc + num, 0);

Error Handling with Try…Catch:

Error handling is an essential aspect of writing robust code. JavaScript provides the try…catch statement, which allows you to catch and handle errors gracefully. This statement is used to wrap the code that may potentially throw an exception, and if an error occurs, it is caught in the catch block. This helps prevent unhandled exceptions from crashing your application and provides a way to handle errors gracefully. Here’s an example:

try {
// Code that may throw an exception
const result = someFunction();
console.log(result);
} catch (error) {
// Handle the error
console.error('An error occurred:', error);
}

In this example, the code inside the try block is executed, and if an exception is thrown, it is caught in the catch block. You can then handle the error appropriately, whether it’s displaying an error message to the user, logging the error, or taking any other necessary action. The try…catch statement helps you identify and handle errors effectively, ensuring the smooth execution of your code.

Modules and ES6 Imports/Exports

JavaScript modules are an essential part of modern web development, allowing you to organize and encapsulate your code into reusable and maintainable units. With the introduction of ES6 modules, you can use the ‘import’ and ‘export’ statements to create modular code structures. This enables you to separate your code into multiple files, making it easier to manage and collaborate on larger projects. Here’s an example of how to use modules:

In file "math.js":
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
In file "main.js":
import { add, subtract } from './math.js';
console.log(add(5, 5)); // Output: 10
console.log(subtract(10, 8)); // Output: 2

Using modules and the import and export statements, you can create a modular and organized codebase, promote code reuse, and improve the maintainability of your JavaScript projects.

Was this guide helpful? If yes, give this post a clap, share it with your friends, and follow me for more informative guides.

--

--

Peace Adekoya

Writing engaging content (landing pages, product descriptions, sales copy, blog posts, etc.) that helps increase visibility, attract leads, clicks, conversion.