Tuesday, September 30, 2025

Javascript Module 72



Javascript  Module 72

If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 

https://onlinecourses2024for.blogspot.com/p/contact-us.html/

Javascript Module 72

  Module 72 : Linting, Formatting, and Testing in JavaScript

1. Introduction

JavaScript projects quickly grow in size and complexity. Without proper linting, formatting, and testing, developers face:



Inconsistent coding styles.

Hard-to-code.

Hidden bugs that are discovered late.

ESLint (for linting), Prettier (for formatting), and Testing frameworks (like Jest and Mocha). Together, they form the backbone of professional-grade JavaScript development.


2. Linting with ESLint

🔹 What is Linting?

Linting is the process of analyzing code for errors, bad practices, and style violations.

Helps catch bugs early.

Enforces coding standards.

Improves collaboration in teams.

🔹 Installing ESLint

npm init -y npm install eslint --save-dev

Initialize ESLint:

npx eslint --init

Choose:

Framework: "None" (if plain JS).

Style guide: "Airbnb" / "Standard" / "Google".

Format: JSON/YAML/JS for config.

This creates an .eslintrc.json file. Example:

{ "env": { "browser": true, "es2021": true }, "extends": ["eslint:recommended"], "rules": { "no-console": "warn", "semi": ["error", "always"] } }

🔹 Example

Code before ESLint:

function add(a, b) { return a + b } console.log(add(2,3))

ESLint Output:

Warn: Missing semicolon.

Warn: Unexpected console statement.

Corrected Code (after ESLint):

function add(a, b) { return a + b; } console.log(add(2, 3));


3. Formatting with Prettier

🔹 What is Prettier?

Opinionated code formatter.


Makes code style consistent across a project.

Works with ESLint (they complement each other).

🔹 Installing Prettier

npm install prettier --save-dev

Create a .prettierrc file:

{ "semi": true, "singleQuote": true, "trailingComma": "es5" }

🔹 Example

Messy Code:

function greet(name){console.log("Hello, "+name)} greet("Rehana")

After Prettier:

function greet(name) { console.log('Hello, ' + name); } greet('Rehana');


4. Combining ESLint and Prettier

ESLint = Catches errors + enforces rules.

Prettier = Handles code style/formatting.

To integrate:

npm install eslint-config-prettier eslint-plugin-prettier --save-dev

Update .eslintrc.json:

{ "extends": ["eslint:recommended", "plugin:prettier/recommended"] }

✅ Now, ESLint and Prettier work together — no conflicts.


5. Testing in JavaScript

🔹 Why Testing?

Testing ensures your code works as expected. Types:








Unit Tests: Test small functions (most common).

Integration Tests: Test multiple modules together.

End-to-End (E2E): Test entire workflows.

🔹 Using Jest (Popular Choice)

Install Jest:

npm install --save-dev jest

Update package.json:

"scripts": { "test": "jest" }

🔹 Example Test

math.js

function add(a, b) { return a + b; } module.exports = add;

math.test.js

const add = require('./math'); test('adds 2 + 3 to equal 5', () => { expect(add(2, 3)).toBe(5); });

Run tests:

npm test

✅ Output: PASS (if correct).


6.  1: ESLint + Prettier Setup

Create a new Node.js project.

Install ESLint and Prettier.

Configure ESLint (.eslintrc.json) to disallow console.log.

Write messy code with console.log.

Run ESLint and Prettier.

Observe auto-fix results.

Goal: Learn how tools enforce consistency.

 2: Writing Tests

Create a function multiply(a, b) in math.js.




Write a Jest test math.test.js to check:

multiply(2, 3) → 6

multiply(5, 0) → 0

multiply(-2, 4) → -8

Run tests.

Goal: Understand how unit tests verify correctness.


3: Integrating Everything

Create a function divide(a, b) in math.js.

Add ESLint rules (no-undef, semi: always).

Use Prettier for consistent formatting.

Write Jest tests to handle edge cases:

Division by zero (should throw error).

Normal division.

Goal: Experience full pipeline: Lint → Format → Test.


7. Research Insights 


Airbnb Style Guide + ESLint: Widely used in industry for consistent JavaScript coding standards.








Prettier: Saves time in code reviews by removing debates over formatting.

Jest: Dominant testing framework (used by Meta, React community).

Expert Advice:

“Automated linting and formatting reduce cognitive load and improve focus on logic instead of style.”

“Testing should be part of development, not an afterthought. Aim for at least 70–80% unit test coverage.”


8. Exercises 

Configure ESLint to enforce camelCase variable names. Write code with snake_case and fix it.

Format a large messy file with Prettier and compare before/after.

 unit tests for a function that finds the largest number in an array.

Create a mini-project: Calculator with add, subtract, multiply, divide, fully linted, formatted, and tested.


Understand how ESLint and Prettier enforce coding quality.

Know how to configure and use linting + formatting tools.

Be able to write and run unit tests in JavaScript.

that simulate workflows.


Sunday, September 28, 2025

Javascript Module 71

 





Javascript  Module 71

If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 

https://onlinecourses2024for.blogspot.com/p/contact-us.html/

Javascript Module 71

   Module 71 : Integrating with REST APIs in JavaScript

1. Introduction to REST APIs

What is an API?


API (Application Programming Interface) is a way for applications to talk to each other.

Example: A weather website fetches live weather data from an API instead of storing all data itself.








REST (Representational State Transfer)

REST is an architecture style for APIs that uses HTTP methods (GET, POST, PUT, DELETE) to interact with resources.

Data is usually exchanged in JSON format.

Why Use REST APIs in JavaScript?

JavaScript runs in browsers and servers (Node.js).

APIs let JavaScript apps fetch data (like tweets, weather info, or stock prices) or send data (like submitting a form).


2. HTTP Methods in REST APIs

GET → Retrieve data (e.g., fetch user list).

POST → Send data (e.g., create new user).

PUT/PATCH → Update existing data (e.g., edit user info).

DELETE → Remove data.


3. Making API Calls in JavaScript

3.1 Using fetch() (Modern Standard)

// Example: Fetching data from a REST API async function getUsers() { try { const response = await fetch("https://jsonplaceholder.typicode.com/users"); // Check if response is OK if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const users = await response.json(); console.log("Fetched Users:", users); } catch (error) { console.error("Error fetching users:", error.message); } } getUsers();

🔎 Explanation:

fetch() is built into modern browsers.

Returns a Promise → must use .then() or async/await.

Always check response.ok for errors.









Use .json() to convert response into usable JavaScript objects.


3.2 Using axios (Popular Library)

// Import axios (Node.js: install with npm install axios) import axios from "axios"; async function getPosts() { try { const response = await axios.get("https://jsonplaceholder.typicode.com/posts"); console.log("Fetched Posts:", response.data); } catch (error) { console.error("Error fetching posts:", error.message); } } getPosts();

🔎 Explanation:

axios simplifies API calls (no need to manually check .ok).

Automatically converts responses to JSON.

Handles errors more cleanly.


4. Sending Data with APIs

4.1 POST Request with fetch

async function createUser() { const newUser = { name: "John Doe", email: "john@example.com" }; try { const response = await fetch("https://jsonplaceholder.typicode.com/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(newUser), }); const data = await response.json(); console.log("User Created:", data); } catch (error) { console.error("Error creating user:", error.message); } } createUser();

🔎 Explanation:

method: "POST" → tells server we’re sending new data.

headers define content type (JSON).

body: JSON.stringify(object) → converts JS object into JSON string.


4.2 PUT & DELETE

// Update User async function updateUser(userId) { const updatedUser = { name: "Jane Doe" }; const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(updatedUser), }); const data = await response.json(); console.log("User Updated:", data); } // Delete User async function deleteUser(userId) { const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`, { method: "DELETE" }); console.log("User Deleted:", response.status); } updateUser(1); deleteUser(1);


5. Handling Errors & Edge Cases

Network errors (no internet).

Server errors (500, 404).

Rate limits (too many requests).

Timeouts (server not responding).

👉 Always use try...catch or .catch() with Promises.

👉 Show user-friendly error messages.


6. Exercises

Exercise 1: Fetch & Display Posts

Fetch posts from https://jsonplaceholder.typicode.com/posts.

Display them in the console or DOM.

Exercise 2: Create a New Post

Send a POST request with a title and body.

Log the server response.

Exercise 3: Update and Delete

Update an existing post’s title.

Delete a post and confirm with response status.

Exercise 4: Error Handling

Try fetching from an invalid URL.

Catch and display the error message.


7. Advanced

7.1 Authentication












Many APIs require API keys or tokens.

async function fetchWithAuth() { const response = await fetch("https://api.example.com/data", { headers: { "Authorization": "Bearer YOUR_API_KEY_HERE" } }); const data = await response.json(); console.log(data); }

7.2 Async/Await vs Promises

// Promise way fetch("https://jsonplaceholder.typicode.com/users") .then(response => response.json()) .then(data => console.log("Promise Example:", data)) .catch(err => console.error(err)); // Async/Await way async function fetchAsync() { try { const res = await fetch("https://jsonplaceholder.typicode.com/users"); const data = await res.json(); console.log("Async/Await Example:", data); } catch (err) { console.error(err); } } fetchAsync();


8. Research Insights 

REST vs GraphQL: REST fetches fixed resources, while GraphQL allows clients to specify exactly what data they need.




CORS (Cross-Origin Resource Sharing): Sometimes APIs block requests from other domains. You may need API keys or server-side proxies.

Rate Limits: Public APIs often limit how many requests you can make per minute/hour.


9. Start with the concept of APIs using analogy (e.g., waiter taking orders = API).

Show a live demo of fetching users from jsonplaceholder.typicode.com.

Gradually move from GET → POST → PUT → DELETE.

Encourage  to modify examples and run them in browser console or Node.js.

Assign exercises at the end.


Understand REST APIs.

Perform GET, POST, PUT, DELETE operations.



Handle errors properly.

Work with fetch() and axios.

Prepare for APIs (authentication, rate limits).


Wednesday, September 24, 2025

Javascript Module 70

 


Javascript  Module 70

If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test And  Give You  certificate  . Go My Contant Page And Fill Your Details Then I Will Contact You Click Here And Go To My Contact Page 

https://onlinecourses2024for.blogspot.com/p/contact-us.html/

Javascript Module 70

  Module 70 : Using JavaScript Libraries (e.g., jQuery, Chart.js).


0) Foundation Concepts

0.1 Library vs Framework vs Plugin

Library: A toolbox of functions/components you call (e.g., jQuery, Chart.js). You control the flow.








Framework: Inversion of control; the framework calls your code (e.g., React, Vue, Angular).

Plugin: Extends a host library (e.g., a jQuery plugin adds a new $.fn.* method).

0.2 Versioning & Compatibility (SemVer)

MAJOR.MINOR.PATCH → Breaking features, new features, bug fixes respectively.

Pin exact versions for reproducible builds. Test upgrades deliberately.

0.3 Installation Options

CDN: Quick start in HTML via <script> tags. Good for prototypes, demos, or when build tools are not used.

npm: npm i jquery chart.js for production/apps with bundlers (Vite, Webpack). Enables tree-shaking, code splitting, and lockfiles.


1) Using jQuery Effectively

1.1 Loading jQuery

CDN (quick demo)

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

 Use the full build (not the “slim” build) if you need AJAX/effects.

npm

npm i jquery

Then in modules/bundlers:

import $ from 'jquery';

1.2 Core Ideas

Selector engine: $(".card[data-id='7']") → returns a jQuery collection.

Chaining: 

$('li').addClass('todo').attr('role','listitem').

Each: $('li').each((i, el) => console.log(i, el));

1.3 DOM Selection & Traversal

const $items = $('ul#tasks > li');

$items.first().text('First task!');

$items.eq(2).addClass('highlight');

$items.parent().addClass('has-tasks');

$items.filter('.done').hide();

$items.not('.done').show();

1.4 Events & Delegation (Performance & Dynamic Content)

// Bad: binds to each button individually

$('.remove').on('click', function(){ /* ... */ });



// Good: delegate to a static parent

$('#task-list').on('click', '.remove', function(){

 $(this).closest('li').remove();

});

Why delegation? Future items added dynamically also work; fewer listeners → faster.

1.5 DOM Manipulation & Effects

$('#add').on('click', function(){

 const text = $('#newTask').val().trim();

 if (!text) return;

 $('#task-list').append(`<li>${text} <button class="remove">×</button></li>`);

 $('#newTask').val('').focus();

});



$('#task-list').on('mouseenter', 'li', function(){ $(this).addClass('hover'); });

$('#task-list').on('mouseleave', 'li', function(){ $(this).removeClass('hover'); });

1.6 AJAX with jQuery vs fetch

// jQuery

$.getJSON('/api/todos').done(data => {

 $('#task-count').text(data.length);

});



// Native fetch (modern standard)

fetch('/api/todos')

 .then(res => res.json())

 .then(data => $('#task-count').text(data.length));

 prefer fetch for new code; jQuery AJAX is handy when you’re already in jQuery land.

1.7 Writing a Tiny jQuery Plugin

(function($){

 $.fn.highlight = function(color = '#fffbcc'){

   return this.each(function(){

     const $el = $(this);

     const original = $el.css('backgroundColor');

     $el.css('backgroundColor', color);

     setTimeout(() => $el.css('backgroundColor', original), 600);

   });

 };

})(jQuery);



// Usage:

$('li.new').highlight('#d1ffd1');

1.8 Pitfalls 

Cache selections: const $rows = $('tr'); then reuse.

Use delegation for dynamic lists.

Don’t mix raw nodes and jQuery objects accidentally: $(el) vs el.

Keep logic (data) separate from presentation (DOM) as much as feasible.


2) Chart.js for Data Visualization

2.1 Loading Chart.js

CDN









<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

npm

npm i chart.js

import { Chart } from 'chart.js';

2.2 Basic Line Chart

<canvas id="salesChart" width="400" height="220"></canvas>

<script>

 const ctx = document.getElementById('salesChart').getContext('2d');

 const salesChart = new Chart(ctx, {

   type: 'line',

   data: {

     labels: ['Jan','Feb','Mar','Apr','May','Jun'],

     datasets: [{

       label: 'Revenue ($k)',

       data: [12, 19, 13, 25, 22, 30],

       fill: false,

       tension: 0.25

     }]

   },

   options: {

     responsive: true,

     plugins: {

       title: { display: true, text: 'Half-Year Revenue' },

       legend: { position: 'bottom' },

       tooltip: { enabled: true }

     },

     scales: {

       y: { beginAtZero: true }

     }

   }

 });

</script>

2.3 Updating Data Dynamically

function pushPoint(chart, label, value){

 chart.data.labels.push(label);

 chart.data.datasets[0].data.push(value);

 chart.update();

}



// Example

pushPoint(salesChart, 'Jul', 28);

2.4 Destroy/Recreate to Avoid Duplicates

if (window._chart) window._chart.destroy();

window._chart = new Chart(ctx, config);

2.5 Time-Series (with Luxon adapter)

<script src="https://cdn.jsdelivr.net/npm/luxon"></script>

<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon"></script>

const timeChart = new Chart(ctx, {

 type: 'line',

 data: {

   datasets: [{

     label: 'CPU %',

     data: [

       { x: '2025-01-01T00:00:00Z', y: 42 },

       { x: '2025-01-01T01:00:00Z', y: 51 }

     ]

   }]

 },

 options: {

   parsing: false,

   scales: {

     x: { type: 'time', time: { unit: 'hour' } },

     y: { beginAtZero: true, max: 100 }

   }

 }

});

2.6 Performance Tips

Prefer fewer points or enable decimation (built-in).

Turn off animations for very large datasets.

Use parsing: false when your data already has {x,y} pairs.

Keep one Chart instance; update data instead of recreating frequently.

2.7 Accessibility

Provide a text/table fallback or downloadable CSV.

Use descriptive titles and labels.

Ensure sufficient color contrast (don’t rely on color alone).


3) jQuery + Chart.js Together (Mini App)

Goal: A simple “Scores Dashboard” where a form (jQuery) feeds a live chart (Chart.js).



<!DOCTYPE html>

<html lang="en">

<head>

 <meta charset="UTF-8" />

 <meta name="viewport" content="width=device-width, initial-scale=1.0" />

 <title>Scores Dashboard</title>

 <style>

   body { font-family: system-ui, sans-serif; margin: 2rem; }

   form, canvas { max-width: 680px; }

   .row { display: flex; gap: .5rem; margin-block: .5rem; }

   label { min-width: 6rem; }

 </style>

</head>

<body>

 <h1>Scores Dashboard</h1>

 <form id="scoreForm">

   <div class="row"><label>Label</label><input id="label" required /></div>

   <div class="row"><label>Score</label><input id="value" type="number" min="0" max="100" required /></div>

   <button type="submit">Add</button>

   <button type="button" id="reset">Reset</button>

 </form>



 <canvas id="scoreChart" height="240"></canvas>



 <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

 <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

 <script>

   const ctx = document.getElementById('scoreChart').getContext('2d');

   const config = {

     type: 'bar',

     data: { labels: [], datasets: [{ label: 'Score', data: [] }] },

     options: { scales: { y: { beginAtZero: true, max: 100 } } }

   };

   const chart = new Chart(ctx, config);



   $('#scoreForm').on('submit', function(e){


4) Exercises 

Exercise A — DOM & Events with jQuery

Build a To-Do list where items can be added, marked done, filtered (All/Active/Done), and removed. Use event delegation.

Key Points: Cache selectors, separate state (array of todos) from DOM, update efficiently.

Hint:

const todos = [];

$('#add').on('click', () => { /* push to array, render() */ });

$('#list').on('click', '.toggle', (e) => { /* find by id, flip done */ });

Exercise B — Line Chart with Live Updates

Create a Chart.js line chart that appends a random point every second for 30 seconds.


Key Points: Keep a single Chart instance; call chart.update(); stop timer afterward.

Exercise C — Tooltips & Legend Customization

 Add custom tooltip callbacks that show label: value%. Move legend to the bottom.

Key Points: options.plugins.tooltip.callbacks, options.plugins.legend.position.

Exercise D — Mixed Chart

Create a chart with two datasets: bars for quantity and a line for average price. Use a secondary axis for price.

Key Points: scales: { y: {...}, y1: { position: 'right' } } and set dataset.yAxisID.

Exercise E — Form + Chart Integration

Extend the “Scores Dashboard” to allow editing existing labels/values by clicking a bar.

Key Points: Use chart events: read active elements via chart.getElementsAtEventForMode.


5) (Capstone)

Title: Weather Trends Mini-Portal (jQuery + Chart.js)








Build a small web app that displays the next 7 days of temperature highs/lows for a chosen city. Provide both a data table (for accessibility) and a chart. Compare two data-loading approaches: (1) direct API call via fetch, (2) loading from a local JSON file (offline mode). 


Javascript Module 78

  Javascript   Module 78 If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test...