Kazi Rahamatullah
Kazi Rahamatullah
AboutProjectsBlogContact
UsesBooks
ResumeView CV
Kazi Rahamatullah

© Copyright 2026 Kazi Rahamatullah

AboutProjectsBlogBooksUses
Twitter/XGitHubProduct HuntCodeSandbox
Back to Blog
MERNJavaScriptAsync AwaitFetch APIJestDOM

MERN Course: JavaScript Essentials

Weeks 6–9 of the MERN syllabus — fundamentals, OOP, DOM, async/await, Fetch API, authentication, Jest testing, and DevTools debugging with performance notes.

Jul 7, 20268 min read

Introduction

JavaScript is the language of the entire MERN stack. This guide expands the syllabus into interview-ready explanations with runnable examples and styled callouts for notes, tips, warnings, and performance.

Course Reference

Quick index

#TopicDescription
1Introduction to JavaScriptJavaScript runs in browsers and on servers (Node.js).
2Control Flow and FunctionsConditionals and loops control program flow.
3Working with Arrays and ObjectsArrays store ordered data; objects store keyed records.
4Object-Oriented Programming in JavaScriptES6 classes are syntactic sugar over prototypes.
5Introduction to the DOMThe DOM is a tree of nodes representing HTML.
6DOM Events and Event HandlingEvents bubble from target to root.
7Advanced DOM Manipulation & FormsValidate forms before submit.
8Callbacks, Promises, and Async/AwaitAsync code avoids blocking the main thread.
9Making API Requests (Fetch API)REST APIs use HTTP verbs: GET reads, POST creates, PUT/PATCH updates, DELETE removes.
10API Authentication and Best PracticesAPIs use API keys, Bearer tokens, or OAuth.
11Introduction to JavaScript Unit Testing (Jest)Unit tests verify functions in isolation.
12Developer Console & DebuggingChrome DevTools: Console for logs, Sources for breakpoints, Network for API inspection, Performance for profiling..

Week 6: JavaScript Fundamentals

1. Introduction to JavaScript

JavaScript runs in browsers and on servers (Node.js). Use const by default, let when reassignment is required, and avoid var.

Example:

javascript
const appName = 'MERN Todo'
let taskCount = 0
 
function addTask(title) {
  taskCount += 1
  return { id: taskCount, title, done: false }
}
 
console.log(addTask('Learn async/await'))

Note

const prevents rebinding — it does not freeze object contents. Use Object.freeze() only when immutability is required.

Tip

Apply this in your Week 6 course project before moving on.

Performance

Declare variables in the smallest scope needed. Hoisted var causes subtle bugs in loops and callbacks.

Back to index


2. Control Flow and Functions

Conditionals and loops control program flow. Arrow functions inherit this lexically — preferred in React event handlers.

Example:

javascript
const tasks = ['HTML', 'CSS', 'JS']
 
const completed = tasks.filter((task) => task !== 'HTML')
 
function greet(name = 'Developer') {
  return 'Hello, ' + name
}
 
for (const task of tasks) {
  console.log(task)
}

Note

Prefer for...of over for...in on arrays — for...in iterates keys, not values.

Tip

Apply this in your Week 6 course project before moving on.

Performance

Extract repeated logic into pure functions. Pure functions are easier to test and memoize in React.

Back to index


3. Working with Arrays and Objects

Arrays store ordered data; objects store keyed records. JSON is the wire format between front-end and MERN APIs.

Example:

javascript
const user = {
  id: 1,
  name: 'Kazi',
  skills: ['React', 'Node', 'MongoDB'],
}
 
const payload = JSON.stringify(user)
const parsed = JSON.parse(payload)
 
const skillList = user.skills.map((s) => s.toUpperCase()).join(', ')

Note

JSON.stringify drops undefined, functions, and symbols. Dates become strings — parse them explicitly.

Tip

Apply this in your Week 6 course project before moving on.

Performance

Use spread for shallow copies: { ...user, name: "Alex" }. For deep clones, use structuredClone() (modern browsers + Node 17+).

Back to index

Week 7: OOP & the DOM

4. Object-Oriented Programming in JavaScript

ES6 classes are syntactic sugar over prototypes. Use classes when modeling entities; use factory functions for simple data.

Example:

javascript
class Task {
  constructor(title) {
    this.title = title
    this.done = false
  }
 
  toggle() {
    this.done = !this.done
  }
}
 
const task = new Task('Deploy MERN app')
task.toggle()

Note

Put shared methods on the prototype (or class body) — not inside the constructor — to save memory.

Tip

Apply this in your Week 7 course project before moving on.

Performance

See the JavaScript Prototypes blog post for why prototype sharing matters at scale.

Back to index


5. Introduction to the DOM

The DOM is a tree of nodes representing HTML. Modern code prefers querySelector over legacy getElementById for flexibility.

Example:

javascript
const heading = document.querySelector('#app-title')
heading.textContent = 'MERN Stack Guide'
 
const list = document.querySelector('.task-list')
list.insertAdjacentHTML('beforeend', '<li>New task</li>')

Note

In React/Next.js you rarely touch the DOM directly — but understanding it helps debug hydration mismatches.

Tip

Apply this in your Week 7 course project before moving on.

Performance

Batch DOM updates. Reading layout properties (offsetHeight) after writes forces reflow — group reads and writes.

Back to index


6. DOM Events and Event Handling

Events bubble from target to root. Use event delegation on parent elements for dynamic lists instead of per-item listeners.

Example:

javascript
document.querySelector('.task-list').addEventListener('click', (event) => {
  const button = event.target.closest('[data-action="toggle"]')
  if (!button) return
  button.closest('li')?.classList.toggle('done')
})

Note

Always call preventDefault() on form submit when handling with JavaScript — unless native submit is intended.

Tip

Apply this in your Week 7 course project before moving on.

Performance

One delegated listener beats 100 individual listeners on large lists — fewer memory allocations.

Back to index

Week 8: Async JavaScript & APIs

7. Advanced DOM Manipulation & Forms

Validate forms before submit. Show inline errors; disable submit while async validation runs.

Example:

javascript
form.addEventListener('submit', async (event) => {
  event.preventDefault()
  const email = form.email.value.trim()
  if (!email.includes('@')) {
    showError('Invalid email')
    return
  }
  await fetch('/api/subscribe', { method: 'POST', body: JSON.stringify({ email }) })
})

Note

Validate on server too — client validation is UX, not security.

Tip

Apply this in your Week 8 course project before moving on.

Performance

Debounce input handlers (search, autocomplete) to avoid excessive API calls on every keystroke.

Back to index


8. Callbacks, Promises, and Async/Await

Async code avoids blocking the main thread. Prefer async/await over callback pyramids; always handle errors with try/catch.

Example:

javascript
async function loadPosts() {
  try {
    const res = await fetch('https://api.example.com/posts')
    if (!res.ok) throw new Error('HTTP ' + res.status)
    return await res.json()
  } catch (error) {
    console.error('Failed to load posts:', error)
    return []
  }
}

Note

Never forget await — floating Promises cause silent failures. Use Promise.all for parallel independent requests.

Tip

Apply this in your Week 8 course project before moving on.

Performance

Fetch in parallel with Promise.all([fetchUsers(), fetchPosts()]) instead of sequential awaits when requests are independent.

Back to index


9. Making API Requests (Fetch API)

REST APIs use HTTP verbs: GET reads, POST creates, PUT/PATCH updates, DELETE removes. Always check response.ok before parsing JSON.

Tip

Apply this in your Week 8 course project before moving on.

Back to index


Week 9: Auth, Testing & DevTools

10. API Authentication and Best Practices

APIs use API keys, Bearer tokens, or OAuth. Respect rate limits; implement exponential backoff on 429 responses.

Example:

javascript
const res = await fetch('/api/profile', {
  headers: {
    Authorization: 'Bearer ' + token,
    Accept: 'application/json',
  },
})

Note

Rotate API keys leaked in client bundles. Use server-side route handlers to proxy sensitive third-party APIs.

Tip

Apply this in your Week 9 course project before moving on.

Performance

Batch requests where the API supports it. N+1 client fetches are a common MERN performance bottleneck.

Back to index


11. Introduction to JavaScript Unit Testing (Jest)

Unit tests verify functions in isolation. TDD writes tests first — forces clear interfaces before implementation.

Example:

javascript
// sum.js
export function sum(a, b) {
  return a + b
}
 
// sum.test.js
import { sum } from './sum'
test('adds numbers', () => {
  expect(sum(2, 3)).toBe(5)
})

Note

Test behavior, not implementation. Mock fetch/DB in unit tests — integration tests hit real services.

Tip

Apply this in your Week 9 course project before moving on.

Performance

Keep unit tests fast (under 50ms each). Slow suites discourage running them before every commit.

Back to index


12. Developer Console & Debugging

Chrome DevTools: Console for logs, Sources for breakpoints, Network for API inspection, Performance for profiling.

  • Use debugger statement or click line numbers to break
  • Inspect failed fetch requests — status, headers, response body
  • React DevTools shows component props and re-render causes

Example:

javascript
console.time('fetch-posts')
const posts = await loadPosts()
console.timeEnd('fetch-posts')

Note

Remove console.log from production hot paths or gate behind process.env.NODE_ENV === "development".

Tip

Apply this in your Week 9 course project before moving on.

Performance

Use Performance panel to find long tasks blocking the main thread — common with heavy sync JSON parsing.

Back to index


Share this article

XLinkedInFacebook
Kazi Rahamatullah

Written by

Kazi Rahamatullah

FullStack Developer

X / TwitterGitHubLinkedIn

Subscribe to my newsletter

Stay up to date and get notified when I share new contents.

No spam ever, unsubscribe anytime