JavaScript and Frameworks Guide
JavaScript and Frameworks Guide
## Introduction
---
## Table of Contents
---
---
```javascript
// Variables - var (legacy), let (block-scoped), const (immutable)
var name = "John"; // function-scoped, hoisted
let age = 25; // block-scoped, not hoisted
const city = "Delhi"; // constant, cannot be reassigned
// Data types
const num = 42; // Number
const str = "Hello"; // String
const bool = true; // Boolean
const obj = { name: "Alice", age: 30 }; // Object
const arr = [1, 2, 3]; // Array
const empty = null; // Null
let undefined_var; // Undefined
const symbol = Symbol('id'); // Symbol
```
```javascript
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression
const add = function(a, b) {
return a + b;
};
```javascript
// Global scope
let globalVar = "global";
function scopeExample() {
// Function scope
let functionVar = "function";
if (true) {
// Block scope
let blockVar = "block";
[Link](blockVar); // "block"
}
// [Link](blockVar); // Error: blockVar is not defined
}
```javascript
// Object literals
const person = {
name: "Alice",
age: 30,
greet() {
[Link](`Hello, I'm ${[Link]}`);
}
};
// Constructor function
function Car(brand, model) {
[Link] = brand;
[Link] = model;
}
[Link] = function() {
return `${[Link]} ${[Link]}`;
};
// Prototypal inheritance
const animal = { eat() { return "eating"; } };
const dog = [Link](animal);
[Link] = function() { return "woof"; };
```
```javascript
const arr = [1, 2, 3, 4, 5];
---
The Document Object Model (DOM) represents the structure of HTML documents.
JavaScript manipulates the DOM to create dynamic, interactive user interfaces.
```javascript
// Get single element
const element = [Link]('myId');
const first_div = [Link]('.my-class');
```javascript
const el = [Link]('box');
// Text content
[Link] = "New text"; // Sets plain text
[Link]([Link]); // Reads text
// Properties
[Link] = "newId";
[Link] = "new-class";
[Link] = "value"; // data-* attributes
```
```javascript
const box = [Link]('.box');
// Inline styles
[Link] = 'blue';
[Link] = '20px';
[Link] = '1px solid black';
// Adding/removing classes
[Link]('active');
[Link]('inactive');
[Link]('highlight');
[Link]('active'); // true/false
```
```javascript
const button = [Link]('button');
// Multiple events
[Link]('keydown', (e) => {
if ([Link] === 'Enter') {
[Link]('Enter pressed');
}
});
// Event delegation
[Link]('click', (e) => {
if ([Link]('.item')) {
[Link]('Item clicked:', [Link]);
}
});
// Remove listener
const handler = () => [Link]('clicked');
[Link]('click', handler);
[Link]('click', handler);
```
// Add to DOM
const container = [Link]('.container');
[Link](newDiv);
[Link](newDiv, [Link]);
// Remove element
[Link]();
[Link](newDiv);
// Clone element
const clone = [Link](true); // deep copy
```
---
Modern JavaScript (ES6/ES2015 and beyond) introduced syntax improvements that made
code more readable, efficient, and maintainable.
```javascript
// Traditional function
const add_old = function(a, b) {
return a + b;
};
// Multiple statements
const calculate = (x, y) => {
const sum = x + y;
const product = x * y;
return { sum, product };
};
```javascript
// var: function-scoped, hoisted, can be redeclared
var a = 1;
var a = 2; // No error
```javascript
const name = "Alice";
const age = 30;
// Old way
const msg1 = "Hello " + name + ", you are " + age + " years old.";
// Template literal
const msg2 = `Hello ${name}, you are ${age} years old.`;
// Multi-line strings
const multiline = `
Line 1
Line 2
Line 3
`;
// Tagged templates
const highlight = (strings, ...values) => {
return [Link]((acc, str, i) => {
return acc + str + (values[i] ? `<strong>${values[i]}</strong>` : '');
}, '');
};
### Destructuring
```javascript
// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
[Link](first); // 1
[Link](rest); // [3, 4, 5]
// Object destructuring
const person = { name: "Bob", age: 25, city: "NYC" };
const { name, age } = person;
const { city: location } = person; // Rename
// Nested destructuring
const user = {
id: 1,
profile: { name: "Carol", address: { city: "LA" } }
};
const { profile: { address: { city } } } = user;
// Default values
const { country = "USA" } = person;
```
```javascript
// Spread operator: unpacking
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3 };
const merged = { ...obj1, ...obj2 }; // { a: 1, b: 2, c: 3 }
// Rest in destructuring
const [head, ...tail] = [1, 2, 3];
const { name, ...rest } = { name: "Dave", age: 30, city: "SF" };
```
```javascript
// Class definition
class Animal {
constructor(name) {
[Link] = name;
}
speak() {
[Link](`${[Link]} makes a sound`);
}
}
// Inheritance
class Dog extends Animal {
constructor(name, breed) {
super(name); // Call parent constructor
[Link] = breed;
}
speak() {
[Link](`${[Link]} barks`);
}
getInfo() {
return `${[Link]} is a ${[Link]}`;
}
}
// Static methods
class Math_Helper {
static add(a, b) {
return a + b;
}
}
[Link](Math_Helper.add(5, 3)); // 8
get area() {
return [Link] * this._radius ** 2;
}
set radius(r) {
if (r <= 0) throw new Error("Invalid radius");
this._radius = r;
}
}
```
### Modules
```javascript
// [Link] - export
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
// [Link] - import
import Calculator, { add, multiply } from './[Link]';
// Import all
import * as math from './[Link]';
```
---
Asynchronous patterns make it possible to run long-running tasks like API requests
without freezing the user interface. This is fundamental to modern JavaScript
development.
### Callbacks
```javascript
// Traditional callback (callback hell)
function fetchData(callback) {
setTimeout(() => {
callback({ id: 1, name: "User" });
}, 1000);
}
fetchData((data) => {
[Link](data);
// Nested callbacks lead to "pyramid of doom"
});
### Promises
```javascript
// Creating a promise
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ id: 1, name: "Alice" });
// or reject(new Error("Failed"));
}, 1000);
});
// Consuming promises
myPromise
.then(data => [Link]("Data:", data))
.catch(error => [Link]("Error:", error))
.finally(() => [Link]("Done"));
// Promise chaining
fetch('[Link]
.then(response => [Link]())
.then(data => {
[Link]("Users:", data);
return data[0].id;
})
.then(userId => fetch(`[Link]
.then(response => [Link]())
.then(posts => [Link]("Posts:", posts))
.catch(error => [Link]("Error:", error));
// Promise utilities
[Link]([promise1, promise2, promise3]) // All must resolve
.then(([r1, r2, r3]) => [Link](r1, r2, r3));
### Async/Await
```javascript
// Async function always returns a Promise
async function getUser(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
if (![Link]) throw new Error("Not found");
---
## 6. Module Systems & Tooling
```javascript
// [Link]
[Link] = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
// [Link]
const math = require('./math');
[Link]([Link](5, 3)); // 8
// Default export
[Link] = class Calculator {
divide(a, b) { return a / b; }
};
// Require
const Calc = require('./calculator');
```
### ES Modules
```javascript
// [Link] - Named exports
export const helper1 = () => {};
export const helper2 = () => {};
// [Link] - Importing
import Utility, { helper1, helper2 } from './[Link]';
import * as utils from './[Link]';
// Dynamic import
const module = await import('./[Link]');
```
```bash
# npm - Node Package Manager
npm init # Initialize project
npm install lodash # Install package
npm install --save-dev jest # Install dev dependency
npm update # Update packages
npm uninstall package # Remove package
# Yarn - Alternative package manager
yarn add lodash
yarn add --dev jest
yarn upgrade
yarn remove package
```javascript
// Webpack configuration ([Link])
[Link] = {
entry: './src/[Link]',
output: {
filename: '[Link]',
path: __dirname + '/dist'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: { loader: 'babel-loader' }
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
}
};
---
## 7. Introduction to Frameworks
---
```javascript
// Functional component
function Welcome(props) {
return <h1>Hello, {[Link]}!</h1>;
}
```javascript
// JSX
const element = <h1 className="greeting">Hello, World!</h1>;
// Equivalent JavaScript
const element = [Link](
'h1',
{ className: 'greeting' },
'Hello, World!'
);
// JSX expressions
const name = "Alice";
const greeting = <h1>Hello, {name}!</h1>;
// Conditional rendering
const message = <div>{isLoggedIn ? "Welcome!" : "Please log in"}</div>;
// Lists
const items = [1, 2, 3].map(num => <li key={num}>{num}</li>);
```
```javascript
function Greeting({ name, age }) {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
// Usage
<Greeting name="Bob" age={30} />
// Default props
function Button({ text = "Click me" }) {
return <button>{text}</button>;
}
// Props spreading
const props = { name: "Carol", age: 25 };
<Greeting {...props} />
```
```javascript
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
// Multiple state variables
function Form() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
return (
<form>
<input value={name} onChange={(e) => setName([Link])} />
<input value={email} onChange={(e) => setEmail([Link])} />
</form>
);
}
```
```javascript
const [value, setValue] = useState(initialValue);
// Example: Toggle
function Toggle() {
const [isOn, setIsOn] = useState(false);
return (
<button onClick={() => setIsOn(!isOn)}>
{isOn ? "ON" : "OFF"}
</button>
);
}
```
```javascript
import { useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
// Cleanup function
function Subscriptions() {
useEffect(() => {
const unsubscribe = subscribeToUpdates((data) => {
[Link]("New data:", data);
});
```javascript
import { createContext, useContext } from 'react';
function App() {
return (
<[Link] value={{ color: 'dark' }}>
<Header />
</[Link]>
);
}
function Header() {
const theme = useContext(ThemeContext);
return <div style={{ background: [Link] }}>Header</div>;
}
```
```javascript
import { useReducer } from 'react';
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {[Link]}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
</div>
);
}
```
```javascript
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
const item = [Link](key);
return item ? [Link](item) : initialValue;
});
// Usage
function App() {
const [name, setName] = useLocalStorage('name', '');
return (
<input
value={name}
onChange={(e) => setName([Link])}
/>
);
}
```
---
```typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [AppComponent, HeaderComponent],
imports: [BrowserModule, HttpClientModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
```typescript
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-button',
template: `<button (click)="onClick()">{{ label }}</button>`,
styles: [`button { padding: 10px; }`]
})
export class ButtonComponent {
@Input() label: string = 'Click';
@Output() clicked = new EventEmitter<void>();
onClick() {
[Link]();
}
}
```
```typescript
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) { }
getUsers(): Observable<any[]> {
return [Link]<any[]>('/api/users');
}
```typescript
@Component({...})
export class UserListComponent implements OnInit {
users: any[] = [];
ngOnInit() {
[Link]().subscribe(
(data) => [Link] = data,
(error) => [Link](error)
);
}
}
```
```typescript
// Component
@Component({
template: `
<input [(ngModel)]="name" />
<p>Hello, {{ name }}!</p>
`
})
export class AppComponent {
name: string = '';
}
```
### Directives
```html
<!-- Structural directives -->
<div *ngIf="isVisible">Visible</div>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
```typescript
import { Observable } from 'rxjs';
import { map, filter } from 'rxjs/operators';
getData()
.pipe(
map(arr => [Link](x => x * 2)),
filter(arr => [Link] > 0)
)
.subscribe(
(result) => [Link](result),
(error) => [Link](error),
() => [Link]('Complete')
);
```
---
```javascript
import { ref, reactive, computed, onMounted } from 'vue';
export default {
setup() {
// Reactive variables
const count = ref(0);
const user = reactive({ name: 'Alice', age: 30 });
// Computed property
const countDoubled = computed(() => [Link] * 2);
// Methods
const increment = () => {
[Link]++;
};
// Lifecycle hooks
onMounted(() => {
[Link]('Component mounted');
});
return {
count,
user,
countDoubled,
increment
};
}
};
```
```vue
<template>
<div>
<!-- Interpolation -->
<h1>{{ message }}</h1>
<script setup>
import { ref, computed } from 'vue';
<style scoped>
.active {
background-color: yellow;
}
.highlight {
font-weight: bold;
}
</style>
```
```vue
<!-- [Link] -->
<template>
<ChildComponent
:message="parentMessage"
@child-event="handleChildEvent"
/>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './[Link]';
<script setup>
defineProps({
message: String
});
defineEmits(['child-event']);
</script>
```
### Watchers
```javascript
import { ref, watch, computed } from 'vue';
export default {
setup() {
const firstName = ref('');
const lastName = ref('');
```svelte
<script>
let count = 0;
function increment() {
count += 1;
}
</script>
<button on:click={increment}>
Clicked {count} times
</button>
<style>
button {
padding: 10px 20px;
font-size: 1.2rem;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
</style>
```
```svelte
<script>
let count = 0;
let doubled = 0;
// Reactive block
$: {
[Link]('Count is:', count);
[Link]('Doubled is:', doubled);
}
</script>
<p>Count: {count}</p>
<p>Doubled: {doubled}</p>
<button on:click={() => count++}>Increment</button>
```
```svelte
<!-- [Link] -->
<script>
export let name = 'World'; // Props
function handleClick() {
dispatch('select', { item: 'clicked' });
}
</script>
<h1>Hello {name}!</h1>
<button on:click={handleClick}>Click me</button>
function handleSelect(e) {
result = [Link];
}
</script>
```svelte
<script>
let name = '';
let items = [];
function addItem() {
items = [...items, name];
name = '';
}
</script>
<ul>
{#each items as item (item)}
<li>{item}</li>
{/each}
</ul>
```
```svelte
<script>
import { fade, slide } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
{#if isVisible}
<div transition:fade={{ duration: 300 }}>
<p>Fade effect</p>
</div>
---
Testing ensures your code works as expected, catches bugs early, and makes
refactoring safer. A comprehensive testing strategy includes unit tests,
integration tests, and end-to-end tests.
```javascript
// [Link]
export function add(a, b) {
return a + b;
}
// [Link]
import { add, multiply } from './math';
```javascript
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';
[Link](button);
expect([Link](/Count: 1/i)).toBeInTheDocument();
});
});
```
### Mocking
```javascript
// API mocking
[Link]('./api');
import { fetchUsers } from './api';
// Function mocking
const mockCallback = [Link]();
mockCallback(1, 2);
expect(mockCallback).toHaveBeenCalledWith(1, 2);
```
```javascript
describe('User flow', () => {
it('allows user to add a todo', () => {
[Link]('[Link]
[Link]('input[placeholder="Add a todo"]')
.type('Buy milk');
[Link]('button[type="submit"]').click();
[Link]('Buy milk').should('[Link]');
});
});
```
---
Building performant applications ensures great user experience, better SEO, and
lower bounce rates.
```javascript
// React
import { lazy, Suspense } from 'react';
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<HeavyComponent />
</Suspense>
);
}
const routes = [
{ path: '/', component: <Suspense fallback={<div>Loading...</div>}><Dashboard
/></Suspense> },
{ path: '/profile', component: <Suspense
fallback={<div>Loading...</div>}><UserProfile /></Suspense> }
];
```
### Memoization
```javascript
// useMemo - Memoize expensive calculations
import { useMemo } from 'react';
return <div>{expensiveValue}</div>;
}
function Parent() {
const handleClick = useCallback(() => {
[Link]('Clicked');
}, []);
```javascript
// Debounce - Wait for user to stop typing
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// Usage
<input onChange={(e) => handleSearch([Link])} />
```html
<!-- Lazy load images -->
<img src="[Link]" loading="lazy" alt="Description" />
```javascript
// Measure performance
const startTime = [Link]();
// Web Vitals
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';
---
```javascript
// [Link] - React framework with SSR
// pages/posts/[id].js
export async function getStaticPaths() {
return {
paths: [{ params: { id: '1' } }],
fallback: true
};
}
```javascript
// Service Worker
[Link]('install', (event) => {
[Link](
[Link]('v1').then((cache) => {
return [Link]([
'/',
'/[Link]',
'/[Link]'
]);
})
);
});
```typescript
// TypeScript - Typed JavaScript
interface User {
id: number;
name: string;
email: string;
}
async function getUser(id: number): Promise<User> {
const response = await fetch(`/api/users/${id}`);
if (![Link]) {
throw new Error(`User not found: ${id}`);
}
return [Link]();
}
### AI Integration
```javascript
// Using AI APIs in JavaScript
import Anthropic from '@anthropic-ai/sdk';
```javascript
// Custom HTML elements
class TodoElement extends HTMLElement {
constructor() {
super();
[Link]({ mode: 'open' });
}
connectedCallback() {
[Link]();
}
render() {
const template = [Link]('template');
[Link] = `
<style>
.todo { padding: 10px; border: 1px solid #ccc; }
</style>
<div class="todo">${[Link]}</div>
`;
[Link]([Link](true));
}
}
[Link]('todo-item', TodoElement);
// Usage
<todo-item>Buy groceries</todo-item>
```
---
```javascript
// Redux - Predictable state container
import { createStore } from 'redux';
// Reducer
function counterReducer(state = 0, action) {
switch([Link]) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
case 'SET':
return [Link];
default:
return state;
}
}
// Store
const store = createStore(counterReducer);
// Subscribe to changes
[Link](() => {
[Link]('State changed:', [Link]());
});
// Dispatch actions
[Link]({ type: 'INCREMENT' });
[Link]({ type: 'SET', payload: 10 });
// React + Redux
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
const count = useSelector(state => state);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>
+
</button>
</div>
);
}
```
```javascript
import { create } from 'zustand';
function Counter() {
const count = useStore((state) => [Link]);
const increment = useStore((state) => [Link]);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
```
```javascript
import { atom, useAtom } from 'jotai';
// Atoms
const countAtom = atom(0);
const userAtom = atom({ name: 'Alice' });
// Derived atoms
const countDoubleAtom = atom(
(get) => get(countAtom) * 2
);
function Component() {
const [count, setCount] = useAtom(countAtom);
const [doubled] = useAtom(countDoubleAtom);
return (
<div>
<p>Count: {count}</p>
<p>Doubled: {doubled}</p>
<button onClick={() => setCount(c => c + 1)}>+</button>
</div>
);
}
```
---
## References
[10] You, E. (2023). [Link]: The Progressive JavaScript Framework. Official Vue
Documentation.
[12] MDN Web Docs. (2025). Web APIs and Standards. [Link]
---
*This comprehensive 14+ page guide covers JavaScript fundamentals through advanced
frameworks and modern development practices. Perfect for students, enthusiasts, and
professionals!*