Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

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

2. Setting Up Your Environment

You can run JavaScript in a browser or through Node.js.

Browser Console

  1. Open a browser.
  2. Open Developer Tools.
  3. Select the Console tab.
  4. 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

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

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:

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:

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:

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

23. Performance and Memory

24. Common Mistakes

  1. Using var everywhere without understanding scope.
  2. Forgetting that const objects can still be mutated.
  3. Assuming spread syntax makes a deep copy.
  4. Using map() when no transformed array is needed.
  5. Forgetting that sort() changes the array.
  6. Forgetting to handle rejected Promises.
  7. Assuming fetch() throws on every HTTP error.
  8. Using == without understanding type coercion.
  9. Using innerHTML with untrusted content.
  10. Confusing null, undefined, and empty strings.
  11. Writing huge functions that are difficult to test.
  12. Putting secrets into browser-side JavaScript.

25. Practice Projects

Beginner

Intermediate

Advanced

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

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