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
Split code into reusable files and import them where needed
// 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));
// 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' |
Data format for exchanging data between server and client
"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}'
Handle errors gracefully without crashing your program
Try dividing by zero or entering text to see error handling in action!
| 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.name - Type of error (Error, TypeError, etc.)error.message - Error descriptionerror.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"); }
| 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 |
Loading...