JavaScript
JavaScript is a versatile, high-level, and interpreted programming language. In the context of frontend development, it is the “brain” of the web page, enabling interactivity beyond static HTML and CSS.
To master JavaScript, it is crucial to distinguish between the language itself (ECMAScript) and the Web APIs provided by the browser environment.
Part 1: Language Fundamentals (ECMAScript)
Section titled “Part 1: Language Fundamentals (ECMAScript)”These concepts are the core of JavaScript. They work the same way whether you are running code in a browser, on a server (Node.js), or in other environments.
1. Variables and Scope
Section titled “1. Variables and Scope”Variables store data. Modern JavaScript uses let and const.
const: For values that won’t be reassigned. (Default choice).let: For values that will be reassigned.var: Legacy variable declaration. Avoid using it due to hoisting and lack of block scope.
const birthYear = 1995; // Cannot be changedlet age = 30; // Can be changedage = 31;
if (true) { let blockScoped = 'I only exist here'; var functionScoped = 'I leak out of this block';}// console.log(blockScoped); // ReferenceErrorconsole.log(functionScoped); // works2. Data Types
Section titled “2. Data Types”JavaScript has 7 primitive types and an Object type.
- Primitives:
String,Number,Boolean,null,undefined,Symbol,BigInt. - Objects: Objects, Arrays, Functions.
const name = 'Alice'; // Stringconst total = 42; // Numberconst isStudent = true; // Booleanlet data = null; // null (intentional empty value)let result; // undefined (not yet assigned)3. Functions
Section titled “3. Functions”Functions are blocks of code designed to perform a particular task.
- Function Declaration: Hoisted, can be called before they are defined.
- Function Expression: Not hoisted.
- Arrow Functions: Concise syntax, useful for callbacks. Note: They do not have their own
this.
// Declarationfunction greet(name) { return `Hello, ${name}!`;}
// Arrow Functionconst multiply = (a, b) => a * b;
// Higher-Order Function (takes another function as argument)[1, 2, 3].forEach((num) => console.log(num));4. Arrays and Transformation
Section titled “4. Arrays and Transformation”Arrays are used to store lists of data.
Common methods:
map(): Transforms every element, returns a new array.filter(): Returns a new array with elements that pass a test.reduce(): Aggregates the array into a single value.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((n) => n * 2); // [2, 4, 6, 8, 10]const evens = numbers.filter((n) => n % 2 === 0); // [2, 4]const sum = numbers.reduce((acc, current) => acc + current, 0); // 15
// Useful for checking conditionsconst hasLargeNum = numbers.some((n) => n > 10); // falseconst allPositive = numbers.every((n) => n > 0); // true5. Strings and Text Manipulation
Section titled “5. Strings and Text Manipulation”Strings in JavaScript are immutable, meaning methods return a new string rather than modifying the original.
- Template Literals: Use backticks (
`) for interpolation and multi-line strings. - Methods:
trim(),includes(),split(),slice().
const str = ' JavaScript is Awesome! ';
console.log(str.trim()); // "JavaScript is Awesome!"console.log(str.includes('Script')); // trueconsole.log(str.toLowerCase()); // " javascript is awesome! "
const words = str.trim().split(' '); // ["JavaScript", "is", "Awesome!"]const firstWord = str.trim().slice(0, 10); // "JavaScript"6. Objects and Classes
Section titled “6. Objects and Classes”Objects are used to store keyed collections. Classes (ES6) are syntactic sugar over prototypal inheritance.
// Object Literalconst user = { name: 'John', greet() { console.log(`Hello, I'm ${this.name}`); },};
// Class (Template for objects)class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a noise.`); }}
class Dog extends Animal { speak() { console.log(`${this.name} barks.`); }}
const d = new Dog('Mitzie');d.speak(); // "Mitzie barks."7. Asynchronous JavaScript
Section titled “7. Asynchronous JavaScript”JavaScript is single-threaded, meaning it can only do one thing at a time. Asynchronous patterns allow it to handle long-running tasks (like fetching data) without freezing the UI.
- Promises: Represents a value that will be available in the future.
- Async/Await: Modern, readable way to handle Promises.
// Using Promisesconst fetchData = () => { return new Promise((resolve, reject) => { setTimeout(() => resolve('Data loaded!'), 1000); });};
// Using Async/Awaitasync function displayData() { console.log('Loading...'); const result = await fetchData(); console.log(result); // "Data loaded!"}Part 2: Browser APIs (Web APIs)
Section titled “Part 2: Browser APIs (Web APIs)”Browser APIs are tools provided by the browser environment. These are not part of the core JavaScript language, but they are accessible via JavaScript when running in a browser.
1. The DOM (Document Object Model)
Section titled “1. The DOM (Document Object Model)”The DOM is a structural representation of the HTML document. JavaScript uses it to change content and styles.
// Selecting elementsconst title = document.querySelector('h1');const buttons = document.querySelectorAll('.btn');
// Modifying content and styletitle.textContent = 'New Title';title.style.color = 'blue';
// Creating and Appendingconst newDiv = document.createElement('div');newDiv.innerHTML = '<p>Newly created paragraph</p>';document.body.appendChild(newDiv);2. Event Handling
Section titled “2. Event Handling”Events allow you to make the page interactive by responding to user actions.
const btn = document.querySelector('#submit');
btn.addEventListener('click', (event) => { console.log('Button clicked!'); console.log('Event details:', event);});3. Fetch API
Section titled “3. Fetch API”The modern way to make network requests (AJAX).
async function getUser() { try { const response = await fetch('https://api.github.com/users/octocat'); if (!response.ok) throw new Error('User not found');
const data = await response.json(); console.log(data.login); } catch (error) { console.error('Error fetching data:', error); }}4. Storage APIs
Section titled “4. Storage APIs”Used to save data in the user’s browser.
localStorage: Persists even after the browser is closed.sessionStorage: Persists only for the duration of the page session.
// Saving datalocalStorage.setItem('theme', 'dark');
// Retrieving dataconst currentTheme = localStorage.getItem('theme');console.log(currentTheme); // 'dark'Summary: Language vs. API
Section titled “Summary: Language vs. API”| Concept | Layer | Examples |
|---|---|---|
| Variables/Loops | Language (Engine) | let, for, if |
| Logic/Math | Language (Engine) | Math.random(), typeof |
| DOM | Browser API | document.body, window.innerWidth |
| Network | Browser API | fetch(), XMLHttpRequest |
| Timers | Browser API | setTimeout(), setInterval() |
| Storage | Browser API | localStorage, IndexedDB |