JavaScript Basics - Interactive Programming for the Web

Comprehensive introduction to JavaScript, the programming language that powers interactive web experiences. Master variables, functions, DOM manipulation, modern ES6+ syntax, and asynchronous programming.


What is JavaScript?

JavaScript is a high-level, interpreted programming language that enables interactive web pages and is an essential part of web applications. It allows you to implement complex features on web pages and is supported by all modern web browsers.

Including JavaScript in HTML

<script>
    console.log("Hello from JavaScript!");
</script>
<script src="script.js"></script>

Deferred Loading (Best Practice)

<script src="script.js" defer></script>

Variables and Data Types

Variable Declarations

// var (legacy, avoid using)
var oldVariable = "deprecated";

// let (block-scoped, can be reassigned)
let age = 25;
age = 26; // OK

// const (block-scoped, cannot be reassigned)
const PI = 3.14159;
// PI = 3.14; // Error: Assignment to constant variable

// Best practice: Use const by default, let when needed

Primitive Data Types

// String
let name = "Alice";
let greeting = 'Hello';

// Template literals (ES6+)
let message = `Hello, ${name}! Welcome to JavaScript.`;

// Number
let count = 42;
let price = 19.99;

// Boolean
let isActive = true;
let isCompleted = false;

// Undefined and Null
let notDefined;        // undefined
let emptyValue = null; // explicit empty value

// Symbol (ES6+)
let uniqueKey = Symbol('key');

// BigInt (ES2020)
let bigNumber = 123456789012345678901234567890n;

Objects and Arrays

// Object literal
let person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    hobbies: ["reading", "gaming", "coding"],
    address: {
        street: "123 Main St",
        city: "Anytown",
        country: "USA"
    },
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
};

// Array
let numbers = [1, 2, 3, 4, 5];
let mixedArray = [1, "hello", true, {key: "value"}];

// Useful array methods
numbers.push(6);           // Add to end
numbers.pop();            // Remove from end
numbers.shift();          // Remove from beginning
numbers.unshift(0);       // Add to beginning
let sliced = numbers.slice(1, 4);  // [1, 2, 3]
let doubled = numbers.map(x => x * 2);   // [2, 4, 6, 8, 10]
let evenNumbers = numbers.filter(x => x % 2 === 0); // [2, 4]

Functions and Control Flow

Function Declarations

// Function declaration (hoisted)
function greetUser(name) {
    return `Hello, ${name}!`;
}

// Function expression
const greetUser = function(name) {
    return `Hello, ${name}!`;
};

// Arrow functions (ES6+)
const greetUser = (name) => {
    return `Hello, ${name}!`;
};

// One-line arrow function
const greetUser = name => `Hello, ${name}!`;

// Immediately Invoked Function Expression (IIFE)
(function() {
    console.log("Executed immediately!");
})();

## DOM Manipulation

The Document Object Model (DOM) represents the HTML page as a tree structure that JavaScript can modify:

### Selecting Elements
```javascript
// By ID (returns single element)
const header = document.getElementById('main-header');

// By class (returns HTMLCollection)
const buttons = document.getElementsByClassName('btn');

// By tag name (returns HTMLCollection)
const paragraphs = document.getElementsByTagName('p');

// By CSS selector (returns NodeList - modern approach)
const loginForm = document.querySelector('#login-form');
const menuItems = document.querySelectorAll('.menu-item');

// Getting parent/children/siblings
const parent = element.parentElement;
const children = element.children;
const firstChild = element.firstElementChild;
const nextSibling = element.nextElementSibling;

Modifying Elements

// Change text content
element.textContent = "New text content";
element.innerHTML = "<strong>HTML content</strong>"; // Be careful with XSS

// Modify attributes
image.src = "new-image.jpg";
link.href = "https://new-url.com";
input.placeholder = "Enter your name";

// Add/remove CSS classes
element.classList.add('active');
element.classList.remove('hidden');
element.classList.toggle('visible');

// Change styles
element.style.color = 'red';
element.style.fontSize = '20px';
element.style.display = 'none';

Creating and Removing Elements

// Create new element
const newDiv = document.createElement('div');
newDiv.className = 'notification';
newDiv.textContent = 'Success!';

// Append to document
document.body.appendChild(newDiv);

// Insert before another element
parentElement.insertBefore(newDiv, referenceElement);

// Remove element
element.remove(); // Modern way
element.parentNode.removeChild(element); // Older way

Event Handling

Basic Event Listeners

// Get the element
const button = document.getElementById('myButton');

// Add click event listener
button.addEventListener('click', function(event) {
    console.log('Button clicked!');
    event.preventDefault(); // Prevent default behavior
});

// Multiple events on same element
button.addEventListener('mouseenter', handleMouseEnter);
button.addEventListener('mouseleave', handleMouseLeave);

// Remove event listener
button.removeEventListener('click', clickHandler);

Event Types

// Mouse events
element.addEventListener('click', handleClick);
element.addEventListener('dblclick', handleDoubleClick);
element.addEventListener('mouseover', handleMouseOver);
element.addEventListener('mouseout', handleMouseOut);

// Keyboard events
input.addEventListener('keyup', handleKeyUp);
input.addEventListener('keydown', handleKeyDown);
input.addEventListener('keypress', handleKeyPress);

// Form events
form.addEventListener('submit', handleSubmit);
input.addEventListener('focus', handleFocus);
input.addEventListener('blur', handleBlur);
textarea.addEventListener('input', handleInput);

// Window events
window.addEventListener('load', handleLoad);
window.addEventListener('resize', handleResize);
window.addEventListener('scroll', handleScroll);

Event Object

function handleClick(event) {
    // Prevent default action
    event.preventDefault();

    // Stop event bubbling
    event.stopPropagation();

    // Get target element
    const target = event.target;

    // Get mouse coordinates
    const x = event.clientX;
    const y = event.clientY;

    // Get key for keyboard events
    const key = event.key;

    console.log(`Clicked at ${x}, ${y}`);
}

Asynchronous JavaScript

Callbacks (Legacy approach)

```javascript function fetchData(callback) { setTimeout(() => { const data = {user: "John", id: 123}; callback(null, data); // First param is