learn_JavaScript

JavaScript Notes


📝 Variable Declarations: var, let, const


📦 Understanding Scope and Block


🔀 Conditional Statements


🔁 Loops


String Properties & Methods


🔢 Number Function


🔢 Number Methods & Usage


📐 Math Object & Methods


📚 More Math Methods

For a complete list of Math methods and properties, visit the MDN Math Reference


🧩 Functions


📚 Arrays & Array Methods


🏗️ Objects


🧩 Object Inheritance


👨‍👩‍👧‍👦 Parent-Child Class Relationships


🏛️ Classes


📄 JSON (JavaScript Object Notation)


⚠️ Error Handling


🌐 The DOM (Document Object Model) in Web Development


🏷️ Accessing Elements in the DOM


🛠️ Modifying HTML and CSS with JavaScript


🖱️ Handling Events


🧑‍💻 Example: Putting It All Together

<!DOCTYPE html>
<html>
<head>
  <style>
    .highlight { color: orange; font-weight: bold; }
  </style>
</head>
<body>
  <h1 id="main-title">Hello World</h1>
  <p class="intro">Welcome to my website.</p>
  <button>Click Me</button>

  <script>
    // Access by ID
    let title = document.getElementById('main-title');
    title.textContent = 'Welcome to the DOM!';

    // Access by class
    let intro = document.querySelector('.intro');
    intro.classList.add('highlight');

    // Access by tag
    let button = document.querySelector('button');
    button.addEventListener('click', function() {
      alert('Button clicked!');
      button.style.backgroundColor = 'red';
    });
  </script>
</body>
</html>

📚 More Resources


🖱️ Event Listeners with Functions

📌 Syntax

element.addEventListener(eventType, handlerFunction);

🟢 Example 1: Using a Named Function

<button id="greetBtn">Greet</button>
<p id="message"></p>

<script>
  function showGreeting() {
    document.getElementById('message').textContent = 'Hello, user!';
  }

  let button = document.getElementById('greetBtn');
  button.addEventListener('click', showGreeting);
</script>

🟢 Example 2: Using an Anonymous Function

<button id="colorBtn">Change Color</button>
<div id="box" style="width:100px; height:100px; background:lightgray;"></div>

<script>
  document.getElementById('colorBtn').addEventListener('click', function() {
    document.getElementById('box').style.backgroundColor = 'skyblue';
  });
</script>

🟢 Example 3: Using an Arrow Function

<input id="nameInput" placeholder="Type your name...">
<button id="sayHiBtn">Say Hi</button>
<p id="output"></p>

<script>
  document.getElementById('sayHiBtn').addEventListener('click', () => {
    const name = document.getElementById('nameInput').value;
    document.getElementById('output').textContent = `Hi, ${name || 'stranger'}!`;
  });
</script>

🟢 Example 4: Passing the Event Object

<button id="logBtn">Log Event</button>

<script>
  document.getElementById('logBtn').addEventListener('click', function(event) {
    console.log('Event type:', event.type);
    console.log('Button text:', event.target.textContent);
  });
</script>

🟢 Example 5: Removing an Event Listener

<button id="onceBtn">Click Me Once</button>
<p id="onceMsg"></p>

<script>
  function handleOnce() {
    document.getElementById('onceMsg').textContent = 'Button clicked! Listener removed.';
    document.getElementById('onceBtn').removeEventListener('click', handleOnce);
  }

  document.getElementById('onceBtn').addEventListener('click', handleOnce);
</script>

📚 More on Events


🌐 APIs and Web Storage API

🤖 What is an API?


💾 Web Storage API

📦 localStorage

Basic Usage:

// Set an item
localStorage.setItem('username', 'Alice');

// Get an item
let user = localStorage.getItem('username'); // 'Alice'

// Remove an item
localStorage.removeItem('username');

// Clear all items
localStorage.clear();

Storing Objects:

let user = { name: 'Bob', age: 30 };
localStorage.setItem('user', JSON.stringify(user));

let storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser.name); // 'Bob'

📦 sessionStorage

Basic Usage:

// Set an item
sessionStorage.setItem('theme', 'dark');

// Get an item
let theme = sessionStorage.getItem('theme'); // 'dark'

// Remove an item
sessionStorage.removeItem('theme');

// Clear all items
sessionStorage.clear();

Storing Arrays:

let colors = ['red', 'green', 'blue'];
sessionStorage.setItem('colors', JSON.stringify(colors));

let storedColors = JSON.parse(sessionStorage.getItem('colors'));
console.log(storedColors[1]); // 'green'

🧑‍💻 Example: Using localStorage and sessionStorage in a Web Page

<!DOCTYPE html>
<html>
<body>
  <input id="nameInput" placeholder="Enter your name">
  <button id="saveBtn">Save to localStorage</button>
  <button id="loadBtn">Load from localStorage</button>
  <p id="output"></p>

  <script>
    document.getElementById('saveBtn').addEventListener('click', function() {
      const name = document.getElementById('nameInput').value;
      localStorage.setItem('savedName', name);
      alert('Name saved!');
    });

    document.getElementById('loadBtn').addEventListener('click', function() {
      const name = localStorage.getItem('savedName') || 'No name found';
      document.getElementById('output').textContent = name;
    });
  </script>
</body>
</html>

⚠️ Notes and Best Practices


📚 More Resources


📦 JavaScript Modules: import & export

📚 What are Modules?


🚚 Exporting from a Module


📥 Importing from a Module


📝 Example: Using Modules in Practice

mathUtils.js

export const PI = 3.14;
export function square(x) { return x * x; }
export default function cube(x) { return x * x * x; }

main.js

import cube, { PI, square } from './mathUtils.js';
console.log(PI);         // 3.14
console.log(square(4));  // 16
console.log(cube(3));    // 27

⚠️ Notes and Best Practices


📚 More Resources


🔼 Higher Order Functions

🧠 What is a Higher Order Function?


📥 Passing Functions as Arguments


📤 Returning Functions from Functions


🔄 Common Higher Order Array Methods

.map()

.filter()

.reduce()

.forEach()

.find()


🧩 Example: Combining Higher Order Functions

let numbers = [1, 2, 3, 4, 5, 6];

// Double the even numbers and sum them
let result = numbers
  .filter(n => n % 2 === 0)   // [2, 4, 6]
  .map(n => n * 2)            // [4, 8, 12]
  .reduce((sum, n) => sum + n, 0); // 24

console.log(result); // 24

⚠️ Notes and Best Practices


📚 More Resources