Master modern ES6+ features to build scalable, predictable, and robust enterprise applications.
const / let)
?.), nullish (??)
import/export) for scale
const vs let
In many projects, variables are declared in inconsistent ways. Declaring intent eliminates entire classes of runtime bugs.
The reference won't change. Safer by default for objects, primitives, and configurations.
Values can change when needed (pagination, accumulators, active filters).
Function scope, hoisting quirks, and accidental re-declarations cause severe subtle bugs.
const REVENUE_TARGET = 1000000; let revenue = 850000; let achievementRate = (revenue / REVENUE_TARGET) * 100;
85.00% of target
const and let enforce block scoping ({ }), preventing accidental variable leakage into outer contexts.
if (true) {
let temp = 'inside block';
const MAX_LIMIT = 100;
}
// temp & MAX_LIMIT are not accessible here!
const API_ENDPOINT = 'https://api.gov/data';
API_ENDPOINT = 'https://api.other';
// TypeError: Assignment to constant variable
var)
for (var i = 0; i < data.length; i++) { ... }
console.log(i); // i leaks outside the loop!
let)
for (let i = 0; i < data.length; i++) { ... }
console.log(i); // ReferenceError: i is not defined!
Business Data Use: Store KPI values with const, track user filter parameters with let, and hold transformed report datasets with const.
` `)
Powerful string syntax for dynamic, readable, and data-driven text. No more messy + string concatenations.
Insert variables or expressions directly inside strings.
Write clean multi-line templates without \n escapes.
Insert endpoint parameters safely into URLs.
this.
Arrow functions offer a concise way to write functions and automatically inherit this from their surrounding scope.
When the function has only one expression, the return keyword and curly braces are optional!
Use parentheses when passing 2 or more arguments (or zero arguments).
Does NOT create its own this. Eliminates the old var self = this; hack in callbacks.
// Implicit Return (Single line, concise)
const double = n => n * 2;
// Explicit Return (Multiple statements require { } and return)
const calculateTax = (amount, rate) => {
const tax = amount * rate;
return amount + tax;
};
// Returning an Object Literal (Wrap with parentheses!)
const makeUser = (name, id) => ({ name, id });
{ }, you MUST write return!
map, filter, reduce
Transform, filter, and calculate business metrics cleanly in chained functional pipelines.
Transform every record in an array into a new shape.
Keep items that match conditional predicates.
Accumulate dataset values into a single summary number.
const students = [
{ id: 1, name: 'Ana', score: 85 }, { id: 2, name: 'Ben', score: 92 },
{ id: 3, name: 'Chai', score: 78 }, { id: 4, name: 'Dao', score: 88 }
];
const passed = students.filter(s => s.score >= 80);
const average = passed.reduce((sum, s) => sum + s.score, 0) / passed.length;
console.log(`Average: ${average.toFixed(2)}`); // Output: Average: 88.33
...rest) Syntax
Good function design provides safe fallbacks when arguments are missing, and flexibly accepts variable argument lists.
Provide fallback values when arguments are undefined or omitted.
Gather any number of incoming arguments into a single true JavaScript Array.
calcKPI(data, startDate = '2024-01-01', ...metrics)).
Unpack values directly from objects into distinct variables with alias renames and safe fallback defaults.
Pick only the properties your component or function needs.
Perfect for API responses, config objects, and options bags.
Rename properties locally to avoid name collisions.
Provide fallback defaults when property is missing.
Destructure by index position, skip unused elements, and unpack deeply nested API response trees in one clean line.
const response = {
data: {
students: [
{ id: 1, name: 'Kaisa', scores: [88, 92] }
]
}
};
// Unpack first student name & english score in 1 go:
const {
data: { students: [{ name: firstName, scores: [, eng] }] }
} = response;
// firstName = 'Kaisa', eng = 92
The ... operator unpacks array elements and object keys with concise, expressive syntax.
Output: ['Ava', 'Ben', 'Cara', 'Dan']
Later properties cleanly replace earlier keys with matching names.
Directly mutating objects and arrays causes silent bugs and breaks reactive UI re-renders in modern frameworks (React / Vue).
Creates a new version of data instead of mutating in place.
Enables undo/redo history, time-travel debugging, and zero side effects.
Component re-renders trigger accurately because reference identity changes (prev !== next).
// Update student with id === 1 without mutating array
const updatedStudents = students.map(s =>
s.id === 1
? { ...s, score: 95 } // Return new object copy with updated score
: s // Keep untouched reference
);
?.): Safe Property Access
Stop the #1 JavaScript crash: "TypeError: Cannot read properties of undefined".
const email = data.user.profile.email;
// CRASH! If user or profile is null/undefined
const email = data?.user?.profile?.email;
// Evaluates safely to undefined without error!
?. anywhere you access an object property, array index, or optional function.
??) vs Logical OR (||)
?? provides fallbacks ONLY for null and undefined, preserving valid falsy values like 0, "", and false!
const totalVisits = data?.stats?.visits ?? 0;
Never crashes & preserves 0 visits!
export & import
Break giant monolithic files into small, focused, reusable modules that only share what's needed.
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
// Importing Named Exports (Must use { } exact names):
import { PI, add } from './utils/math.js';
export default function formatDate(date) {
return new Intl.DateTimeFormat('en-US').format(date);
}
// Importing Default Export (No curly braces! Can rename):
import formatDate from './format/date.js';
Structure your codebase by feature and responsibility to reduce duplication and empower team collaboration.
Share common logic across all features (e.g. utils/format.js replaces 5 duplicate currency formatters).
Looking at top-level import statements tells any developer immediately what a file depends on.
Engineers work on isolated feature directories with near-zero Git merge conflicts.
<script type="module" src="app.js"></script>
Node.js: Set "type": "module" in package.json
Combining const, destructuring, arrow functions, optional chaining, nullish coalescing, and template strings.
export const fetchStudentSummary = async (schoolId, { minGrade = 'C' } = {}) => {
const url = `https://api.edu.gov/v1/schools/${schoolId}/students`;
const res = await fetch(url);
const { data = [] } = await res.json();
return data.map(({ id, name, scores, profile }) => ({
id,
fullName: name?.trim() || 'Anonymous',
avgScore: scores?.length ? scores.reduce((a, b) => a + b, 0) / scores.length : 0,
city: profile?.address?.city ?? 'Unknown City',
avatar: profile?.avatarUrl ?? '/default.png'
}));
};
Incorporate these guidelines into daily development, code reviews, and project standards.
const; use let only when reassignment is strictly required.?. and ?? defensively on all external API payloads.var in modern JavaScript codebases.|| when 0 or false are valid domain values (use ??).{...obj}).Quick lookup reference for the most impactful ES6+ syntaxes.