Write Clean JS with Destructuring & Template Literals


Ever feel like writing JavaScript can be a bit... messy? Especially when you're trying to grab specific pieces of information from an array or an object, or when you're trying to build sentences that mix text with changing information, like names or prices? For example, maybe you've written code that looks like this:
const user = {
name: "Hardik",
age: 23
}
const userName = user.name;
const message = 'Hello, ' + name + '! Your total is ' + total + '.';
It works, but it can quickly become difficult to read, manage, and, honestly, not very enjoyable to write.
Good news! Modern JavaScript has some clever tools that fix these problems. In this blog post, we'll explore two outstanding features: Destructuring and Template Literals. They will help you write JavaScript that's much neater, easier to understand, and even more enjoyable to work with.
Destructuring in JavaScript: Picking Out What You Need
Imagine you have a big box of chocolates (that's your data, like a list or an item). Instead of dumping the whole box out and finding the ones you want, what if you could just reach in and pick out only the specific chocolates you're craving?
That's what Destructuring does in JavaScript. It’s just a syntactical sugar and a quick way to extract specific values from arrays or objects and put them into their own easy-to-use variable. It saves you from writing repetitive code and makes your program much easier to read.
Array Destructuring
Array destructuring lets you grab items from an array and give them their own names, just by matching their position in the list.
Basic Destructuring
const arr = ["Hardik", "Pankaj"]
// The old way:
// const name1= arr[0];
// const name2= arr[1];
const [name1, name2] = arr;
console.log(name1); // Output: Hardik
console.log(name2);// Output: Pankaj
// Here we are extractiing values based on the position of the element
Skipping Elements → Don't need all the items? No problem! Just leave a space where the item would be.
const fruits = ["apple", "banana", "cherry", "date"];
const [, , thirdFruit] = fruits; // We skip the first two with empty commas
console.log(thirdFruit); // Shows: cherry
Grabbing "The Rest" (...rest) → Sometimes you want a few specific items, and then everything else that's left over. The three dots (...) can help here.
const numbers = [10, 20, 30, 40, 50];
const [first, second, ...remainingNumbers] = numbers;
console.log(first); // Shows: 10
console.log(second); // Shows: 20
console.log(remainingNumbers); // Shows: [30, 40, 50] (a new list with the rest)
Giving Default Values → What if you try to grab an item that isn't there? You can tell JavaScript what to use instead, just in case.
const settings = ["dark-theme"];
// fontSize isn't in 'settings', so it uses '16px' by default
const [theme, fontSize = "16px"] = settings;
console.log(theme); // Shows: dark-theme
console.log(fontSize); // Shows: 16px
const userPrefs = []; // An empty list
const [language = "en", country = "US"] = userPrefs; // Both get default values
console.log(language); // Shows: en
console.log(country); // Shows: US
Swapping Two Things Easily → This is a neat trick! You can swap values between two variables without needing an extra temporary variable.
let a = 5;
let b = 10;
console.log(`Before swap: a = ${a}, b = ${b}`); // Shows: Before swap: a = 5, b = 10
[a, b] = [b, a]; // Swaps the values!
console.log(`After swap: a = ${a}, b = ${b}`); // Shows: After swap: a = 10, b = 5
Object Destructuring
Object destructuring lets you pull out specific pieces of information (properties) from an item (object).
const user = {
id: 1,
firstName: "Alice",
lastName: "Smith",
age: 30,
};
// The old way:
// const userId = user.id;
// const userFirstName = user.firstName;
// The new, neat way with Destructuring:
const { id, firstName, age } = user;
console.log(id); // Shows: 1
console.log(firstName); // Shows: Alice
console.log(age); // Shows: 30
// if the variable name seems to be long or any other case in which you want to use different name
// you can do it like this
const { id, firstName: fName, lastName: lName} = user;
console.log(id); // Shows: 1
console.log(fName); // Shows: Alice
console.log(lName; // Shows: Smith
Giving Default Values for Missing Properties → You can set a default value if a property isn't found in your item.
const config = {
theme: "dark",
};
// 'backgroundColor' isn't in 'config', so it gets 'white' by default
const { theme, backgroundColor = "white", debugMode = false } = config;
console.log(theme); // Shows: dark
console.log(backgroundColor); // Shows: white
console.log(debugMode); // Shows: false
Picking from Nested Items (Objects inside Objects) → If your item has other items inside it, you can pick parts from those too, all in one go.
const userProfile = {
userId: 456,
name: "Bob",
address: { // This is an object inside userProfile
street: "123 Main St",
city: "Anytown",
zip: "12345",
},
};
// We grab 'name', and then from 'address', we grab 'street' and 'city'.
const {
name,
address: { street, city },
} = userProfile;
console.log(name); // Shows: Bob
console.log(street); // Shows: 123 Main St
console.log(city); // Shows: Anytown
// console.log(address); // Error! 'address' itself wasn't made a variable.
Why Use Destructuring?
Easier Data from Websites (APIs): When you get a lot of data from a website, destructuring helps you quickly pick out the important parts.
Looks Neater: Your code becomes much easier to read because you're directly naming what you're picking out.
Less Typing: You write less code to do the same job!
Understanding Template Literals: A Better Way to Build (Strings)
Remember how you used to build sentences in JavaScript? It often involved lots of + signs and " or ' quotes, especially if you had to include different pieces of information or if your sentence went over several lines.
// The old, clunky way to build a sentence:
const product = "Laptop";
const price = 1200;
const taxRate = 0.08;
const message =
"Your order for " + product +" costs $" + price +".\n" + // '\n' makes a new line
"Applicable tax: $" + price * taxRate + ".\n" +
"Total price: $" + (price + price * taxRate) +".";
console.log(message);
// Output
// Your order for Laptop costs $1200.
// Applicable tax: $96.
// Total price: $1296.
Introducing Template Literals
Template literals are introduced in modern JavaScript. These are a much better way to create strings. Instead of using single or double quotes (‘ ‘ or “ “), we can use backticks (` `) to wrap the sentence. These backticks let you do two really cool things: write sentences over many lines and easily inject variables into the string.
// The new, neat way with Template Literals:
const product = "Laptop";
const price = 1200;
const taxRate = 0.08;
const message = `Your order for ${product} costs $${price}.
Applicable tax: $${price * taxRate}.
Total price: $${price + price * taxRate}.`; // See how much cleaner this is!
console.log(message);
/* The output exactly same as above but more cleaner, easy to read and understand this is what
Template literals gives us
Your order for Laptop costs $1200.
Applicable tax: $96.
Total price: $1296.*/
Sentences Over Many Lines → With backticks, you can simply press Enter in your code, and the new line will appear in your sentence. No more \n.
const poem = `Roses are red, Violets are blue, Modern JavaScript Is awesome, too!`; console.log(poem); /* This will print: Roses are red, Violets are blue, Modern JavaScript Is awesome, too! */
Dropping in Information (String Interpolation) → This is the super powerful part and most used. You can inject variables or even simple math calculations directly into your sentence! Just wrap them in ${}
const name = "Alice"; const greeting = `Hello, ${name}!`; // We put the 'name' variable directly in! console.log(greeting); // Shows: Hello, Alice! const num1 = 5; const num2 = 7; // We do the math right inside the sentence! console.log(`The sum is ${num1 + num2}.`); // Shows: The sum is 12. function getFullName(first, last) { return `${first} ${last}`; } // We even call a function inside the sentence! console.log(`User: ${getFullName("John", "Doe")}`); // Shows: User: John Doe
Why Use Template Literals? (Benefits)
Much Easier to Read: Your code for building sentences looks exactly like the sentence itself. No more guessing what the final text will be!
Fewer Mistakes: Less chance of accidentally missing a + sign or a quote.
Simple to Update: If your sentence needs to change, it's easy to see where everything is.
Variables: It is very easy to inject variables by using just a ${} directly into the string.
Conclusion
You've just learned two incredibly useful modern JavaScript tools that will make your coding life much easier
Destructuring is your go-to for neatly picking out specific pieces of information from lists and items, cutting down on messy code.
Template Literals are your new best friend for building strings and sentences. They make your text much clearer and let you drop in changing information with ease.
Now that you’re writing cleaner syntax, it’s time to handle data smarter, too.
Next Blog on: Spread, Rest, Map, and Set – stay tuned!
Subscribe to my newsletter
Read articles from Hardik Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Hardik Kumar
Hardik Kumar
👨💻 Full Stack Developer | MERN & Beyond | Generative AI Enthusiast As a Full Stack Developer, I specialize in building modern, scalable web applications using the MERN stack and beyond. During my previous internship roles, I contributed to both frontend and backend development on real-world projects, working with technologies like React, Node.js, and microservices-based architectures. With a BTech in Computer Science, I’ve built a strong foundation in programming and software development. I'm passionate about continuous learning and personal growth — and I document my journey as I explore new technologies, sharpen my skills, and strive to become a better engineer every day.