Guides › TypeScript & Modern JavaScript
JavaScript ES6+: Complete Guide from Beginner to Advanced
Master modern JavaScript, ES6+ features, functions, arrays, objects, promises, modules, async/await, and practical coding examples.
JavaScript ES6+: Complete Guide from Beginner to Advanced
1. Introduction to Modern JavaScript
JavaScript is a programming language used to create interactive websites, web applications, server-side applications, and cross-platform software.
Modern JavaScript refers to newer language features introduced through ECMAScript standards, especially ES2015 (ES6) and later versions.
What You Will Learn
- JavaScript fundamentals and modern syntax
- Variables, data types, and operators
- Arrow functions and template literals
- Arrays, objects, and destructuring
- Spread and rest operators
- Optional chaining and nullish coalescing
- Array methods and functional programming
- DOM manipulation and browser events
- Promises, async/await, and error handling
- Modules and modern JavaScript tooling
- Performance, security, and best practices
2. Setting Up Your Environment
You can run JavaScript in a browser or through Node.js.
Browser Console
- Open a browser.
- Open Developer Tools.
- Select the Console tab.
- Run:
console.log("Hello, Modern JavaScript!");
Using Node.js
Install Node.js, create a file named app.js, and run:
console.log("Hello from Node.js!");
Execute it with:
node app.js
3. Variables: var, let, and const
Variables store values.
var oldVariable = "Older syntax";
let age = 21;
const language = "JavaScript";
age = 22;
console.log(age);
console.log(language);
Differences
varis function-scoped and can be redeclared.letis block-scoped and can be reassigned.constis block-scoped and cannot be reassigned.
Prefer const by default. Use let when reassignment is required.
A const object can still have its properties changed; const prevents reassignment of the binding, not mutation of the object.
4. Data Types
JavaScript has primitive types and objects.
Primitive Types
- String
- Number
- BigInt
- Boolean
- Undefined
- Null
- Symbol
const name = "Aman";
const score = 95;
const isActive = true;
const missingValue = undefined;
const emptyValue = null;
const largeNumber = 12345678901234567890n;
Objects include arrays, functions, dates, and ordinary objects.
const user = {
name: "Aman",
age: 21
};
const skills = ["HTML", "CSS", "JavaScript"];
Use typeof to inspect many values, but remember that typeof null returns "object" because of a historical JavaScript quirk.
5. Template Literals
Template literals use backticks and support interpolation.
const name = "Aman";
const course = "JavaScript";
console.log(`Hello ${name}, welcome to ${course}!`);
They also support multiline strings.
const message = `
Welcome to Codify.
Learn JavaScript step by step.
`;
6. Arrow Functions
Arrow functions provide concise function syntax.
const add = (a, b) => a + b;
console.log(add(10, 20));
With one parameter:
const square = number => number * number;
With multiple statements:
const calculateTotal = (price, quantity) => {
const total = price * quantity;
return total;
};
Arrow functions do not have their own this or arguments. Choose regular functions when their own function context is required.
7. Default Parameters
Default parameters provide fallback values.
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
console.log(greet());
console.log(greet("Aman"));
8. Destructuring
Destructuring extracts values from arrays and properties from objects.
Array Destructuring
const colors = ["red", "green", "blue"];
const [first, second] = colors;
console.log(first);
console.log(second);
Object Destructuring
const user = {
name: "Aman",
age: 21,
city: "Jaipur"
};
const { name, age } = user;
console.log(name, age);
Renaming and Defaults
const { name: userName, country = "India" } = user;
Nested Destructuring
const student = {
name: "Aman",
address: {
city: "Jaipur"
}
};
const {
address: { city }
} = student;
9. Spread and Rest Operators
Both use ..., but their purposes differ.
Spread
Spread expands iterable values or object properties.
const first = [1, 2, 3];
const second = [...first, 4, 5];
const original = { name: "Aman" };
const updated = { ...original, age: 21 };
Spread creates a shallow copy, not a deep copy.
Rest
Rest collects remaining arguments or properties.
function sum(...numbers) {
return numbers.reduce((total, number) => total + number, 0);
}
console.log(sum(1, 2, 3, 4));
10. Array Methods
Array methods help transform, filter, search, and summarize data.
map()
Creates a new array by transforming each item.
const numbers = [1, 2, 3];
const doubled = numbers.map(number => number * 2);
filter()
Returns items that match a condition.
const numbers = [10, 15, 20, 25];
const result = numbers.filter(number => number >= 20);
reduce()
Combines array items into a single result.
const numbers = [10, 20, 30];
const total = numbers.reduce(
(sum, number) => sum + number,
0
);
find() and findIndex()
const users = [
{ id: 1, name: "Aman" },
{ id: 2, name: "Riya" }
];
const user = users.find(item => item.id === 2);
const index = users.findIndex(item => item.id === 2);
some() and every()
const numbers = [2, 4, 6];
console.log(numbers.some(number => number > 5));
console.log(numbers.every(number => number % 2 === 0));
Other useful methods include includes(), slice(), splice(), sort(), flat(), and flatMap().
Remember: sort() and splice() mutate the original array. slice() creates a shallow copy.
11. Objects and Modern Object Syntax
const name = "Aman";
const age = 21;
const user = {
name,
age,
greet() {
return `Hello, I am ${this.name}`;
}
};
console.log(user.greet());
Useful methods:
Object.keys(user);
Object.values(user);
Object.entries(user);
Object.hasOwn(user, "name");
Use Object.hasOwn() when checking whether a property belongs directly to an object.
12. Optional Chaining and Nullish Coalescing
Optional Chaining
Avoids errors when an intermediate value is null or undefined.
const user = {
profile: {
city: "Jaipur"
}
};
console.log(user.profile?.city);
console.log(user.contact?.email);
Nullish Coalescing
Use ?? when you want a fallback only for null or undefined.
const username = null;
const displayName = username ?? "Guest";
Unlike ||, the ?? operator preserves valid falsy values such as 0, false, and an empty string.
13. Map and Set
Map
A Map stores key-value pairs and supports keys of different types.
const scores = new Map();
scores.set("Aman", 95);
scores.set("Riya", 98);
console.log(scores.get("Aman"));
console.log(scores.has("Riya"));
Set
A Set stores unique values.
const numbers = [1, 2, 2, 3, 3, 4];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers);
14. Promises
A Promise represents the eventual result of an asynchronous operation.
const task = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Task completed");
} else {
reject(new Error("Task failed"));
}
});
task
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log("Finished"));
Promise states are pending, fulfilled, and rejected.
Useful Promise methods include:
Promise.all()Promise.allSettled()Promise.race()Promise.any()
Choose the method according to whether you need every result, all outcomes, the first settlement, or the first fulfillment.
15. Async/Await
async and await make Promise-based code easier to read.
async function getUsers() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const users = await response.json();
console.log(users);
} catch (error) {
console.error("Could not load users:", error);
}
}
getUsers();
Important points:
- An
asyncfunction always returns a Promise. awaitpauses that async function until a Promise settles.- Check
response.ok;fetch()does not reject for ordinary HTTP error statuses. - Use
try/catchfor error handling.
Independent operations can often run concurrently:
const [users, posts] = await Promise.all([
fetch("/api/users").then(response => response.json()),
fetch("/api/posts").then(response => response.json())
]);
16. ES Modules
Modules split code into reusable files.
Export
// math.js
export const add = (a, b) => a + b;
export function multiply(a, b) {
return a * b;
}
export default function subtract(a, b) {
return a - b;
}
Import
// app.js
import subtract, { add, multiply } from "./math.js";
console.log(add(2, 3));
console.log(multiply(2, 3));
console.log(subtract(5, 2));
Browsers can use modules with <script type="module">. Node.js supports modules through project configuration and file extensions.
17. Classes and Inheritance
Classes provide syntax for working with objects and prototypes.
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}`;
}
}
class Developer extends Person {
constructor(name, language) {
super(name);
this.language = language;
}
introduce() {
return `${this.greet()}. I use ${this.language}.`;
}
}
const developer = new Developer("Aman", "JavaScript");
console.log(developer.introduce());
Learn constructors, methods, inheritance, super, static methods, and private fields such as #balance.
Prefer composition over inheritance when it creates a simpler design.
18. DOM Manipulation
The Document Object Model allows JavaScript to interact with webpage elements.
<h1 id="heading">Hello</h1>
<button id="changeButton">Change Text</button>
const heading = document.querySelector("#heading");
const button = document.querySelector("#changeButton");
button.addEventListener("click", () => {
heading.textContent = "Welcome to Codify!";
});
Important DOM APIs include:
querySelector()andquerySelectorAll()createElement()append()andremove()classList.add()andclassList.remove()addEventListener()setAttribute()
Use textContent for plain user-provided text. Avoid inserting untrusted content with innerHTML.
19. Event Handling
const form = document.querySelector("#signupForm");
form.addEventListener("submit", event => {
event.preventDefault();
const formData = new FormData(form);
const email = formData.get("email");
console.log(email);
});
Learn event bubbling, capturing, delegation, keyboard events, form events, and event cleanup.
For dynamically generated lists, event delegation can reduce the number of individual listeners.
20. JSON and Data Exchange
JSON is a common format for APIs and configuration.
const user = {
name: "Aman",
active: true
};
const json = JSON.stringify(user);
const parsed = JSON.parse(json);
JSON.parse() can throw an error for invalid JSON, so handle untrusted input carefully.
JSON does not directly preserve values such as functions, undefined properties, or object prototypes.
21. Error Handling
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (error) {
console.error(error.message);
}
Use meaningful error messages, avoid silently swallowing failures, and distinguish expected validation errors from unexpected application errors.
22. Modern JavaScript Best Practices
- Use
constby default andletwhen reassignment is needed. - Prefer strict equality (
===) unless coercion is intentional. - Keep functions small and focused.
- Use descriptive variable and function names.
- Avoid deeply nested conditionals.
- Handle asynchronous errors explicitly.
- Prefer immutable updates when they simplify reasoning.
- Avoid unnecessary global variables.
- Validate external input.
- Do not expose API secrets in frontend code.
- Use a formatter and linter.
- Write tests for important logic.
- Read browser and runtime error messages carefully.
23. Performance and Memory
- Avoid unnecessary DOM updates.
- Debounce or throttle high-frequency events when appropriate.
- Use pagination or virtualization for very large lists.
- Avoid retaining references to unused DOM elements.
- Clean up event listeners and subscriptions when necessary.
- Measure performance before optimizing.
- Use browser performance and memory tools to investigate bottlenecks.
24. Common Mistakes
- Using
vareverywhere without understanding scope. - Forgetting that
constobjects can still be mutated. - Assuming spread syntax makes a deep copy.
- Using
map()when no transformed array is needed. - Forgetting that
sort()changes the array. - Forgetting to handle rejected Promises.
- Assuming
fetch()throws on every HTTP error. - Using
==without understanding type coercion. - Using
innerHTMLwith untrusted content. - Confusing
null,undefined, and empty strings. - Writing huge functions that are difficult to test.
- Putting secrets into browser-side JavaScript.
25. Practice Projects
Beginner
- Calculator
- Digital clock
- Counter application
- Random quote generator
- To-do list
Intermediate
- Weather dashboard using an API
- Expense tracker
- Quiz application
- Searchable product list
- Form validation system
Advanced
- GitHub profile finder
- Paginated data explorer
- Real-time chat interface
- Offline-capable notes application
- Modular task management application
For every project, include a README, responsive interface, error handling, meaningful commits, and tests for important logic.
26. Learning Roadmap
Week 1
Learn variables, types, operators, conditions, loops, and functions.
Week 2
Practice arrays, objects, destructuring, spread/rest, and array methods.
Week 3
Learn DOM manipulation, events, modules, and JSON.
Week 4
Learn Promises, async/await, API requests, error handling, and testing.
Week 5
Build projects and learn debugging, performance, and code quality.
27. Final Checklist
- Understand scope and variable declarations.
- Work confidently with arrays and objects.
- Use modern functions and destructuring.
- Understand spread, rest, and optional chaining.
- Transform data with array methods.
- Work with Promises and async/await.
- Organize code using modules.
- Manipulate the DOM safely.
- Handle events and forms.
- Debug and test code.
- Build and deploy at least three projects.
Conclusion
Modern JavaScript is essential for frontend development, backend development with Node.js, and many full-stack frameworks. Master the fundamentals first, then build projects that demonstrate your ability to write readable, reliable code.
More guides
- How to Use Codify: A 7-Day Start Plan — New here? Pick a roadmap, make a study plan, start the DSA sheet, revise with notes, practise for placements and test yourself — one step a day, then a daily routine.
- Infosys Preparation Guide: Online Test, Pseudocode and Interview — Roles (SE, DSE, SP), what each section of the Infosys online test checks, how to crack pseudocode and reasoning, a 4-week plan and the interview.
- Wipro Elite NLTH Preparation: Aptitude, Essay and Coding — The Wipro fresher test round by round — quant, logical and verbal, the written essay, two coding problems — plus a 3-week plan and interview tips.
- Accenture Preparation Guide: Cognitive, Technical, Coding and Communication — Every Accenture round explained — cognitive, MS Office/networking/cloud technical MCQs, pseudocode, coding and the spoken-English test — with a 4-week plan.