JavaScript Arrow Functions and Template Literals
Arrow functions and template literals are two of the most impactful features introduced in ES6 (2015). They make JavaScript code shorter, cleaner, and more readable.
Arrow Functions
Arrow functions provide a compact alternative to traditional function expressions. They use the => (fat arrow) syntax and are commonly used in modern JavaScript for callbacks, array methods, and more.
Traditional Function vs Arrow Function
// Traditional function expression
const add = function(a, b) {
return a + b;
};
// Arrow function — same logic, shorter syntax
const add = (a, b) => {
return a + b;
};
// Even shorter — implicit return for single expressions
const add = (a, b) => a + b;
console.log(add(3, 7)); // 10Arrow Function Syntax Rules
One parameter — parentheses are optional:
const square = num => num * num;
console.log(square(5)); // 25No parameters — empty parentheses required:
const sayHello = () => console.log("Hello!");
sayHello(); // Hello!Multiple lines — use curly braces and explicit return:
const calculateBill = (price, tax) => {
let taxAmount = price * tax;
let total = price + taxAmount;
return total;
};
console.log(calculateBill(1000, 0.18)); // 1180Returning an object — wrap it in parentheses:
const createUser = (name, age) => ({ name: name, age: age });
console.log(createUser("Tara", 24)); // { name: "Tara", age: 24 }Arrow Functions with Array Methods
Arrow functions shine when used with array methods like map, filter, and reduce.
let numbers = [1, 2, 3, 4, 5];
// Double each number
let doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// Get only even numbers
let evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]The this Keyword in Arrow Functions
The most important difference between arrow functions and regular functions is how they handle this. Arrow functions do not have their own this — they inherit this from the surrounding code where they are defined.
// Problem with regular function — "this" refers to the wrong context
function Timer() {
this.seconds = 0;
setInterval(function() {
this.seconds++; // "this" here refers to the global object, not Timer!
console.log(this.seconds); // NaN or undefined
}, 1000);
}
// Solution with arrow function — "this" is inherited from Timer
function Timer() {
this.seconds = 0;
setInterval(() => {
this.seconds++; // "this" correctly refers to Timer
console.log(this.seconds); // 1, 2, 3, ...
}, 1000);
}When NOT to Use Arrow Functions
- As object methods —
thiswill not refer to the object - As event handlers when
thisneeds to refer to the element - As constructors — arrow functions cannot be used with
new
// Wrong: arrow function as an object method
const person = {
name: "Ajay",
greet: () => {
console.log("Hello, " + this.name); // "this" is undefined here
}
};
// Correct: regular method
const person = {
name: "Ajay",
greet() {
console.log("Hello, " + this.name); // "this" correctly refers to person
}
};
person.greet(); // Hello, AjayTemplate Literals
Template literals (also called template strings) are string literals defined with backticks ` `. They offer a powerful and clean way to work with strings.
Embedding Expressions with ${}
Variables and expressions can be directly embedded in strings using ${ }.
// Old way
let name = "Sunita";
let age = 28;
let message = "Hello, my name is " + name + " and I am " + age + " years old.";
// Modern way with template literal
let message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message);
// Hello, my name is Sunita and I am 28 years old.Expressions Inside ${}
Any JavaScript expression can go inside ${ } — calculations, function calls, ternary operators.
let a = 10, b = 20;
console.log(`Sum of ${a} and ${b} is ${a + b}.`);
// Sum of 10 and 20 is 30.
let price = 1200;
let tax = 0.18;
console.log(`Total with tax: ₹${price + price * tax}`);
// Total with tax: ₹1416
let isVIP = true;
console.log(`Status: ${isVIP ? "VIP Member" : "Regular Member"}`);
// Status: VIP MemberMulti-line Strings
Template literals preserve line breaks without needing \n escape characters.
// Old way
let oldMsg = "Line 1\nLine 2\nLine 3";
// Template literal way
let newMsg = `Line 1
Line 2
Line 3`;
console.log(newMsg);
// Line 1
// Line 2
// Line 3Building HTML Strings
Template literals are especially useful for building HTML snippets dynamically.
let productName = "Wireless Speaker";
let productPrice = 2499;
let inStock = true;
let html = `
<div class="product">
<h3>${productName}</h3>
<p>Price: ₹${productPrice}</p>
<p>Status: ${inStock ? "In Stock" : "Out of Stock"}</p>
</div>
`;
console.log(html);Tagged Template Literals (Advanced)
A tagged template literal is a function that processes a template literal. The tag function receives the string parts and values separately.
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
return result + str + (values[i] !== undefined ? `[${values[i]}]` : "");
}, "");
}
let item = "Laptop";
let price = 55000;
let message = highlight`The ${item} costs ₹${price}.`;
console.log(message);
// The [Laptop] costs ₹[55000].Arrow Functions vs Regular Functions — Quick Reference
| Feature | Regular Function | Arrow Function |
|---|---|---|
| Syntax | function() {} | () => {} |
| this binding | Has its own this | Inherits this from outer scope |
| arguments object | Available | Not available |
| Can be constructor | Yes | No |
| Best for | Methods, constructors | Callbacks, array methods |
Practical Example — Report Generator
const generateReport = (students) => {
return students.map(student => {
let grade = student.score >= 90 ? "A" :
student.score >= 75 ? "B" :
student.score >= 60 ? "C" : "F";
return `${student.name} scored ${student.score} — Grade: ${grade}`;
});
};
let students = [
{ name: "Meena", score: 92 },
{ name: "Karan", score: 75 },
{ name: "Deepak", score: 58 }
];
let report = generateReport(students);
report.forEach(line => console.log(line));
// Meena scored 92 — Grade: A
// Karan scored 75 — Grade: B
// Deepak scored 58 — Grade: FKey Points to Remember
- Arrow functions use
=>and provide a shorter syntax than regular functions - If the function has a single expression, curly braces and
returncan be omitted - Arrow functions do not have their own
this— they inherit it from the surrounding scope - Do not use arrow functions as object methods or constructors
- Template literals use backticks and allow embedding expressions with
${ } - Template literals support multi-line strings naturally without escape characters
- Template literals are perfect for building dynamic HTML strings
