Intermediate Development Guide

Asynchronous JavaScript

Understanding the event loop, callbacks, promises, and async/await is crucial for writing non‑blocking code.

async function fetchData(url) {
    try {
        const response = await fetch(url);
        const data = await response.json();
        return data;
    } catch (err) {
        console.error('Error:', err);
    }
}

Consuming APIs

Use the fetch API or libraries like axios to interact with RESTful services.

fetch('https://api.example.com/items')
    .then(res => res.json())
    .then(items => console.log(items))
    .catch(err => console.error(err));

ES Modules

Modern JavaScript supports native modules. Export and import functionality across files.

// utils.js
export function add(a, b) {
    return a + b;
}

// main.js
import { add } from './utils.js';
console.log(add(2, 3)); // 5

Bundling with Webpack

Webpack bundles assets, transforms code with loaders, and provides development features.

// webpack.config.js
const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    mode: 'development',
    module: {
        rules: [{ test: /\.css$/, use: ['style-loader', 'css-loader'] }]
    }
};

Testing Basics

Use Jest or Mocha for unit testing. Write assertions to verify logic.

// sum.js
export const sum = (a, b) => a + b;

// sum.test.js
import { sum } from './sum';

test('adds two numbers', () => {
    expect(sum(1, 2)).toBe(3);
});