JavaScript

Learn the language that powers the interactive web. JavaScript is essential for creating dynamic, responsive websites and web applications.

JavaScript Basics

What is JavaScript?

JavaScript is a high-level, interpreted programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. It enables interactive web pages and is an essential part of web applications.

Originally created to "make web pages alive," JavaScript now runs on the server as well as on mobile devices, making it one of the most versatile and widely used programming languages in the world.

Key Features of JavaScript

  • Client-side scripting: Runs in the user's browser, reducing server load
  • Event-driven: Responds to user actions like clicks, form submissions, and key presses
  • Dynamic typing: Variables can hold different types of data
  • Object-oriented: Uses objects and prototypes for inheritance
  • Functional programming: Supports first-class functions and higher-order functions
  • Asynchronous programming: Can execute code without blocking other operations
  • Cross-platform: Works across different browsers and operating systems

Getting Started with JavaScript

You can add JavaScript to an HTML page in three ways:

1. Inline JavaScript

<button onclick="alert('Hello, World!')">Click Me</button>

2. Internal JavaScript

<script>
function sayHello() {
alert('Hello, World!');
}
</script>

3. External JavaScript

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

Where script.js contains your JavaScript code. This is the recommended approach for larger projects.

JavaScript Syntax

Variables
// Modern variable declarations
let name = "John"; // Block-scoped variable
const age = 30; // Constant (cannot be reassigned)

// Legacy variable declaration
var job = "Developer"; // Function-scoped variable

Use let for variables that will change, and const for variables that won't. Avoid using var in modern JavaScript.

Data Types
// Primitive types
let name = "John"; // String
let age = 30; // Number
let isActive = true; // Boolean
let user = null; // Null
let points; // Undefined
let id = Symbol("id"); // Symbol
let bigNumber = 9007199254740991n; // BigInt

// Object type
let person = {
name: "John",
age: 30
};
Functions
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}

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

// Arrow function
const greetUser = (name) => `Hello, ${name}!`;
Control Flow
// Conditional statements
if (age >= 18) {
console.log("Adult");
} else if (age >= 13) {
console.log("Teenager");
} else {
console.log("Child");
}

// Loops
for (let i = 0; i < 5; i++) {
console.log(i);
}

let j = 0;
while (j < 5) {
console.log(j);
j++;
}

DOM Manipulation

One of JavaScript's most important features is its ability to manipulate the Document Object Model (DOM), which represents the structure of an HTML document.

Selecting Elements

// Get element by ID
const header = document.getElementById("header");

// Get elements by class name
const items = document.getElementsByClassName("item");

// Get elements by tag name
const paragraphs = document.getElementsByTagName("p");

// Query selector (returns first match)
const firstButton = document.querySelector("button");

// Query selector all (returns all matches)
const allButtons = document.querySelectorAll("button");

Modifying Elements

// Changing content
element.textContent = "New text"; // Text only
element.innerHTML = "<span>New HTML</span>"; // HTML content

// Changing attributes
element.setAttribute("class", "new-class");
element.id = "new-id";

// Changing styles
element.style.color = "blue";
element.style.fontSize = "16px";

// Adding/removing classes
element.classList.add("active");
element.classList.remove("inactive");
element.classList.toggle("visible");

Creating and Removing Elements

// Creating elements
const newDiv = document.createElement("div");
newDiv.textContent = "I'm a new div";

// Adding elements to the DOM
document.body.appendChild(newDiv); // Add as last child
parentElement.insertBefore(newDiv, referenceElement); // Add before another element

// Removing elements
element.remove(); // Remove the element
parentElement.removeChild(childElement); // Remove a child element

Event Handling

// Adding event listeners
element.addEventListener("click", function() {
console.log("Element clicked!");
});

// Using arrow functions
element.addEventListener("mouseover", (event) => {
event.target.style.color = "red";
});

// Removing event listeners
function handleClick() {
console.log("Clicked!");
}

element.addEventListener("click", handleClick);
element.removeEventListener("click", handleClick);

JavaScript in Modern Web Development

Frontend Frameworks

Modern web development often uses JavaScript frameworks to build complex user interfaces:

  • React: A library for building user interfaces with reusable components
  • Vue.js: A progressive framework for building UIs
  • Angular: A platform and framework for building single-page client applications
  • Svelte: A compiler that converts your components into highly efficient JavaScript
Backend JavaScript

JavaScript isn't just for browsers anymore. It can also run on servers:

  • Node.js: A JavaScript runtime built on Chrome's V8 JavaScript engine
  • Express.js: A minimal and flexible Node.js web application framework
  • Next.js: A React framework with server-side rendering capabilities
  • Deno: A secure runtime for JavaScript and TypeScript
Modern JavaScript Features

JavaScript has evolved significantly with ECMAScript updates:

  • Arrow Functions: Shorter syntax for writing functions
  • Destructuring: Extract data from arrays and objects easily
  • Spread/Rest Operators: Work with arrays and objects more efficiently
  • Async/Await: Write asynchronous code that looks synchronous
  • Modules: Organize code into reusable, encapsulated pieces
Tools and Ecosystem

JavaScript development is supported by a rich ecosystem of tools:

  • npm/yarn: Package managers for JavaScript
  • Webpack/Vite: Module bundlers for applications
  • ESLint: Code linting tool for identifying problematic patterns
  • Jest/Mocha: Testing frameworks
  • TypeScript: A strongly typed programming language that builds on JavaScript

Common JavaScript Use Cases

Form Validation

JavaScript is commonly used to validate form inputs before submission:

const form = document.getElementById("myForm");
const emailInput = document.getElementById("email");

form.addEventListener("submit", function(event) {
const emailValue = emailInput.value;
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if (!emailPattern.test(emailValue)) {
alert("Please enter a valid email address");
event.preventDefault(); // Prevent form submission
}
});

API Requests

JavaScript can fetch data from APIs and update the page dynamically:

// Using Fetch API with async/await
async function getUsers() {
try {
const response = await fetch('https://api.example.com/users');

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

const data = await response.json();
console.log(data);

// Update the UI with the data
displayUsers(data);
} catch (error) {
console.error('Error fetching users:', error);
}
}

getUsers();

Interactive UI Elements

JavaScript can create interactive UI elements like tabs, accordions, and modals:

// Simple tab implementation
const tabs = document.querySelectorAll('.tab');
const tabContents = document.querySelectorAll('.tab-content');

tabs.forEach(tab => {
tab.addEventListener('click', () => {
// Remove active class from all tabs and contents
tabs.forEach(t => t.classList.remove('active'));
tabContents.forEach(content => content.classList.remove('active'));

// Add active class to clicked tab and corresponding content
tab.classList.add('active');
const tabId = tab.getAttribute('data-tab');
document.getElementById(tabId).classList.add('active');
});
});

Animations and Visual Effects

JavaScript can create animations and visual effects:

// Simple fade-in animation
function fadeIn(element) {
let opacity = 0;
element.style.opacity = opacity;
element.style.display = 'block';

const timer = setInterval(() => {
if (opacity >= 1) {
clearInterval(timer);
}

opacity += 0.1;
element.style.opacity = opacity;
}, 50);
}

// Usage
const element = document.getElementById('myElement');
fadeIn(element);

Learning Resources

Continue your JavaScript journey with these resources: