LearningJavaScript TutorialModern JavaScript (ES6+)
CHAPTER 13 · MODERN SYNTAX

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.

English + Hinglish48 min readPractice included

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.

Hinglish Explanation

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.

bindings.jsJS
const course = "JavaScript";
let progress = 40;

progress = 60;
console.log(course, progress);
Remember: 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.

template.jsJS
const name = "Aman";
const score = 88;

const message = `Hello ${name}, your score is ${score}.`;
console.log(message);

Expressions can run inside interpolation.

template-expression.jsJS
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.

defaults.jsJS
function greet(name = "Student") {
  return `Welcome, ${name}!`;
}

console.log(greet());
console.log(greet("Riya"));
Important: Default parameter does not replace null. Passing null explicitly keeps null.

Arrow functions

Arrow functions provide compact function syntax and are especially useful for short callbacks.

arrow.jsJS
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.

arrow-block.jsJS
const getResult = score => {
  const passed = score >= 40;
  return passed ? "Pass" : "Fail";
};
Arrow function caution: Arrow functions do not create their own this, arguments or constructor behavior. Object methods or constructors may need normal functions/classes instead.

Array destructuring

Destructuring extracts array positions into variables.

array-destructure.jsJS
const skills = ["HTML", "CSS", "JavaScript"];
const [first, second, third] = skills;

console.log(first, second, third);

Positions can be skipped and defaults can be provided.

array-default.jsJS
const values = [10];
const [start, end = 100] = values;

console.log(start, end);

Object destructuring

Object destructuring extracts properties by key name.

object-destructure.jsJS
const student = {
  name: "Neha",
  score: 92,
  city: "Lucknow"
};

const { name, score } = student;
console.log(name, score);

Rename and defaults in objects

rename.jsJS
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.

nested.jsJS
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.

spread-array.jsJS
const frontend = ["HTML", "CSS"];
const allSkills = [...frontend, "JavaScript"];
const copy = [...allSkills];

console.log(allSkills);
console.log(copy);
Shallow copy: Nested arrays/objects inside still share references unless they are copied separately.

Spread with objects

Object spread is useful for creating updated copies.

spread-object.jsJS
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.

rest-parameters.jsJS
function total(...numbers) {
  return numbers.reduce((sum, number) => sum + number, 0);
}

console.log(total(10, 20, 30)); // 60
Spread vs Rest

Syntax dono me ... hai, but kaam opposite hai. Spread values ko expand karta hai; rest multiple values ko collect karta hai.

Rest in destructuring

rest-destructure.jsJS
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.

shorthand.jsJS
const name = "Aman";
const score = 88;

const student = { name, score };
console.log(student);

Method shorthand

method.jsJS
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.

computed.jsJS
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.

optional.jsJS
const student = { profile: { name: "Aman" } };
const city = student.profile?.address?.city;

console.log(city); // undefined

Nullish coalescing

?? uses the right-hand fallback only when the left value is null or undefined.

nullish.jsJS
const progress = 0;

console.log(progress || 100); // 100
console.log(progress ?? 100); // 0
Difference: || 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 &&=.

logical-assignment.jsJS
const settings = { theme: null };
settings.theme ??= "light";

console.log(settings.theme); // light

Set

Set stores unique values.

set.jsJS
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.

map-collection.jsJS
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.

math.jsJS
export function add(a, b) {
  return a + b;
}

export const taxRate = 0.18;
app.jsJS
import { add, taxRate } from "./math.js";

console.log(add(10, 20));
console.log(taxRate);
Browser note: Browser modules are loaded as module scripts. Module loading follows URL and origin rules, so local file testing may differ from serving files through a development server.

Default exports

A module can have one default export.

format.jsJS
export default function formatScore(score) {
  return `${score}%`;
}
app.jsJS
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.

Important difference

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 this behavior 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 null ke 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

  • const by default; reassignment needed ho to let.
  • 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?
  • Set aur Map ka 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.

  1. const aur let ko correct places par use karo.
  2. String concatenation ko template literal me convert karo.
  3. Greeting function me default parameter add karo.
  4. Ek simple callback ko arrow function me convert karo.
  5. Student array se first item destructure karo.
  6. Student object se name aur score destructure karo.
  7. Object destructuring me ek property rename aur default value use karo.
  8. Spread se array aur object ka shallow copy banao.
  9. Rest parameter se total(...numbers) function banao.
  10. Missing nested city ko optional chaining se safely read karo.
  11. Progress value 0 ke saath || vs ?? compare karo.
  12. Duplicate skills ko Set se remove karo.
  13. Student scores ka small Map banao.
  14. Ek utility ko named export karo aur second module me import syntax likho.
  15. Final code ko readability ke liye review karo — sirf short code ke liye nahi.