Modern JavaScript (ES6+)
ES6 ne JavaScript ko cleaner, more expressive aur large applications ke liye easier banaya. Is chapter me modern syntax ko practical examples ke saath samjhenge — bina unnecessary shortcuts ke.
What does ES6+ mean?
ES6 is the popular name for ECMAScript 2015, a major JavaScript language update. The + means later ECMAScript releases too, because modern JavaScript continues to add useful language features.
ES6 ko modern JavaScript ka major turning point samjho. let, const, arrow functions, template literals, destructuring, modules aur bahut saare features isi modern style ka part hain.
let and const recap
Modern code usually const by default use karta hai and let only when a binding must be reassigned.
const course = "JavaScript";
let progress = 40;
progress = 60;
console.log(course, progress);const object ya array ke contents ko deeply immutable nahi banata; it only prevents rebinding that variable to a different value.Template literals
Backticks allow interpolation with ${...} and make multi-line strings easier to write.
const name = "Aman";
const score = 88;
const message = `Hello ${name}, your score is ${score}.`;
console.log(message);Expressions can run inside interpolation.
const price = 499;
const quantity = 2;
console.log(`Total: ₹${price * quantity}`);Default parameters
Function parameters can provide fallback values when an argument is missing or explicitly undefined.
function greet(name = "Student") {
return `Welcome, ${name}!`;
}
console.log(greet());
console.log(greet("Riya"));null. Passing null explicitly keeps null.Arrow functions
Arrow functions provide compact function syntax and are especially useful for short callbacks.
const double = number => number * 2;
const scores = [40, 55, 80];
const boosted = scores.map(score => score + 5);
console.log(double(6));
console.log(boosted);For multiple statements, use braces and an explicit return when a value should be returned.
const getResult = score => {
const passed = score >= 40;
return passed ? "Pass" : "Fail";
};this, arguments or constructor behavior. Object methods or constructors may need normal functions/classes instead.Array destructuring
Destructuring extracts array positions into variables.
const skills = ["HTML", "CSS", "JavaScript"];
const [first, second, third] = skills;
console.log(first, second, third);Positions can be skipped and defaults can be provided.
const values = [10];
const [start, end = 100] = values;
console.log(start, end);Object destructuring
Object destructuring extracts properties by key name.
const student = {
name: "Neha",
score: 92,
city: "Lucknow"
};
const { name, score } = student;
console.log(name, score);Rename and defaults in objects
const user = { name: "Riya" };
const { name: userName, role = "student" } = user;
console.log(userName);
console.log(role);Here name property is stored in the local variable userName.
Nested destructuring
Nested values can also be unpacked, but very deep destructuring can become hard to read.
const student = {
name: "Aman",
progress: { javascript: 70 }
};
const { progress: { javascript } } = student;
console.log(javascript);Spread with arrays
Spread syntax expands iterable values. With arrays it is commonly used for shallow copies and combining arrays.
const frontend = ["HTML", "CSS"];
const allSkills = [...frontend, "JavaScript"];
const copy = [...allSkills];
console.log(allSkills);
console.log(copy);Spread with objects
Object spread is useful for creating updated copies.
const student = { name: "Aman", score: 70 };
const updated = { ...student, score: 85, active: true };
console.log(updated);Later properties overwrite earlier same-name properties.
Rest parameters
Rest parameters collect remaining function arguments into a real array.
function total(...numbers) {
return numbers.reduce((sum, number) => sum + number, 0);
}
console.log(total(10, 20, 30)); // 60Syntax dono me ... hai, but kaam opposite hai. Spread values ko expand karta hai; rest multiple values ko collect karta hai.
Rest in destructuring
const [first, ...remaining] = [10, 20, 30, 40];
console.log(first);
console.log(remaining);
const { name, ...details } = {
name: "Riya",
score: 90,
city: "Delhi"
};
console.log(details);Object property shorthand
If variable name and property key are the same, modern object literals can use shorthand.
const name = "Aman";
const score = 88;
const student = { name, score };
console.log(student);Method shorthand
const learner = {
name: "Neha",
greet() {
return `Hi, ${this.name}`;
}
};This form is cleaner than writing greet: function () { ... }.
Computed property names
Square brackets inside an object literal allow expressions to become property keys.
const subject = "javascript";
const progress = {
[subject]: 75
};
console.log(progress.javascript);Optional chaining
?. safely stops property access when the value before it is null or undefined.
const student = { profile: { name: "Aman" } };
const city = student.profile?.address?.city;
console.log(city); // undefinedNullish coalescing
?? uses the right-hand fallback only when the left value is null or undefined.
const progress = 0;
console.log(progress || 100); // 100
console.log(progress ?? 100); // 0|| treats all falsy values as fallback cases. ?? only treats nullish values as missing.Logical assignment operators
Modern JavaScript also supports assignment forms such as ??=, ||= and &&=.
const settings = { theme: null };
settings.theme ??= "light";
console.log(settings.theme); // lightSet
Set stores unique values.
const topics = new Set(["HTML", "CSS", "CSS", "JavaScript"]);
console.log(topics.size); // 3
console.log(topics.has("CSS")); // true
topics.add("DOM");A common deduplication pattern is [...new Set(values)].
Map
Map stores key-value pairs and allows keys of any value type.
const scores = new Map();
scores.set("Aman", 88);
scores.set("Riya", 92);
console.log(scores.get("Riya"));
console.log(scores.has("Aman"));Plain objects are still excellent for many record-like structures; Map is useful when you specifically need map-style behavior and flexible keys.
JavaScript modules
Modules let code be split into files with explicit exports and imports. Each module has its own top-level scope.
export function add(a, b) {
return a + b;
}
export const taxRate = 0.18;import { add, taxRate } from "./math.js";
console.log(add(10, 20));
console.log(taxRate);Default exports
A module can have one default export.
export default function formatScore(score) {
return `${score}%`;
}import formatScore from "./format.js";
console.log(formatScore(88));Named exports make imported names explicit; default exports allow the importer to choose a local name. Teams often prefer consistent conventions rather than mixing styles randomly.
Module scope and strict mode
Top-level declarations in one module do not automatically become globals in another module. Modules also run in strict mode automatically, helping catch some silent mistakes.
Modern syntax and compatibility
Modern browsers support most common ES6+ features, but production projects should still consider their target browsers. Build tools can transform some newer syntax, while some APIs may need separate polyfills.
Syntax aur browser API same cheez nahi hain. Build tool syntax transform kar sakta hai, lekin missing browser API ko automatically add karna alag problem hai.
Modern does not mean shorter at any cost
Modern syntax ka goal readable code hai, sirf minimum characters nahi. Deep nested destructuring, clever one-liners aur chained expressions beginner code ko harder bana sakte hain.
Common beginner mistakes
- Every function ko arrow function me convert kar dena even when
thisbehavior matters. - Spread copy ko deep clone samajhna.
- Spread aur rest ko same operation samajhna.
- Destructuring me property name aur local renamed variable confuse karna.
||aur??ko interchangeable samajhna.- Default parameter ko
nullke liye bhi fallback samajhna. - Module file me export/import names mismatch karna.
- Default and named imports ka syntax mix karna.
- Modern one-liner ko readability se zyada important samajhna.
Beginner best practices
constby default; reassignment needed ho tolet.- Template literals interpolation-heavy strings ke liye use karo.
- Destructuring tab use karo jab required values clear hon.
- Spread/rest ka shallow behavior samjho.
- Arrow callbacks ko small and readable rakho.
?.aur??missing data ke intended meaning ke hisaab se use karo.- Modules ko responsibility ke basis par split karo, random tiny files me nahi.
- Named exports ke names stable aur meaningful rakho.
- Readable code ko shortest code se prefer karo.
Chapter checklist
- Template literals aur interpolation use kar sakte ho?
- Default parameters ka behavior clear hai?
- Arrow functions aur normal functions ka basic difference samajh aaya?
- Array/object destructuring use kar sakte ho?
- Spread vs rest difference explain kar sakte ho?
- Optional chaining aur nullish coalescing ka use clear hai?
SetaurMapka basic purpose samajh aaya?- Named/default module exports aur imports recognize kar sakte ho?
Practice Task — Modern Student Data Refactor
Purane-style JavaScript ko modern readable syntax me refactor karo.
constaurletko correct places par use karo.- String concatenation ko template literal me convert karo.
- Greeting function me default parameter add karo.
- Ek simple callback ko arrow function me convert karo.
- Student array se first item destructure karo.
- Student object se
nameaurscoredestructure karo. - Object destructuring me ek property rename aur default value use karo.
- Spread se array aur object ka shallow copy banao.
- Rest parameter se
total(...numbers)function banao. - Missing nested city ko optional chaining se safely read karo.
- Progress value
0ke saath||vs??compare karo. - Duplicate skills ko
Setse remove karo. - Student scores ka small
Mapbanao. - Ek utility ko named export karo aur second module me import syntax likho.
- Final code ko readability ke liye review karo — sirf short code ke liye nahi.