0% found this document useful (0 votes)
1 views133 pages

Mastering JavaScript and SQL Book

The document is a comprehensive guide on mastering JavaScript and SQL, authored by Christopher Honeywick, aimed at aspiring developers. It covers essential topics such as JavaScript syntax, functions, DOM manipulation, and the use of objects and arrays, providing practical examples throughout. The guide emphasizes hands-on learning to equip readers with modern programming skills for web development and database management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views133 pages

Mastering JavaScript and SQL Book

The document is a comprehensive guide on mastering JavaScript and SQL, authored by Christopher Honeywick, aimed at aspiring developers. It covers essential topics such as JavaScript syntax, functions, DOM manipulation, and the use of objects and arrays, providing practical examples throughout. The guide emphasizes hands-on learning to equip readers with modern programming skills for web development and database management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 133

Mastering JavaScript and SQL

A Complete Guide to Web Programming and Database Management

About the Author

Christopher Honeywick is a seasoned web developer and database expert with years of
experience in building enterprise-level web applications. This book is a product of his
commitment to empowering aspiring developers with hands-on, practical, and modern
programming skills.
Chapter 1: Introduction to JavaScript

JavaScript is a dynamic, lightweight programming language used primarily to add


interactivity to web pages. It works alongside HTML and CSS to create responsive, dynamic
user experiences.

What Can JavaScript Do?

- Change HTML content and attributes.


- React to user actions (clicks, typing, scrolling, etc.).
- Validate form inputs.
- Fetch data from servers (APIs).
- Create browser-based games and applications.

Example: Basic JavaScript in HTML

<!DOCTYPE html>
<html>
<head>
<title>JS Example</title>
</head>
<body>
<h1 id="heading">Hello World</h1>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("heading").innerHTML = "Text
Changed!";
}
</script>
</body>
</html>
Chapter 1: Introduction to JavaScript

JavaScript is a dynamic, lightweight programming language used primarily to add


interactivity to web pages. It works alongside HTML and CSS to create responsive, dynamic
user experiences.

What Can JavaScript Do?

- Change HTML content and attributes.


- React to user actions (clicks, typing, scrolling, etc.).
- Validate form inputs.
- Fetch data from servers (APIs).
- Create browser-based games and applications.

Example: Basic JavaScript in HTML

<!DOCTYPE html>
<html>
<head>
<title>JS Example</title>
</head>
<body>
<h1 id="heading">Hello World</h1>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("heading").innerHTML = "Text
Changed!";
}
</script>
</body>
</html>
Chapter 2: JavaScript Syntax, Variables, and Data Types

Understanding the basic syntax and structure of JavaScript is crucial. In this chapter, you'll
learn how to declare variables, use different data types, and write syntactically correct
JavaScript code.

Variables

JavaScript uses three main keywords for variable declaration: var, let, and const.

- `var` was traditionally used, but it's now recommended to use `let` or `const`.
- `let` allows variable reassignment.
- `const` defines a constant, which cannot be reassigned.

Example:

let name = "John";


const age = 30;
var city = "New York";

Data Types

JavaScript supports several data types including:

- String: "Hello World"


- Number: 42
- Boolean: true or false
- Null: intentional absence of any value
- Undefined: variable declared but not yet assigned
- Object: { name: "Alice", age: 25 }
- Array: [1, 2, 3, 4]

Example:

let message = "Welcome";


let score = 100;
let isLoggedIn = true;
let data = null;
let user;
let profile = { name: "Alice", age: 25 };
let items = [10, 20, 30];
Chapter 1: Introduction to JavaScript

JavaScript is a dynamic, lightweight programming language used primarily to add


interactivity to web pages. It works alongside HTML and CSS to create responsive, dynamic
user experiences.

What Can JavaScript Do?

- Change HTML content and attributes.


- React to user actions (clicks, typing, scrolling, etc.).
- Validate form inputs.
- Fetch data from servers (APIs).
- Create browser-based games and applications.

Example: Basic JavaScript in HTML

<!DOCTYPE html>
<html>
<head>
<title>JS Example</title>
</head>
<body>
<h1 id="heading">Hello World</h1>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("heading").innerHTML = "Text
Changed!";
}
</script>
</body>
</html>
Chapter 2: JavaScript Syntax, Variables, and Data Types

Understanding the basic syntax and structure of JavaScript is crucial. In this chapter, you'll
learn how to declare variables, use different data types, and write syntactically correct
JavaScript code.

Variables

JavaScript uses three main keywords for variable declaration: var, let, and const.

- `var` was traditionally used, but it's now recommended to use `let` or `const`.
- `let` allows variable reassignment.
- `const` defines a constant, which cannot be reassigned.

Example:

let name = "John";


const age = 30;
var city = "New York";

Data Types

JavaScript supports several data types including:

- String: "Hello World"


- Number: 42
- Boolean: true or false
- Null: intentional absence of any value
- Undefined: variable declared but not yet assigned
- Object: { name: "Alice", age: 25 }
- Array: [1, 2, 3, 4]

Example:

let message = "Welcome";


let score = 100;
let isLoggedIn = true;
let data = null;
let user;
let profile = { name: "Alice", age: 25 };
let items = [10, 20, 30];
Chapter 3: Functions and Scope

Functions are reusable blocks of code that perform a specific task. Scope refers to the
context in which variables are accessible. Understanding how functions and scope work is
essential to writing clean and effective JavaScript.

Function Declaration and Invocation

JavaScript supports different ways to define functions:

1. **Function Declaration**

function greet(name) {
return "Hello, " + name + "!";
}

greet("Alice");

2. **Function Expression**

const greet = function(name) {


return "Hi, " + name;
};

3. **Arrow Function (ES6+)**

const greet = (name) => "Hey, " + name + "!";

Scope in JavaScript

Scope determines the visibility of variables. There are two types of scope:

- **Global Scope**: Accessible anywhere in the script.


- **Local Scope**: Variables declared inside a function are local.
Example:

let globalVar = "I'm global";

function showScope() {
let localVar = "I'm local";
console.log(globalVar);
console.log(localVar);
}

showScope();
console.log(localVar); // Error: localVar is not defined
Chapter 1: Introduction to JavaScript

JavaScript is a dynamic, lightweight programming language used primarily to add


interactivity to web pages. It works alongside HTML and CSS to create responsive, dynamic
user experiences.

What Can JavaScript Do?

- Change HTML content and attributes.


- React to user actions (clicks, typing, scrolling, etc.).
- Validate form inputs.
- Fetch data from servers (APIs).
- Create browser-based games and applications.

Example: Basic JavaScript in HTML

<!DOCTYPE html>
<html>
<head>
<title>JS Example</title>
</head>
<body>
<h1 id="heading">Hello World</h1>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("heading").innerHTML = "Text
Changed!";
}
</script>
</body>
</html>
Chapter 2: JavaScript Syntax, Variables, and Data Types

Understanding the basic syntax and structure of JavaScript is crucial. In this chapter, you'll
learn how to declare variables, use different data types, and write syntactically correct
JavaScript code.

Variables

JavaScript uses three main keywords for variable declaration: var, let, and const.

- `var` was traditionally used, but it's now recommended to use `let` or `const`.
- `let` allows variable reassignment.
- `const` defines a constant, which cannot be reassigned.

Example:

let name = "John";


const age = 30;
var city = "New York";

Data Types

JavaScript supports several data types including:

- String: "Hello World"


- Number: 42
- Boolean: true or false
- Null: intentional absence of any value
- Undefined: variable declared but not yet assigned
- Object: { name: "Alice", age: 25 }
- Array: [1, 2, 3, 4]

Example:

let message = "Welcome";


let score = 100;
let isLoggedIn = true;
let data = null;
let user;
let profile = { name: "Alice", age: 25 };
let items = [10, 20, 30];
Chapter 3: Functions and Scope

Functions are reusable blocks of code that perform a specific task. Scope refers to the
context in which variables are accessible. Understanding how functions and scope work is
essential to writing clean and effective JavaScript.

Function Declaration and Invocation

JavaScript supports different ways to define functions:

1. **Function Declaration**

function greet(name) {
return "Hello, " + name + "!";
}

greet("Alice");

2. **Function Expression**

const greet = function(name) {


return "Hi, " + name;
};

3. **Arrow Function (ES6+)**

const greet = (name) => "Hey, " + name + "!";

Scope in JavaScript

Scope determines the visibility of variables. There are two types of scope:

- **Global Scope**: Accessible anywhere in the script.


- **Local Scope**: Variables declared inside a function are local.
Example:

let globalVar = "I'm global";

function showScope() {
let localVar = "I'm local";
console.log(globalVar);
console.log(localVar);
}

showScope();
console.log(localVar); // Error: localVar is not defined
Chapter 4: DOM Manipulation and Events

The Document Object Model (DOM) allows JavaScript to access and modify HTML content
dynamically. You can use JavaScript to change the structure, style, and content of a web
page in response to user actions.

Accessing DOM Elements

You can access elements using different methods:

- `getElementById()`
- `getElementsByClassName()`
- `querySelector()`
- `querySelectorAll()`

Example:

const heading = document.getElementById("main-heading");


const items = document.querySelectorAll(".list-item");

Changing Content and Style

You can modify HTML content and style dynamically.

Example:

heading.textContent = "New Heading";


heading.style.color = "blue";

Handling Events

JavaScript can respond to user events like clicks, typing, and form submissions.
Example:

const button = document.querySelector("button");


button.addEventListener("click", function() {
alert("Button clicked!");
});
Chapter 1: Introduction to JavaScript

JavaScript is a dynamic, lightweight programming language used primarily to add


interactivity to web pages. It works alongside HTML and CSS to create responsive, dynamic
user experiences.

What Can JavaScript Do?

- Change HTML content and attributes.


- React to user actions (clicks, typing, scrolling, etc.).
- Validate form inputs.
- Fetch data from servers (APIs).
- Create browser-based games and applications.

Example: Basic JavaScript in HTML

<!DOCTYPE html>
<html>
<head>
<title>JS Example</title>
</head>
<body>
<h1 id="heading">Hello World</h1>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("heading").innerHTML = "Text
Changed!";
}
</script>
</body>
</html>
Chapter 2: JavaScript Syntax, Variables, and Data Types

Understanding the basic syntax and structure of JavaScript is crucial. In this chapter, you'll
learn how to declare variables, use different data types, and write syntactically correct
JavaScript code.

Variables

JavaScript uses three main keywords for variable declaration: var, let, and const.

- `var` was traditionally used, but it's now recommended to use `let` or `const`.
- `let` allows variable reassignment.
- `const` defines a constant, which cannot be reassigned.

Example:

let name = "John";


const age = 30;
var city = "New York";

Data Types

JavaScript supports several data types including:

- String: "Hello World"


- Number: 42
- Boolean: true or false
- Null: intentional absence of any value
- Undefined: variable declared but not yet assigned
- Object: { name: "Alice", age: 25 }
- Array: [1, 2, 3, 4]

Example:

let message = "Welcome";


let score = 100;
let isLoggedIn = true;
let data = null;
let user;
let profile = { name: "Alice", age: 25 };
let items = [10, 20, 30];
Chapter 3: Functions and Scope

Functions are reusable blocks of code that perform a specific task. Scope refers to the
context in which variables are accessible. Understanding how functions and scope work is
essential to writing clean and effective JavaScript.

Function Declaration and Invocation

JavaScript supports different ways to define functions:

1. **Function Declaration**

function greet(name) {
return "Hello, " + name + "!";
}

greet("Alice");

2. **Function Expression**

const greet = function(name) {


return "Hi, " + name;
};

3. **Arrow Function (ES6+)**

const greet = (name) => "Hey, " + name + "!";

Scope in JavaScript

Scope determines the visibility of variables. There are two types of scope:

- **Global Scope**: Accessible anywhere in the script.


- **Local Scope**: Variables declared inside a function are local.
Example:

let globalVar = "I'm global";

function showScope() {
let localVar = "I'm local";
console.log(globalVar);
console.log(localVar);
}

showScope();
console.log(localVar); // Error: localVar is not defined
Chapter 4: DOM Manipulation and Events

The Document Object Model (DOM) allows JavaScript to access and modify HTML content
dynamically. You can use JavaScript to change the structure, style, and content of a web
page in response to user actions.

Accessing DOM Elements

You can access elements using different methods:

- `getElementById()`
- `getElementsByClassName()`
- `querySelector()`
- `querySelectorAll()`

Example:

const heading = document.getElementById("main-heading");


const items = document.querySelectorAll(".list-item");

Changing Content and Style

You can modify HTML content and style dynamically.

Example:

heading.textContent = "New Heading";


heading.style.color = "blue";

Handling Events

JavaScript can respond to user events like clicks, typing, and form submissions.
Example:

const button = document.querySelector("button");


button.addEventListener("click", function() {
alert("Button clicked!");
});
Chapter 5: Objects and Arrays

Objects and arrays are fundamental data structures in JavaScript. They allow you to group
related data and manipulate collections efficiently.

Objects

Objects store data in key-value pairs. Each key is a string, and the value can be any type.

Example:

const person = {
name: "Alice",
age: 30,
isStudent: false
};

console.log(person.name); // Alice

Modifying Objects

You can update, add, or delete properties in an object.

Example:

person.age = 31;
person.city = "New York";
delete person.isStudent;

Arrays

Arrays are ordered collections of items. You can access elements using index numbers.
Example:

const fruits = ["Apple", "Banana", "Cherry"];


console.log(fruits[1]); // Banana

Array Methods

JavaScript provides many methods for arrays:

- `push()` – adds an item to the end


- `pop()` – removes the last item
- `shift()` – removes the first item
- `unshift()` – adds an item to the beginning
- `forEach()` – executes a function for each item

Example:

fruits.push("Orange");
fruits.forEach(function(fruit) {
console.log(fruit);
});
Chapter 1: Introduction to JavaScript

JavaScript is a dynamic, lightweight programming language used primarily to add


interactivity to web pages. It works alongside HTML and CSS to create responsive, dynamic
user experiences.

What Can JavaScript Do?

- Change HTML content and attributes.


- React to user actions (clicks, typing, scrolling, etc.).
- Validate form inputs.
- Fetch data from servers (APIs).
- Create browser-based games and applications.

Example: Basic JavaScript in HTML

<!DOCTYPE html>
<html>
<head>
<title>JS Example</title>
</head>
<body>
<h1 id="heading">Hello World</h1>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("heading").innerHTML = "Text
Changed!";
}
</script>
</body>
</html>
Chapter 2: JavaScript Syntax, Variables, and Data Types

Understanding the basic syntax and structure of JavaScript is crucial. In this chapter, you'll
learn how to declare variables, use different data types, and write syntactically correct
JavaScript code.

Variables

JavaScript uses three main keywords for variable declaration: var, let, and const.

- `var` was traditionally used, but it's now recommended to use `let` or `const`.
- `let` allows variable reassignment.
- `const` defines a constant, which cannot be reassigned.

Example:

let name = "John";


const age = 30;
var city = "New York";

Data Types

JavaScript supports several data types including:

- String: "Hello World"


- Number: 42
- Boolean: true or false
- Null: intentional absence of any value
- Undefined: variable declared but not yet assigned
- Object: { name: "Alice", age: 25 }
- Array: [1, 2, 3, 4]

Example:

let message = "Welcome";


let score = 100;
let isLoggedIn = true;
let data = null;
let user;
let profile = { name: "Alice", age: 25 };
let items = [10, 20, 30];
Chapter 3: Functions and Scope

Functions are reusable blocks of code that perform a specific task. Scope refers to the
context in which variables are accessible. Understanding how functions and scope work is
essential to writing clean and effective JavaScript.

Function Declaration and Invocation

JavaScript supports different ways to define functions:

1. **Function Declaration**

function greet(name) {
return "Hello, " + name + "!";
}

greet("Alice");

2. **Function Expression**

const greet = function(name) {


return "Hi, " + name;
};

3. **Arrow Function (ES6+)**

const greet = (name) => "Hey, " + name + "!";

Scope in JavaScript

Scope determines the visibility of variables. There are two types of scope:

- **Global Scope**: Accessible anywhere in the script.


- **Local Scope**: Variables declared inside a function are local.
Example:

let globalVar = "I'm global";

function showScope() {
let localVar = "I'm local";
console.log(globalVar);
console.log(localVar);
}

showScope();
console.log(localVar); // Error: localVar is not defined
Chapter 4: DOM Manipulation and Events

The Document Object Model (DOM) allows JavaScript to access and modify HTML content
dynamically. You can use JavaScript to change the structure, style, and content of a web
page in response to user actions.

Accessing DOM Elements

You can access elements using different methods:

- `getElementById()`
- `getElementsByClassName()`
- `querySelector()`
- `querySelectorAll()`

Example:

const heading = document.getElementById("main-heading");


const items = document.querySelectorAll(".list-item");

Changing Content and Style

You can modify HTML content and style dynamically.

Example:

heading.textContent = "New Heading";


heading.style.color = "blue";

Handling Events

JavaScript can respond to user events like clicks, typing, and form submissions.
Example:

const button = document.querySelector("button");


button.addEventListener("click", function() {
alert("Button clicked!");
});
Chapter 5: Objects and Arrays

Objects and arrays are fundamental data structures in JavaScript. They allow you to group
related data and manipulate collections efficiently.

Objects

Objects store data in key-value pairs. Each key is a string, and the value can be any type.

Example:

const person = {
name: "Alice",
age: 30,
isStudent: false
};

console.log(person.name); // Alice

Modifying Objects

You can update, add, or delete properties in an object.

Example:

person.age = 31;
person.city = "New York";
delete person.isStudent;

Arrays

Arrays are ordered collections of items. You can access elements using index numbers.
Example:

const fruits = ["Apple", "Banana", "Cherry"];


console.log(fruits[1]); // Banana

Array Methods

JavaScript provides many methods for arrays:

- `push()` – adds an item to the end


- `pop()` – removes the last item
- `shift()` – removes the first item
- `unshift()` – adds an item to the beginning
- `forEach()` – executes a function for each item

Example:

fruits.push("Orange");
fruits.forEach(function(fruit) {
console.log(fruit);
});
Chapter 6: Conditional Statements and Loops

Conditional statements and loops allow you to control the flow of your code. Conditions
decide what code runs, while loops allow you to repeat blocks of code.

Conditional Statements

JavaScript supports several conditional structures:

- `if`
- `else if`
- `else`
- `switch`

Example (if-else):

let age = 20;


if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

Example (switch):

let color = "blue";


switch (color) {
case "red":
console.log("Color is red");
break;
case "blue":
console.log("Color is blue");
break;
default:
console.log("Color not recognized");
}
Loops

Loops let you run code multiple times:

- `for` loop
- `while` loop
- `do...while` loop
- `for...of` and `for...in` loops

Example (for loop):

for (let i = 0; i < 5; i++) {


console.log("Number: " + i);
}

Example (while loop):

let i = 0;
while (i < 3) {
console.log("i is " + i);
i++;
}

Example (for...of loop):

const fruits = ["apple", "banana", "cherry"];


for (let fruit of fruits) {
console.log(fruit);
}
Chapter 1: Introduction to JavaScript

JavaScript is a dynamic, lightweight programming language used primarily to add


interactivity to web pages. It works alongside HTML and CSS to create responsive, dynamic
user experiences.

What Can JavaScript Do?

- Change HTML content and attributes.


- React to user actions (clicks, typing, scrolling, etc.).
- Validate form inputs.
- Fetch data from servers (APIs).
- Create browser-based games and applications.

Example: Basic JavaScript in HTML

<!DOCTYPE html>
<html>
<head>
<title>JS Example</title>
</head>
<body>
<h1 id="heading">Hello World</h1>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("heading").innerHTML = "Text
Changed!";
}
</script>
</body>
</html>
Chapter 2: JavaScript Syntax, Variables, and Data Types

Understanding the basic syntax and structure of JavaScript is crucial. In this chapter, you'll
learn how to declare variables, use different data types, and write syntactically correct
JavaScript code.

Variables

JavaScript uses three main keywords for variable declaration: var, let, and const.

- `var` was traditionally used, but it's now recommended to use `let` or `const`.
- `let` allows variable reassignment.
- `const` defines a constant, which cannot be reassigned.

Example:

let name = "John";


const age = 30;
var city = "New York";

Data Types

JavaScript supports several data types including:

- String: "Hello World"


- Number: 42
- Boolean: true or false
- Null: intentional absence of any value
- Undefined: variable declared but not yet assigned
- Object: { name: "Alice", age: 25 }
- Array: [1, 2, 3, 4]

Example:

let message = "Welcome";


let score = 100;
let isLoggedIn = true;
let data = null;
let user;
let profile = { name: "Alice", age: 25 };
let items = [10, 20, 30];
Chapter 3: Functions and Scope

Functions are reusable blocks of code that perform a specific task. Scope refers to the
context in which variables are accessible. Understanding how functions and scope work is
essential to writing clean and effective JavaScript.

Function Declaration and Invocation

JavaScript supports different ways to define functions:

1. **Function Declaration**

function greet(name) {
return "Hello, " + name + "!";
}

greet("Alice");

2. **Function Expression**

const greet = function(name) {


return "Hi, " + name;
};

3. **Arrow Function (ES6+)**

const greet = (name) => "Hey, " + name + "!";

Scope in JavaScript

Scope determines the visibility of variables. There are two types of scope:

- **Global Scope**: Accessible anywhere in the script.


- **Local Scope**: Variables declared inside a function are local.
Example:

let globalVar = "I'm global";

function showScope() {
let localVar = "I'm local";
console.log(globalVar);
console.log(localVar);
}

showScope();
console.log(localVar); // Error: localVar is not defined
Chapter 4: DOM Manipulation and Events

The Document Object Model (DOM) allows JavaScript to access and modify HTML content
dynamically. You can use JavaScript to change the structure, style, and content of a web
page in response to user actions.

Accessing DOM Elements

You can access elements using different methods:

- `getElementById()`
- `getElementsByClassName()`
- `querySelector()`
- `querySelectorAll()`

Example:

const heading = document.getElementById("main-heading");


const items = document.querySelectorAll(".list-item");

Changing Content and Style

You can modify HTML content and style dynamically.

Example:

heading.textContent = "New Heading";


heading.style.color = "blue";

Handling Events

JavaScript can respond to user events like clicks, typing, and form submissions.
Example:

const button = document.querySelector("button");


button.addEventListener("click", function() {
alert("Button clicked!");
});
Chapter 5: Objects and Arrays

Objects and arrays are fundamental data structures in JavaScript. They allow you to group
related data and manipulate collections efficiently.

Objects

Objects store data in key-value pairs. Each key is a string, and the value can be any type.

Example:

const person = {
name: "Alice",
age: 30,
isStudent: false
};

console.log(person.name); // Alice

Modifying Objects

You can update, add, or delete properties in an object.

Example:

person.age = 31;
person.city = "New York";
delete person.isStudent;

Arrays

Arrays are ordered collections of items. You can access elements using index numbers.
Example:

const fruits = ["Apple", "Banana", "Cherry"];


console.log(fruits[1]); // Banana

Array Methods

JavaScript provides many methods for arrays:

- `push()` – adds an item to the end


- `pop()` – removes the last item
- `shift()` – removes the first item
- `unshift()` – adds an item to the beginning
- `forEach()` – executes a function for each item

Example:

fruits.push("Orange");
fruits.forEach(function(fruit) {
console.log(fruit);
});
Chapter 6: Conditional Statements and Loops

Conditional statements and loops allow you to control the flow of your code. Conditions
decide what code runs, while loops allow you to repeat blocks of code.

Conditional Statements

JavaScript supports several conditional structures:

- `if`
- `else if`
- `else`
- `switch`

Example (if-else):

let age = 20;


if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

Example (switch):

let color = "blue";


switch (color) {
case "red":
console.log("Color is red");
break;
case "blue":
console.log("Color is blue");
break;
default:
console.log("Color not recognized");
}
Loops

Loops let you run code multiple times:

- `for` loop
- `while` loop
- `do...while` loop
- `for...of` and `for...in` loops

Example (for loop):

for (let i = 0; i < 5; i++) {


console.log("Number: " + i);
}

Example (while loop):

let i = 0;
while (i < 3) {
console.log("i is " + i);
i++;
}

Example (for...of loop):

const fruits = ["apple", "banana", "cherry"];


for (let fruit of fruits) {
console.log(fruit);
}
Chapter 7: JavaScript Project – To-Do List App

This project demonstrates how to build a fully functional To-Do List using HTML, CSS, and
JavaScript. It covers essential web development skills including DOM manipulation, event
handling, and localStorage.

Project Structure

The project consists of three main files:


- `index.html`
- `style.css`
- `script.js`

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>To-Do List App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>To-Do List</h1>
<input type="text" id="taskInput" placeholder="Add a new task">
<button id="addTask">Add Task</button>
<ul id="taskList"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
style.css

body {
font-family: Arial, sans-serif;
background: #f4f4f4;
display: flex;
justify-content: center;
padding: 50px;
}

.container {
background: #fff;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
width: 300px;
}

input {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}

button {
width: 100%;
padding: 10px;
background: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}

ul {
list-style: none;
padding: 0;
}

li {
padding: 10px;
border-bottom: 1px solid #ddd;
display: flex;
justify-content: space-between;
align-items: center;
}

li.completed {
text-decoration: line-through;
color: #888;
}

script.js

document.addEventListener("DOMContentLoaded", () => {
const taskInput = document.getElementById("taskInput");
const addTask = document.getElementById("addTask");
const taskList = document.getElementById("taskList");

// Load tasks from localStorage


let tasks = JSON.parse(localStorage.getItem("tasks")) || [];
tasks.forEach(task => renderTask(task.text, task.completed));

addTask.addEventListener("click", () => {
const text = taskInput.value.trim();
if (text !== "") {
renderTask(text);
tasks.push({ text, completed: false });
localStorage.setItem("tasks", JSON.stringify(tasks));
taskInput.value = "";
}
});

function renderTask(text, completed = false) {


const li = document.createElement("li");
li.textContent = text;
if (completed) li.classList.add("completed");

li.addEventListener("click", () => {
li.classList.toggle("completed");
tasks = tasks.map(t => t.text === text ? { ...t, completed: !
t.completed } : t);
localStorage.setItem("tasks", JSON.stringify(tasks));
});

const removeBtn = document.createElement("button");


removeBtn.textContent = "X";
removeBtn.style.marginLeft = "10px";
removeBtn.addEventListener("click", () => {
li.remove();
tasks = tasks.filter(t => t.text !== text);
localStorage.setItem("tasks", JSON.stringify(tasks));
});

li.appendChild(removeBtn);
taskList.appendChild(li);
}
});
Chapter 1: Introduction to JavaScript

JavaScript is a dynamic, lightweight programming language used primarily to add


interactivity to web pages. It works alongside HTML and CSS to create responsive, dynamic
user experiences.

What Can JavaScript Do?

- Change HTML content and attributes.


- React to user actions (clicks, typing, scrolling, etc.).
- Validate form inputs.
- Fetch data from servers (APIs).
- Create browser-based games and applications.

Example: Basic JavaScript in HTML

<!DOCTYPE html>
<html>
<head>
<title>JS Example</title>
</head>
<body>
<h1 id="heading">Hello World</h1>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("heading").innerHTML = "Text
Changed!";
}
</script>
</body>
</html>
Chapter 2: JavaScript Syntax, Variables, and Data Types

Understanding the basic syntax and structure of JavaScript is crucial. In this chapter, you'll
learn how to declare variables, use different data types, and write syntactically correct
JavaScript code.

Variables

JavaScript uses three main keywords for variable declaration: var, let, and const.

- `var` was traditionally used, but it's now recommended to use `let` or `const`.
- `let` allows variable reassignment.
- `const` defines a constant, which cannot be reassigned.

Example:

let name = "John";


const age = 30;
var city = "New York";

Data Types

JavaScript supports several data types including:

- String: "Hello World"


- Number: 42
- Boolean: true or false
- Null: intentional absence of any value
- Undefined: variable declared but not yet assigned
- Object: { name: "Alice", age: 25 }
- Array: [1, 2, 3, 4]

Example:

let message = "Welcome";


let score = 100;
let isLoggedIn = true;
let data = null;
let user;
let profile = { name: "Alice", age: 25 };
let items = [10, 20, 30];
Chapter 3: Functions and Scope

Functions are reusable blocks of code that perform a specific task. Scope refers to the
context in which variables are accessible. Understanding how functions and scope work is
essential to writing clean and effective JavaScript.

Function Declaration and Invocation

JavaScript supports different ways to define functions:

1. **Function Declaration**

function greet(name) {
return "Hello, " + name + "!";
}

greet("Alice");

2. **Function Expression**

const greet = function(name) {


return "Hi, " + name;
};

3. **Arrow Function (ES6+)**

const greet = (name) => "Hey, " + name + "!";

Scope in JavaScript

Scope determines the visibility of variables. There are two types of scope:

- **Global Scope**: Accessible anywhere in the script.


- **Local Scope**: Variables declared inside a function are local.
Example:

let globalVar = "I'm global";

function showScope() {
let localVar = "I'm local";
console.log(globalVar);
console.log(localVar);
}

showScope();
console.log(localVar); // Error: localVar is not defined
Chapter 4: DOM Manipulation and Events

The Document Object Model (DOM) allows JavaScript to access and modify HTML content
dynamically. You can use JavaScript to change the structure, style, and content of a web
page in response to user actions.

Accessing DOM Elements

You can access elements using different methods:

- `getElementById()`
- `getElementsByClassName()`
- `querySelector()`
- `querySelectorAll()`

Example:

const heading = document.getElementById("main-heading");


const items = document.querySelectorAll(".list-item");

Changing Content and Style

You can modify HTML content and style dynamically.

Example:

heading.textContent = "New Heading";


heading.style.color = "blue";

Handling Events

JavaScript can respond to user events like clicks, typing, and form submissions.
Example:

const button = document.querySelector("button");


button.addEventListener("click", function() {
alert("Button clicked!");
});
Chapter 5: Objects and Arrays

Objects and arrays are fundamental data structures in JavaScript. They allow you to group
related data and manipulate collections efficiently.

Objects

Objects store data in key-value pairs. Each key is a string, and the value can be any type.

Example:

const person = {
name: "Alice",
age: 30,
isStudent: false
};

console.log(person.name); // Alice

Modifying Objects

You can update, add, or delete properties in an object.

Example:

person.age = 31;
person.city = "New York";
delete person.isStudent;

Arrays

Arrays are ordered collections of items. You can access elements using index numbers.
Example:

const fruits = ["Apple", "Banana", "Cherry"];


console.log(fruits[1]); // Banana

Array Methods

JavaScript provides many methods for arrays:

- `push()` – adds an item to the end


- `pop()` – removes the last item
- `shift()` – removes the first item
- `unshift()` – adds an item to the beginning
- `forEach()` – executes a function for each item

Example:

fruits.push("Orange");
fruits.forEach(function(fruit) {
console.log(fruit);
});
Chapter 6: Conditional Statements and Loops

Conditional statements and loops allow you to control the flow of your code. Conditions
decide what code runs, while loops allow you to repeat blocks of code.

Conditional Statements

JavaScript supports several conditional structures:

- `if`
- `else if`
- `else`
- `switch`

Example (if-else):

let age = 20;


if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

Example (switch):

let color = "blue";


switch (color) {
case "red":
console.log("Color is red");
break;
case "blue":
console.log("Color is blue");
break;
default:
console.log("Color not recognized");
}
Loops

Loops let you run code multiple times:

- `for` loop
- `while` loop
- `do...while` loop
- `for...of` and `for...in` loops

Example (for loop):

for (let i = 0; i < 5; i++) {


console.log("Number: " + i);
}

Example (while loop):

let i = 0;
while (i < 3) {
console.log("i is " + i);
i++;
}

Example (for...of loop):

const fruits = ["apple", "banana", "cherry"];


for (let fruit of fruits) {
console.log(fruit);
}
Chapter 7: JavaScript Project – To-Do List App

This project demonstrates how to build a fully functional To-Do List using HTML, CSS, and
JavaScript. It covers essential web development skills including DOM manipulation, event
handling, and localStorage.

Project Structure

The project consists of three main files:


- `index.html`
- `style.css`
- `script.js`

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>To-Do List App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>To-Do List</h1>
<input type="text" id="taskInput" placeholder="Add a new task">
<button id="addTask">Add Task</button>
<ul id="taskList"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
style.css

body {
font-family: Arial, sans-serif;
background: #f4f4f4;
display: flex;
justify-content: center;
padding: 50px;
}

.container {
background: #fff;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
width: 300px;
}

input {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}

button {
width: 100%;
padding: 10px;
background: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}

ul {
list-style: none;
padding: 0;
}

li {
padding: 10px;
border-bottom: 1px solid #ddd;
display: flex;
justify-content: space-between;
align-items: center;
}

li.completed {
text-decoration: line-through;
color: #888;
}

script.js

document.addEventListener("DOMContentLoaded", () => {
const taskInput = document.getElementById("taskInput");
const addTask = document.getElementById("addTask");
const taskList = document.getElementById("taskList");

// Load tasks from localStorage


let tasks = JSON.parse(localStorage.getItem("tasks")) || [];
tasks.forEach(task => renderTask(task.text, task.completed));

addTask.addEventListener("click", () => {
const text = taskInput.value.trim();
if (text !== "") {
renderTask(text);
tasks.push({ text, completed: false });
localStorage.setItem("tasks", JSON.stringify(tasks));
taskInput.value = "";
}
});

function renderTask(text, completed = false) {


const li = document.createElement("li");
li.textContent = text;
if (completed) li.classList.add("completed");

li.addEventListener("click", () => {
li.classList.toggle("completed");
tasks = tasks.map(t => t.text === text ? { ...t, completed: !
t.completed } : t);
localStorage.setItem("tasks", JSON.stringify(tasks));
});

const removeBtn = document.createElement("button");


removeBtn.textContent = "X";
removeBtn.style.marginLeft = "10px";
removeBtn.addEventListener("click", () => {
li.remove();
tasks = tasks.filter(t => t.text !== text);
localStorage.setItem("tasks", JSON.stringify(tasks));
});

li.appendChild(removeBtn);
taskList.appendChild(li);
}
});
Chapter 8: Introduction to SQL

SQL (Structured Query Language) is used to manage and manipulate relational databases. It
allows you to query, insert, update, and delete data using simple and powerful syntax.

Basic SQL Syntax

A basic SQL statement includes a command followed by the target table and conditions.

Example:

SELECT * FROM users;

Common SQL Commands

- `SELECT`: Retrieves data from one or more tables.


- `INSERT`: Adds new data to a table.
- `UPDATE`: Modifies existing data.
- `DELETE`: Removes data from a table.
- `CREATE`: Creates new tables or databases.
- `DROP`: Deletes tables or databases.

Sample Table and Data

Example: Creating a `users` table and inserting data.

CREATE TABLE users (


id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
);

INSERT INTO users (id, name, email)


VALUES (1, 'Alice', '[email protected]');
Chapter 1: Introduction to JavaScript

JavaScript is a dynamic, lightweight programming language used primarily to add


interactivity to web pages. It works alongside HTML and CSS to create responsive, dynamic
user experiences.

What Can JavaScript Do?

- Change HTML content and attributes.


- React to user actions (clicks, typing, scrolling, etc.).
- Validate form inputs.
- Fetch data from servers (APIs).
- Create browser-based games and applications.

Example: Basic JavaScript in HTML

<!DOCTYPE html>
<html>
<head>
<title>JS Example</title>
</head>
<body>
<h1 id="heading">Hello World</h1>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("heading").innerHTML = "Text
Changed!";
}
</script>
</body>
</html>
Chapter 2: JavaScript Syntax, Variables, and Data Types

Understanding the basic syntax and structure of JavaScript is crucial. In this chapter, you'll
learn how to declare variables, use different data types, and write syntactically correct
JavaScript code.

Variables

JavaScript uses three main keywords for variable declaration: var, let, and const.

- `var` was traditionally used, but it's now recommended to use `let` or `const`.
- `let` allows variable reassignment.
- `const` defines a constant, which cannot be reassigned.

Example:

let name = "John";


const age = 30;
var city = "New York";

Data Types

JavaScript supports several data types including:

- String: "Hello World"


- Number: 42
- Boolean: true or false
- Null: intentional absence of any value
- Undefined: variable declared but not yet assigned
- Object: { name: "Alice", age: 25 }
- Array: [1, 2, 3, 4]

Example:

let message = "Welcome";


let score = 100;
let isLoggedIn = true;
let data = null;
let user;
let profile = { name: "Alice", age: 25 };
let items = [10, 20, 30];
Chapter 3: Functions and Scope

Functions are reusable blocks of code that perform a specific task. Scope refers to the
context in which variables are accessible. Understanding how functions and scope work is
essential to writing clean and effective JavaScript.

Function Declaration and Invocation

JavaScript supports different ways to define functions:

1. **Function Declaration**

function greet(name) {
return "Hello, " + name + "!";
}

greet("Alice");

2. **Function Expression**

const greet = function(name) {


return "Hi, " + name;
};

3. **Arrow Function (ES6+)**

const greet = (name) => "Hey, " + name + "!";

Scope in JavaScript

Scope determines the visibility of variables. There are two types of scope:

- **Global Scope**: Accessible anywhere in the script.


- **Local Scope**: Variables declared inside a function are local.
Example:

let globalVar = "I'm global";

function showScope() {
let localVar = "I'm local";
console.log(globalVar);
console.log(localVar);
}

showScope();
console.log(localVar); // Error: localVar is not defined
Chapter 4: DOM Manipulation and Events

The Document Object Model (DOM) allows JavaScript to access and modify HTML content
dynamically. You can use JavaScript to change the structure, style, and content of a web
page in response to user actions.

Accessing DOM Elements

You can access elements using different methods:

- `getElementById()`
- `getElementsByClassName()`
- `querySelector()`
- `querySelectorAll()`

Example:

const heading = document.getElementById("main-heading");


const items = document.querySelectorAll(".list-item");

Changing Content and Style

You can modify HTML content and style dynamically.

Example:

heading.textContent = "New Heading";


heading.style.color = "blue";

Handling Events

JavaScript can respond to user events like clicks, typing, and form submissions.
Example:

const button = document.querySelector("button");


button.addEventListener("click", function() {
alert("Button clicked!");
});
Chapter 5: Objects and Arrays

Objects and arrays are fundamental data structures in JavaScript. They allow you to group
related data and manipulate collections efficiently.

Objects

Objects store data in key-value pairs. Each key is a string, and the value can be any type.

Example:

const person = {
name: "Alice",
age: 30,
isStudent: false
};

console.log(person.name); // Alice

Modifying Objects

You can update, add, or delete properties in an object.

Example:

person.age = 31;
person.city = "New York";
delete person.isStudent;

Arrays

Arrays are ordered collections of items. You can access elements using index numbers.
Example:

const fruits = ["Apple", "Banana", "Cherry"];


console.log(fruits[1]); // Banana

Array Methods

JavaScript provides many methods for arrays:

- `push()` – adds an item to the end


- `pop()` – removes the last item
- `shift()` – removes the first item
- `unshift()` – adds an item to the beginning
- `forEach()` – executes a function for each item

Example:

fruits.push("Orange");
fruits.forEach(function(fruit) {
console.log(fruit);
});
Chapter 6: Conditional Statements and Loops

Conditional statements and loops allow you to control the flow of your code. Conditions
decide what code runs, while loops allow you to repeat blocks of code.

Conditional Statements

JavaScript supports several conditional structures:

- `if`
- `else if`
- `else`
- `switch`

Example (if-else):

let age = 20;


if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

Example (switch):

let color = "blue";


switch (color) {
case "red":
console.log("Color is red");
break;
case "blue":
console.log("Color is blue");
break;
default:
console.log("Color not recognized");
}
Loops

Loops let you run code multiple times:

- `for` loop
- `while` loop
- `do...while` loop
- `for...of` and `for...in` loops

Example (for loop):

for (let i = 0; i < 5; i++) {


console.log("Number: " + i);
}

Example (while loop):

let i = 0;
while (i < 3) {
console.log("i is " + i);
i++;
}

Example (for...of loop):

const fruits = ["apple", "banana", "cherry"];


for (let fruit of fruits) {
console.log(fruit);
}
Chapter 7: JavaScript Project – To-Do List App

This project demonstrates how to build a fully functional To-Do List using HTML, CSS, and
JavaScript. It covers essential web development skills including DOM manipulation, event
handling, and localStorage.

Project Structure

The project consists of three main files:


- `index.html`
- `style.css`
- `script.js`

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>To-Do List App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>To-Do List</h1>
<input type="text" id="taskInput" placeholder="Add a new task">
<button id="addTask">Add Task</button>
<ul id="taskList"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
style.css

body {
font-family: Arial, sans-serif;
background: #f4f4f4;
display: flex;
justify-content: center;
padding: 50px;
}

.container {
background: #fff;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
width: 300px;
}

input {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}

button {
width: 100%;
padding: 10px;
background: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}

ul {
list-style: none;
padding: 0;
}

li {
padding: 10px;
border-bottom: 1px solid #ddd;
display: flex;
justify-content: space-between;
align-items: center;
}

li.completed {
text-decoration: line-through;
color: #888;
}

script.js

document.addEventListener("DOMContentLoaded", () => {
const taskInput = document.getElementById("taskInput");
const addTask = document.getElementById("addTask");
const taskList = document.getElementById("taskList");

// Load tasks from localStorage


let tasks = JSON.parse(localStorage.getItem("tasks")) || [];
tasks.forEach(task => renderTask(task.text, task.completed));

addTask.addEventListener("click", () => {
const text = taskInput.value.trim();
if (text !== "") {
renderTask(text);
tasks.push({ text, completed: false });
localStorage.setItem("tasks", JSON.stringify(tasks));
taskInput.value = "";
}
});

function renderTask(text, completed = false) {


const li = document.createElement("li");
li.textContent = text;
if (completed) li.classList.add("completed");

li.addEventListener("click", () => {
li.classList.toggle("completed");
tasks = tasks.map(t => t.text === text ? { ...t, completed: !
t.completed } : t);
localStorage.setItem("tasks", JSON.stringify(tasks));
});

const removeBtn = document.createElement("button");


removeBtn.textContent = "X";
removeBtn.style.marginLeft = "10px";
removeBtn.addEventListener("click", () => {
li.remove();
tasks = tasks.filter(t => t.text !== text);
localStorage.setItem("tasks", JSON.stringify(tasks));
});

li.appendChild(removeBtn);
taskList.appendChild(li);
}
});
Chapter 8: Introduction to SQL

SQL (Structured Query Language) is used to manage and manipulate relational databases. It
allows you to query, insert, update, and delete data using simple and powerful syntax.

Basic SQL Syntax

A basic SQL statement includes a command followed by the target table and conditions.

Example:

SELECT * FROM users;

Common SQL Commands

- `SELECT`: Retrieves data from one or more tables.


- `INSERT`: Adds new data to a table.
- `UPDATE`: Modifies existing data.
- `DELETE`: Removes data from a table.
- `CREATE`: Creates new tables or databases.
- `DROP`: Deletes tables or databases.

Sample Table and Data

Example: Creating a `users` table and inserting data.

CREATE TABLE users (


id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
);

INSERT INTO users (id, name, email)


VALUES (1, 'Alice', '[email protected]');
Chapter 9: SQL Queries – SELECT, WHERE, ORDER BY, and More

In this chapter, we explore SQL queries in greater detail. SQL allows you to filter, sort, and
retrieve data precisely according to your needs.

The SELECT Statement

The `SELECT` statement is used to retrieve data from a database.

Example:

SELECT name, email FROM users;

The WHERE Clause

`WHERE` is used to filter records.

Example:

SELECT * FROM users WHERE id = 1;

Comparison Operators

- `=` : Equal to
- `!=` or `<>` : Not equal to
- `>` : Greater than
- `<` : Less than
- `>=`, `<=` : Greater than or equal to, less than or equal to

Logical Operators

- `AND`: Combines multiple conditions (all must be true)


- `OR`: Combines multiple conditions (any can be true)
- `NOT`: Negates a condition

Example:

SELECT * FROM users WHERE name = 'Alice' AND email LIKE


'%@example.com';

ORDER BY Clause

`ORDER BY` is used to sort the result set.

Example:

SELECT * FROM users ORDER BY name ASC;


Chapter 1: Introduction to JavaScript

JavaScript is a dynamic, lightweight programming language used primarily to add


interactivity to web pages. It works alongside HTML and CSS to create responsive, dynamic
user experiences.

What Can JavaScript Do?

- Change HTML content and attributes.


- React to user actions (clicks, typing, scrolling, etc.).
- Validate form inputs.
- Fetch data from servers (APIs).
- Create browser-based games and applications.

Example: Basic JavaScript in HTML

<!DOCTYPE html>
<html>
<head>
<title>JS Example</title>
</head>
<body>
<h1 id="heading">Hello World</h1>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("heading").innerHTML = "Text
Changed!";
}
</script>
</body>
</html>
Chapter 2: JavaScript Syntax, Variables, and Data Types

Understanding the basic syntax and structure of JavaScript is crucial. In this chapter, you'll
learn how to declare variables, use different data types, and write syntactically correct
JavaScript code.

Variables

JavaScript uses three main keywords for variable declaration: var, let, and const.

- `var` was traditionally used, but it's now recommended to use `let` or `const`.
- `let` allows variable reassignment.
- `const` defines a constant, which cannot be reassigned.

Example:

let name = "John";


const age = 30;
var city = "New York";

Data Types

JavaScript supports several data types including:

- String: "Hello World"


- Number: 42
- Boolean: true or false
- Null: intentional absence of any value
- Undefined: variable declared but not yet assigned
- Object: { name: "Alice", age: 25 }
- Array: [1, 2, 3, 4]

Example:

let message = "Welcome";


let score = 100;
let isLoggedIn = true;
let data = null;
let user;
let profile = { name: "Alice", age: 25 };
let items = [10, 20, 30];
Chapter 3: Functions and Scope

Functions are reusable blocks of code that perform a specific task. Scope refers to the
context in which variables are accessible. Understanding how functions and scope work is
essential to writing clean and effective JavaScript.

Function Declaration and Invocation

JavaScript supports different ways to define functions:

1. **Function Declaration**

function greet(name) {
return "Hello, " + name + "!";
}

greet("Alice");

2. **Function Expression**

const greet = function(name) {


return "Hi, " + name;
};

3. **Arrow Function (ES6+)**

const greet = (name) => "Hey, " + name + "!";

Scope in JavaScript

Scope determines the visibility of variables. There are two types of scope:

- **Global Scope**: Accessible anywhere in the script.


- **Local Scope**: Variables declared inside a function are local.
Example:

let globalVar = "I'm global";

function showScope() {
let localVar = "I'm local";
console.log(globalVar);
console.log(localVar);
}

showScope();
console.log(localVar); // Error: localVar is not defined
Chapter 4: DOM Manipulation and Events

The Document Object Model (DOM) allows JavaScript to access and modify HTML content
dynamically. You can use JavaScript to change the structure, style, and content of a web
page in response to user actions.

Accessing DOM Elements

You can access elements using different methods:

- `getElementById()`
- `getElementsByClassName()`
- `querySelector()`
- `querySelectorAll()`

Example:

const heading = document.getElementById("main-heading");


const items = document.querySelectorAll(".list-item");

Changing Content and Style

You can modify HTML content and style dynamically.

Example:

heading.textContent = "New Heading";


heading.style.color = "blue";

Handling Events

JavaScript can respond to user events like clicks, typing, and form submissions.
Example:

const button = document.querySelector("button");


button.addEventListener("click", function() {
alert("Button clicked!");
});
Chapter 5: Objects and Arrays

Objects and arrays are fundamental data structures in JavaScript. They allow you to group
related data and manipulate collections efficiently.

Objects

Objects store data in key-value pairs. Each key is a string, and the value can be any type.

Example:

const person = {
name: "Alice",
age: 30,
isStudent: false
};

console.log(person.name); // Alice

Modifying Objects

You can update, add, or delete properties in an object.

Example:

person.age = 31;
person.city = "New York";
delete person.isStudent;

Arrays

Arrays are ordered collections of items. You can access elements using index numbers.
Example:

const fruits = ["Apple", "Banana", "Cherry"];


console.log(fruits[1]); // Banana

Array Methods

JavaScript provides many methods for arrays:

- `push()` – adds an item to the end


- `pop()` – removes the last item
- `shift()` – removes the first item
- `unshift()` – adds an item to the beginning
- `forEach()` – executes a function for each item

Example:

fruits.push("Orange");
fruits.forEach(function(fruit) {
console.log(fruit);
});
Chapter 6: Conditional Statements and Loops

Conditional statements and loops allow you to control the flow of your code. Conditions
decide what code runs, while loops allow you to repeat blocks of code.

Conditional Statements

JavaScript supports several conditional structures:

- `if`
- `else if`
- `else`
- `switch`

Example (if-else):

let age = 20;


if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

Example (switch):

let color = "blue";


switch (color) {
case "red":
console.log("Color is red");
break;
case "blue":
console.log("Color is blue");
break;
default:
console.log("Color not recognized");
}
Loops

Loops let you run code multiple times:

- `for` loop
- `while` loop
- `do...while` loop
- `for...of` and `for...in` loops

Example (for loop):

for (let i = 0; i < 5; i++) {


console.log("Number: " + i);
}

Example (while loop):

let i = 0;
while (i < 3) {
console.log("i is " + i);
i++;
}

Example (for...of loop):

const fruits = ["apple", "banana", "cherry"];


for (let fruit of fruits) {
console.log(fruit);
}
Chapter 7: JavaScript Project – To-Do List App

This project demonstrates how to build a fully functional To-Do List using HTML, CSS, and
JavaScript. It covers essential web development skills including DOM manipulation, event
handling, and localStorage.

Project Structure

The project consists of three main files:


- `index.html`
- `style.css`
- `script.js`

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>To-Do List App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>To-Do List</h1>
<input type="text" id="taskInput" placeholder="Add a new task">
<button id="addTask">Add Task</button>
<ul id="taskList"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
style.css

body {
font-family: Arial, sans-serif;
background: #f4f4f4;
display: flex;
justify-content: center;
padding: 50px;
}

.container {
background: #fff;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
width: 300px;
}

input {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}

button {
width: 100%;
padding: 10px;
background: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}

ul {
list-style: none;
padding: 0;
}

li {
padding: 10px;
border-bottom: 1px solid #ddd;
display: flex;
justify-content: space-between;
align-items: center;
}

li.completed {
text-decoration: line-through;
color: #888;
}

script.js

document.addEventListener("DOMContentLoaded", () => {
const taskInput = document.getElementById("taskInput");
const addTask = document.getElementById("addTask");
const taskList = document.getElementById("taskList");

// Load tasks from localStorage


let tasks = JSON.parse(localStorage.getItem("tasks")) || [];
tasks.forEach(task => renderTask(task.text, task.completed));

addTask.addEventListener("click", () => {
const text = taskInput.value.trim();
if (text !== "") {
renderTask(text);
tasks.push({ text, completed: false });
localStorage.setItem("tasks", JSON.stringify(tasks));
taskInput.value = "";
}
});

function renderTask(text, completed = false) {


const li = document.createElement("li");
li.textContent = text;
if (completed) li.classList.add("completed");

li.addEventListener("click", () => {
li.classList.toggle("completed");
tasks = tasks.map(t => t.text === text ? { ...t, completed: !
t.completed } : t);
localStorage.setItem("tasks", JSON.stringify(tasks));
});

const removeBtn = document.createElement("button");


removeBtn.textContent = "X";
removeBtn.style.marginLeft = "10px";
removeBtn.addEventListener("click", () => {
li.remove();
tasks = tasks.filter(t => t.text !== text);
localStorage.setItem("tasks", JSON.stringify(tasks));
});

li.appendChild(removeBtn);
taskList.appendChild(li);
}
});
Chapter 8: Introduction to SQL

SQL (Structured Query Language) is used to manage and manipulate relational databases. It
allows you to query, insert, update, and delete data using simple and powerful syntax.

Basic SQL Syntax

A basic SQL statement includes a command followed by the target table and conditions.

Example:

SELECT * FROM users;

Common SQL Commands

- `SELECT`: Retrieves data from one or more tables.


- `INSERT`: Adds new data to a table.
- `UPDATE`: Modifies existing data.
- `DELETE`: Removes data from a table.
- `CREATE`: Creates new tables or databases.
- `DROP`: Deletes tables or databases.

Sample Table and Data

Example: Creating a `users` table and inserting data.

CREATE TABLE users (


id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
);

INSERT INTO users (id, name, email)


VALUES (1, 'Alice', '[email protected]');
Chapter 9: SQL Queries – SELECT, WHERE, ORDER BY, and More

In this chapter, we explore SQL queries in greater detail. SQL allows you to filter, sort, and
retrieve data precisely according to your needs.

The SELECT Statement

The `SELECT` statement is used to retrieve data from a database.

Example:

SELECT name, email FROM users;

The WHERE Clause

`WHERE` is used to filter records.

Example:

SELECT * FROM users WHERE id = 1;

Comparison Operators

- `=` : Equal to
- `!=` or `<>` : Not equal to
- `>` : Greater than
- `<` : Less than
- `>=`, `<=` : Greater than or equal to, less than or equal to

Logical Operators

- `AND`: Combines multiple conditions (all must be true)


- `OR`: Combines multiple conditions (any can be true)
- `NOT`: Negates a condition

Example:

SELECT * FROM users WHERE name = 'Alice' AND email LIKE


'%@example.com';

ORDER BY Clause

`ORDER BY` is used to sort the result set.

Example:

SELECT * FROM users ORDER BY name ASC;


Chapter 10: SQL Joins and Relationships

Joins are used in SQL to combine rows from two or more tables, based on a related column
between them. Understanding joins is essential for managing relationships in relational
databases.

Types of Joins

- `INNER JOIN`: Returns records with matching values in both tables


- `LEFT JOIN` (or LEFT OUTER JOIN): Returns all records from the left table, and the
matched records from the right table
- `RIGHT JOIN` (or RIGHT OUTER JOIN): Returns all records from the right table, and the
matched records from the left table
- `FULL JOIN` (or FULL OUTER JOIN): Returns all records when there is a match in either left
or right table

Example: Joining Users and Orders Tables

Suppose we have the following tables:

Table: `users`

| id | name |

|----|----------|

| 1 | Alice |

| 2 | Bob |

Table: `orders`

| id | user_id | product |

|----|---------|-------------|

|1 |1 | Laptop |

|2 |2 | Smartphone |
|3 |1 | Mouse |

INNER JOIN Example:

SELECT users.name, orders.product


FROM users
INNER JOIN orders ON users.id = orders.user_id;

LEFT JOIN Example:

SELECT users.name, orders.product


FROM users
LEFT JOIN orders ON users.id = orders.user_id;

Using Aliases in Joins

You can use aliases to simplify table references in joins.

Example:

SELECT u.name, o.product


FROM users AS u
JOIN orders AS o ON u.id = o.user_id;
Chapter 1: Introduction to JavaScript

JavaScript is a dynamic, lightweight programming language used primarily to add


interactivity to web pages. It works alongside HTML and CSS to create responsive, dynamic
user experiences.

What Can JavaScript Do?

- Change HTML content and attributes.


- React to user actions (clicks, typing, scrolling, etc.).
- Validate form inputs.
- Fetch data from servers (APIs).
- Create browser-based games and applications.

Example: Basic JavaScript in HTML

<!DOCTYPE html>
<html>
<head>
<title>JS Example</title>
</head>
<body>
<h1 id="heading">Hello World</h1>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("heading").innerHTML = "Text
Changed!";
}
</script>
</body>
</html>
Chapter 2: JavaScript Syntax, Variables, and Data Types

Understanding the basic syntax and structure of JavaScript is crucial. In this chapter, you'll
learn how to declare variables, use different data types, and write syntactically correct
JavaScript code.

Variables

JavaScript uses three main keywords for variable declaration: var, let, and const.

- `var` was traditionally used, but it's now recommended to use `let` or `const`.
- `let` allows variable reassignment.
- `const` defines a constant, which cannot be reassigned.

Example:

let name = "John";


const age = 30;
var city = "New York";

Data Types

JavaScript supports several data types including:

- String: "Hello World"


- Number: 42
- Boolean: true or false
- Null: intentional absence of any value
- Undefined: variable declared but not yet assigned
- Object: { name: "Alice", age: 25 }
- Array: [1, 2, 3, 4]

Example:

let message = "Welcome";


let score = 100;
let isLoggedIn = true;
let data = null;
let user;
let profile = { name: "Alice", age: 25 };
let items = [10, 20, 30];
Chapter 3: Functions and Scope

Functions are reusable blocks of code that perform a specific task. Scope refers to the
context in which variables are accessible. Understanding how functions and scope work is
essential to writing clean and effective JavaScript.

Function Declaration and Invocation

JavaScript supports different ways to define functions:

1. **Function Declaration**

function greet(name) {
return "Hello, " + name + "!";
}

greet("Alice");

2. **Function Expression**

const greet = function(name) {


return "Hi, " + name;
};

3. **Arrow Function (ES6+)**

const greet = (name) => "Hey, " + name + "!";

Scope in JavaScript

Scope determines the visibility of variables. There are two types of scope:

- **Global Scope**: Accessible anywhere in the script.


- **Local Scope**: Variables declared inside a function are local.
Example:

let globalVar = "I'm global";

function showScope() {
let localVar = "I'm local";
console.log(globalVar);
console.log(localVar);
}

showScope();
console.log(localVar); // Error: localVar is not defined
Chapter 4: DOM Manipulation and Events

The Document Object Model (DOM) allows JavaScript to access and modify HTML content
dynamically. You can use JavaScript to change the structure, style, and content of a web
page in response to user actions.

Accessing DOM Elements

You can access elements using different methods:

- `getElementById()`
- `getElementsByClassName()`
- `querySelector()`
- `querySelectorAll()`

Example:

const heading = document.getElementById("main-heading");


const items = document.querySelectorAll(".list-item");

Changing Content and Style

You can modify HTML content and style dynamically.

Example:

heading.textContent = "New Heading";


heading.style.color = "blue";

Handling Events

JavaScript can respond to user events like clicks, typing, and form submissions.
Example:

const button = document.querySelector("button");


button.addEventListener("click", function() {
alert("Button clicked!");
});
Chapter 5: Objects and Arrays

Objects and arrays are fundamental data structures in JavaScript. They allow you to group
related data and manipulate collections efficiently.

Objects

Objects store data in key-value pairs. Each key is a string, and the value can be any type.

Example:

const person = {
name: "Alice",
age: 30,
isStudent: false
};

console.log(person.name); // Alice

Modifying Objects

You can update, add, or delete properties in an object.

Example:

person.age = 31;
person.city = "New York";
delete person.isStudent;

Arrays

Arrays are ordered collections of items. You can access elements using index numbers.
Example:

const fruits = ["Apple", "Banana", "Cherry"];


console.log(fruits[1]); // Banana

Array Methods

JavaScript provides many methods for arrays:

- `push()` – adds an item to the end


- `pop()` – removes the last item
- `shift()` – removes the first item
- `unshift()` – adds an item to the beginning
- `forEach()` – executes a function for each item

Example:

fruits.push("Orange");
fruits.forEach(function(fruit) {
console.log(fruit);
});
Chapter 6: Conditional Statements and Loops

Conditional statements and loops allow you to control the flow of your code. Conditions
decide what code runs, while loops allow you to repeat blocks of code.

Conditional Statements

JavaScript supports several conditional structures:

- `if`
- `else if`
- `else`
- `switch`

Example (if-else):

let age = 20;


if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

Example (switch):

let color = "blue";


switch (color) {
case "red":
console.log("Color is red");
break;
case "blue":
console.log("Color is blue");
break;
default:
console.log("Color not recognized");
}
Loops

Loops let you run code multiple times:

- `for` loop
- `while` loop
- `do...while` loop
- `for...of` and `for...in` loops

Example (for loop):

for (let i = 0; i < 5; i++) {


console.log("Number: " + i);
}

Example (while loop):

let i = 0;
while (i < 3) {
console.log("i is " + i);
i++;
}

Example (for...of loop):

const fruits = ["apple", "banana", "cherry"];


for (let fruit of fruits) {
console.log(fruit);
}
Chapter 7: JavaScript Project – To-Do List App

This project demonstrates how to build a fully functional To-Do List using HTML, CSS, and
JavaScript. It covers essential web development skills including DOM manipulation, event
handling, and localStorage.

Project Structure

The project consists of three main files:


- `index.html`
- `style.css`
- `script.js`

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>To-Do List App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>To-Do List</h1>
<input type="text" id="taskInput" placeholder="Add a new task">
<button id="addTask">Add Task</button>
<ul id="taskList"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
style.css

body {
font-family: Arial, sans-serif;
background: #f4f4f4;
display: flex;
justify-content: center;
padding: 50px;
}

.container {
background: #fff;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
width: 300px;
}

input {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}

button {
width: 100%;
padding: 10px;
background: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}

ul {
list-style: none;
padding: 0;
}

li {
padding: 10px;
border-bottom: 1px solid #ddd;
display: flex;
justify-content: space-between;
align-items: center;
}

li.completed {
text-decoration: line-through;
color: #888;
}

script.js

document.addEventListener("DOMContentLoaded", () => {
const taskInput = document.getElementById("taskInput");
const addTask = document.getElementById("addTask");
const taskList = document.getElementById("taskList");

// Load tasks from localStorage


let tasks = JSON.parse(localStorage.getItem("tasks")) || [];
tasks.forEach(task => renderTask(task.text, task.completed));

addTask.addEventListener("click", () => {
const text = taskInput.value.trim();
if (text !== "") {
renderTask(text);
tasks.push({ text, completed: false });
localStorage.setItem("tasks", JSON.stringify(tasks));
taskInput.value = "";
}
});

function renderTask(text, completed = false) {


const li = document.createElement("li");
li.textContent = text;
if (completed) li.classList.add("completed");

li.addEventListener("click", () => {
li.classList.toggle("completed");
tasks = tasks.map(t => t.text === text ? { ...t, completed: !
t.completed } : t);
localStorage.setItem("tasks", JSON.stringify(tasks));
});

const removeBtn = document.createElement("button");


removeBtn.textContent = "X";
removeBtn.style.marginLeft = "10px";
removeBtn.addEventListener("click", () => {
li.remove();
tasks = tasks.filter(t => t.text !== text);
localStorage.setItem("tasks", JSON.stringify(tasks));
});

li.appendChild(removeBtn);
taskList.appendChild(li);
}
});
Chapter 8: Introduction to SQL

SQL (Structured Query Language) is used to manage and manipulate relational databases. It
allows you to query, insert, update, and delete data using simple and powerful syntax.

Basic SQL Syntax

A basic SQL statement includes a command followed by the target table and conditions.

Example:

SELECT * FROM users;

Common SQL Commands

- `SELECT`: Retrieves data from one or more tables.


- `INSERT`: Adds new data to a table.
- `UPDATE`: Modifies existing data.
- `DELETE`: Removes data from a table.
- `CREATE`: Creates new tables or databases.
- `DROP`: Deletes tables or databases.

Sample Table and Data

Example: Creating a `users` table and inserting data.

CREATE TABLE users (


id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
);

INSERT INTO users (id, name, email)


VALUES (1, 'Alice', '[email protected]');
Chapter 9: SQL Queries – SELECT, WHERE, ORDER BY, and More

In this chapter, we explore SQL queries in greater detail. SQL allows you to filter, sort, and
retrieve data precisely according to your needs.

The SELECT Statement

The `SELECT` statement is used to retrieve data from a database.

Example:

SELECT name, email FROM users;

The WHERE Clause

`WHERE` is used to filter records.

Example:

SELECT * FROM users WHERE id = 1;

Comparison Operators

- `=` : Equal to
- `!=` or `<>` : Not equal to
- `>` : Greater than
- `<` : Less than
- `>=`, `<=` : Greater than or equal to, less than or equal to

Logical Operators

- `AND`: Combines multiple conditions (all must be true)


- `OR`: Combines multiple conditions (any can be true)
- `NOT`: Negates a condition

Example:

SELECT * FROM users WHERE name = 'Alice' AND email LIKE


'%@example.com';

ORDER BY Clause

`ORDER BY` is used to sort the result set.

Example:

SELECT * FROM users ORDER BY name ASC;


Chapter 10: SQL Joins and Relationships

Joins are used in SQL to combine rows from two or more tables, based on a related column
between them. Understanding joins is essential for managing relationships in relational
databases.

Types of Joins

- `INNER JOIN`: Returns records with matching values in both tables


- `LEFT JOIN` (or LEFT OUTER JOIN): Returns all records from the left table, and the
matched records from the right table
- `RIGHT JOIN` (or RIGHT OUTER JOIN): Returns all records from the right table, and the
matched records from the left table
- `FULL JOIN` (or FULL OUTER JOIN): Returns all records when there is a match in either left
or right table

Example: Joining Users and Orders Tables

Suppose we have the following tables:

Table: `users`

| id | name |

|----|----------|

| 1 | Alice |

| 2 | Bob |

Table: `orders`

| id | user_id | product |

|----|---------|-------------|

|1 |1 | Laptop |

|2 |2 | Smartphone |
|3 |1 | Mouse |

INNER JOIN Example:

SELECT users.name, orders.product


FROM users
INNER JOIN orders ON users.id = orders.user_id;

LEFT JOIN Example:

SELECT users.name, orders.product


FROM users
LEFT JOIN orders ON users.id = orders.user_id;

Using Aliases in Joins

You can use aliases to simplify table references in joins.

Example:

SELECT u.name, o.product


FROM users AS u
JOIN orders AS o ON u.id = o.user_id;
Chapter 11: Advanced SQL – GROUP BY, HAVING, Subqueries, and Indexes

Advanced SQL concepts help you write more powerful and efficient queries. This chapter
introduces `GROUP BY`, `HAVING`, subqueries, and indexing techniques.

GROUP BY Clause

`GROUP BY` groups rows that have the same values into summary rows. It's commonly used
with aggregate functions like COUNT, SUM, AVG, etc.

Example:

SELECT user_id, COUNT(*) as total_orders


FROM orders
GROUP BY user_id;

HAVING Clause

`HAVING` is used to filter records after grouping (similar to WHERE but for groups).

Example:

SELECT user_id, COUNT(*) as total_orders


FROM orders
GROUP BY user_id
HAVING total_orders > 1;

Subqueries

A subquery is a query nested inside another query. It allows for


complex filtering and data manipulation.

Example: Find users who placed orders


SELECT name FROM users
WHERE id IN (SELECT user_id FROM orders);

Indexes

Indexes speed up data retrieval operations. They work like an index in a book.

Example:

CREATE INDEX idx_user_id ON orders(user_id);

While indexes improve read performance, they may slow down write operations like
INSERT or UPDATE.

You might also like