JavaScript Modules, JSON & Error Handling

Detailed explanations & code examples are in the JavaScript (.js) file

Click the { } button at the bottom right to view it

Master ES6 Modules, JSON, and Error Handling

Topic 35: ES6 Modules (import/export)

Split code into reusable files and import them where needed

For a better explanation, see the JavaScript file.

Named Exports (Multiple per file)

// This is a example of mathUtils.js file contents which exports
export const PI = 3.14159;

export function getArea(radius){
    return PI * radius * radius;
}

// This is your file where you import the code from mathUtils.js file: main.js
import {PI, getArea} from './mathUtils.js';
console.log(getArea(10));
        

Default Export (One per file)

// Component.js
export default function MyComponent(){
    return <div>Hello</div>;
}

// App.js
import MyComponent from './Component.js';
Type Export Import
Named export const PI = 3.14 import {PI} from './file.js'
Default export default MyFunc import MyFunc from './file.js'
All Named - import * as Utils from './file.js'
Rename - import {PI as pi} from './file.js'

Topic 36: JSON (JavaScript Object Notation)

Data format for exchanging data between server and client

What is JSON?
• TEXT format (not a JavaScript object)
• Used by APIs to send/receive data
• Must be converted to/from JavaScript objects
• Keys must be in double quotes: "name"
Method Purpose Input - Output
JSON.parse() Convert JSON string to JS object JSON string - Object
JSON.stringify() Convert JS object to JSON string Object - JSON string
JSON.stringify(obj, null, 2) Pretty print with indentation Object - Formatted JSON
// JSON string (from API):
const jsonString = `{"name":"Umer Azmi","age":23}`;

// Convert to JavaScript object:
const obj = JSON.parse(jsonString);
console.log(obj.name);  // "Umer Azmi"

// Convert JavaScript object to JSON:
const person = {name: "Umer", age: 23};
const json = JSON.stringify(person);
console.log(json);  // '{"name":"Umer","age":23}'

Examples in Console:

Topic 37: Error Handling (try/catch/finally)

Handle errors gracefully without crashing your program

🔥 ESSENTIAL FOR PRODUCTION CODE! Always handle errors:

Interactive Division Calculator

Try dividing by zero or entering text to see error handling in action!





Enter values and click Calculate
Test These Error Cases:

Error Handling Keywords

Keyword Purpose When It Runs
try { } Enclose code that might throw errors Executes until error or completion
catch(error) { } Handle errors from try block Only if error occurs
finally { } Cleanup code (optional) ALWAYS runs (error or not)
throw Manually create custom errors When you need to throw error

Error Object

Error object properties:
error.name - Type of error (Error, TypeError, etc.)
error.message - Error description
error.stack - Stack trace for debugging
try{
    if(divisor === 0){
        // throw = manually creates error and jumps to catch
        throw new Error("Can't divide by zero!");
    }
    const result = dividend / divisor;
}
catch(error){
    // Handle the error
    console.error(error.message);
}
finally{
    // Always runs (cleanup)
    console.log("Done");
}

Common Error Types

Error Type Description Example
Error Generic error (base class) Custom errors you create
SyntaxError Invalid code syntax Missing bracket, typo
ReferenceError Variable doesn't exist Using undefined variable
TypeError Wrong data type Calling method on null
RangeError Number outside valid range Array with negative length

Why Use try/catch?

Without try/catch: Program crashes, rest of code doesn't run
With try/catch: Error is caught, program continues running
📄 loading...
Loading...