JavaScript Advanced: OOPs, JSON, APIs

1. Object-Oriented Programming (OOPs) in JavaScript

Classes, Objects, Inheritance, and Polymorphism Example

// Base class demonstrating Class concept
class Vehicle {
    constructor(brand, model) {
        this.brand = brand;
        this.model = model;
    }
    
    start() {
        return `${this.brand} ${this.model} is starting`;
    }
    
    // Method to be overridden (Polymorphism)
    move() {
        return "Vehicle is moving";
    }
}

// Inheritance - Car extends Vehicle
class Car extends Vehicle {
    constructor(brand, model, doors) {
        super(brand, model); // Call parent constructor
        this.doors = doors;
    }
    
    // Polymorphism - Override parent method
    move() {
        return `${this.brand} car is driving on road`;
    }
    
    honk() {
        return "Beep beep!";
    }
}

// Inheritance - Bike extends Vehicle
class Bike extends Vehicle {
    constructor(brand, model, type) {
        super(brand, model);
        this.type = type;
    }
    
    // Polymorphism - Override parent method
    move() {
        return `${this.brand} bike is riding smoothly`;
    }
}

// Creating Objects
const myCar = new Car("Toyota", "Camry", 4);
const myBike = new Bike("Honda", "CBR", "Sport");

// Using objects and methods
console.log(myCar.start());        // Toyota Camry is starting
console.log(myCar.move());         // Toyota car is driving on road
console.log(myBike.move());        // Honda bike is riding smoothly

Explanation:

Classes are blueprints that define properties and methods for creating objects, like the Vehicle class defining brand and model properties

Objects are instances of classes created using the ‘new’ keyword, such as myCar and myBike being specific instances with actual values

Inheritance allows child classes to inherit properties and methods from parent classes using ‘extends’ keyword, where Car and Bike inherit from Vehicle

Polymorphism enables different classes to have methods with the same name but different implementations, as seen in the move() method behaving differently for Car and Bike

2. JSON (JavaScript Object Notation)

// JSON Example
const studentData = {
    "name": "John Doe",
    "age": 22,
    "courses": ["JavaScript", "Python", "React"],
    "isActive": true,
    "address": {
        "city": "New York",
        "zipCode": "10001"
    }
};

// Converting object to JSON string
const jsonString = JSON.stringify(studentData);
console.log("JSON String:", jsonString);

// Converting JSON string back to object
const parsedData = JSON.parse(jsonString);
console.log("Parsed Object:", parsedData.name);

Explanation:

JSON is a lightweight data interchange format that uses human-readable text to store and transmit data objects consisting of key-value pairs

JSON.stringify() converts JavaScript objects into JSON strings, useful for sending data to servers or storing in local storage

JSON.parse() converts JSON strings back into JavaScript objects, essential for receiving and processing data from APIs • JSON supports various data types including strings, numbers, booleans, arrays, objects, and null, but not functions or undefined values

3. API Introduction and Fetch

// API Example using Fetch
async function fetchUserData() {
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
        const userData = await response.json();
        console.log('User Data:', userData);
        return userData;
    } catch (error) {
        console.error('API Error:', error);
    }
}

// Call the function
fetchUserData();

Explanation:

APIs (Application Programming Interfaces) are sets of protocols and tools that allow different software applications to communicate with each other

fetch() is a modern JavaScript method for making HTTP requests to APIs, returning a Promise that resolves to the response object

response.json() is used to extract JSON data from the response object, also returning a Promise • APIs enable applications to access external data sources, services, and functionality without knowing the internal implementation details

4. AJAX Introduction

// AJAX Example using XMLHttpRequest
function loadDataWithAJAX() {
    const xhr = new XMLHttpRequest();
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            const data = JSON.parse(xhr.responseText);
            console.log('AJAX Data:', data);
            document.getElementById('result').innerHTML = data.title;
        }
    };
    
    xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
    xhr.send();
}

// Call the function
loadDataWithAJAX();

Explanation:

AJAX (Asynchronous JavaScript and XML) allows web pages to update content dynamically without reloading the entire page

XMLHttpRequest is the traditional method for making asynchronous HTTP requests, though fetch() is now preferred for new projects

readyState property indicates the state of the request (0-4), with 4 meaning the request is complete

• AJAX enables creating responsive web applications by fetching data in the background and updating specific page sections

5. Promises, Async/Await

// Promise Example
function fetchDataWithPromise() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const success = Math.random() > 0.3;
            if (success) {
                resolve({ message: "Data fetched successfully", id: 123 });
            } else {
                reject(new Error("Failed to fetch data"));
            }
        }, 2000);
    });
}

// Using Promise with .then()
fetchDataWithPromise()
    .then(data => console.log('Promise Success:', data))
    .catch(error => console.error('Promise Error:', error));

// Using Async/Await
async function handleAsyncOperation() {
    try {
        const result = await fetchDataWithPromise();
        console.log('Async/Await Success:', result);
        return result;
    } catch (error) {
        console.error('Async/Await Error:', error);
    }
}

handleAsyncOperation();

Explanation:

Promises are objects representing the eventual completion or failure of asynchronous operations, providing a cleaner alternative to callback hell

resolve() is called when the asynchronous operation succeeds, while reject() is called when it fails

async/await is syntactic sugar over Promises that makes asynchronous code look and behave more like synchronous code

await pauses the execution of async functions until the Promise is resolved, making error handling easier with try-catch blocks

6. Spread Operator Example

// Spread Operator Examples
const numbers = [1, 2, 3];
const moreNumbers = [4, 5, 6];

// Array spreading
const combinedNumbers = [...numbers, ...moreNumbers];
console.log('Combined Array:', combinedNumbers); // [1, 2, 3, 4, 5, 6]

// Object spreading
const person = { name: "Alice", age: 25 };
const employee = { ...person, jobTitle: "Developer", salary: 75000 };
console.log('Employee Object:', employee);

// Function parameters spreading
function sum(...args) {
    return args.reduce((total, num) => total + num, 0);
}

console.log('Sum:', sum(1, 2, 3, 4, 5)); // 15

Explanation:

Spread operator (…) allows arrays, objects, or function arguments to be expanded or “spread” into individual elements

• In arrays, spread operator creates a new array by combining elements from multiple arrays without modifying the originals

• In objects, spread operator creates a new object by copying properties from existing objects, with later properties overriding earlier ones

• In function parameters, spread operator collects multiple arguments into an array, enabling functions to accept variable numbers of arguments

7. DateTime Functions Example

// DateTime Functions Example
function demonstrateDateTime() {
    // Current date and time
    const now = new Date();
    console.log('Current DateTime:', now);
    
    // Specific date creation
    const specificDate = new Date('2024-12-25T10:30:00');
    console.log('Christmas Date:', specificDate);
    
    // Date formatting
    const options = { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    };
    console.log('Formatted Date:', now.toLocaleDateString('en-US', options));
    
    // Date calculations
    const tomorrow = new Date(now);
    tomorrow.setDate(now.getDate() + 1);
    console.log('Tomorrow:', tomorrow.toDateString());
    
    // Time difference
    const timeDiff = specificDate - now;
    const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
    console.log(`Days until Christmas: ${daysDiff}`);
}

demonstrateDateTime();

Explanation:

Date object in JavaScript represents a single moment in time and provides methods for creating, formatting, and manipulating dates

new Date() creates a Date object with the current date and time, while new Date(string) creates a date from a string representation

toLocaleDateString() formats dates according to locale-specific conventions, accepting options for customizing the output format

Date arithmetic can be performed by getting/setting individual components (year, month, day) or by calculating differences in milliseconds

8. jQuery Introduction

// jQuery Example (requires jQuery library)
// <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

$(document).ready(function() {
    // Element selection and manipulation
    $('#myButton').click(function() {
        $('.content').fadeToggle();
        $(this).text($(this).text() === 'Hide' ? 'Show' : 'Hide');
    });
    
    // AJAX with jQuery
    $.ajax({
        url: 'https://jsonplaceholder.typicode.com/posts/1',
        method: 'GET',
        success: function(data) {
            $('#result').html(`<h3>${data.title}</h3><p>${data.body}</p>`);
        },
        error: function(xhr, status, error) {
            console.error('jQuery AJAX Error:', error);
        }
    });
    
    // Dynamic content manipulation
    $('p').hover(
        function() { $(this).css('color', 'blue'); },
        function() { $(this).css('color', 'black'); }
    );
});

Explanation:

jQuery is a fast, lightweight JavaScript library that simplifies HTML document traversal, manipulation, event handling, and AJAX

$(document).ready() ensures code runs only after the DOM is fully loaded, similar to modern addEventListener(‘DOMContentLoaded’)

Selectors in jQuery use CSS-style syntax like $(‘#id’), $(‘.class’), and $(‘element’) to select and manipulate DOM elements

Method chaining allows multiple operations to be performed on selected elements in a single statement, making code more concise

9. Error Handling Example

// Error Handling Example
function divideNumbers(a, b) {
    try {
        // Input validation
        if (typeof a !== 'number' || typeof b !== 'number') {
            throw new TypeError('Both arguments must be numbers');
        }
        
        if (b === 0) {
            throw new Error('Division by zero is not allowed');
        }
        
        const result = a / b;
        console.log(`Result: ${a} ÷ ${b} = ${result}`);
        return result;
        
    } catch (error) {
        console.error('Error occurred:', error.message);
        console.error('Error type:', error.name);
        return null;
    } finally {
        console.log('Division operation completed');
    }
}

// Test cases
divideNumbers(10, 2);      // Success case
divideNumbers(10, 0);      // Error case - division by zero
divideNumbers('10', 2);    // Error case - invalid type

Explanation:

try-catch-finally blocks provide structured error handling, where try contains code that might throw errors

throw statement allows you to create custom errors with specific messages and error types for better debugging

catch block handles any errors thrown in the try block, receiving an error object with properties like message and name

finally block always executes regardless of whether an error occurred, useful for cleanup operations like closing files or connections

10. Top 10 JavaScript Frameworks in Current Industry

  1. React – Building user interfaces with component-based architecture and virtual DOM for efficient updates
  2. Angular – Full-featured framework for building complex enterprise applications with TypeScript support
  3. Vue.js – Progressive framework that’s easy to integrate into existing projects with excellent documentation
  4. Node.js – Server-side JavaScript runtime for building scalable backend applications and APIs
  5. Express.js – Minimal web application framework for Node.js used for building REST APIs and web servers
  6. Next.js – React framework with server-side rendering, static site generation, and built-in optimization features
  7. Svelte – Compile-time framework that generates vanilla JavaScript for smaller bundle sizes and better performance
  8. Nuxt.js – Vue.js framework offering server-side rendering, static site generation, and automatic routing
  9. Gatsby – Static site generator built on React for creating fast, SEO-friendly websites with GraphQL integration
  10. Ember.js – Opinionated framework following convention-over-configuration principle for ambitious web applications

Leave a Reply

Your email address will not be published. Required fields are marked *