# Session 4: JavaScript Basics
## Overview
Welcome to Session 4! In this session, you'll learn the fundamentals of JavaScript, a powerful programming language that adds interactivity to websites. JavaScript is essential for modern web development and is used for creating dynamic user experiences.
## Learning Objectives
- Understand what JavaScript is and its role in web development
- Learn JavaScript syntax and basic programming concepts
- Manipulate HTML elements using JavaScript
- Handle user events and create interactive web elements
- Understand how to use JavaScript to solve common web development problems
## Topics Covered
### 1. Introduction to JavaScript
JavaScript is a high-level, interpreted programming language that conforms to the ECMAScript specification. It's primarily used for enhancing web pages to provide a more interactive experience for users.
#### Key Features:
- Client-side scripting language (runs in the browser)
- Dynamic typing (variables can change types)
- Object-oriented with prototype-based inheritance
- Event-driven programming
- Single-threaded with asynchronous capabilities
### 2. Adding JavaScript to HTML
There are three ways to add JavaScript to your HTML:
#### Inline JavaScript
```html
```
#### Internal JavaScript
```html
```
#### External JavaScript
```html
```
### 3. JavaScript Syntax Basics
#### Variables and Data Types
```javascript
// Variables
let name = 'John'; // String
let age = 25; // Number
let isStudent = true; // Boolean
let hobbies = ['reading', 'gaming', 'coding']; // Array
let person = { // Object
name: 'John',
age: 25,
isStudent: true
};
const PI = 3.14159; // Constant
// Modern JavaScript uses let and const instead of var
```
#### Operators
```javascript
// Arithmetic Operators
let sum = 5 + 3; // Addition
let difference = 5 - 3; // Subtraction
let product = 5 * 3; // Multiplication
let quotient = 5 / 3; // Division
let remainder = 5 % 3; // Modulus
// Comparison Operators
let isEqual = 5 === 3; // Strict equality (value and type)
let isNotEqual = 5 !== 3; // Strict inequality
let isGreater = 5 > 3; // Greater than
let isLess = 5 < 3; // Less than
// Logical Operators
let andOperator = true && false; // Logical AND
let orOperator = true || false; // Logical OR
let notOperator = !true; // Logical NOT
```
#### Control Flow
```javascript
// Conditional Statements
if (age >= 18) {
console.log('You are an adult');
} else if (age >= 13) {
console.log('You are a teenager');
} else {
console.log('You are a child');
}
// Switch Statement
switch (day) {
case 'Monday':
console.log('Start of the work week');
break;
case 'Friday':
console.log('End of the work week');
break;
default:
console.log('Another day');
}
// Loops
// For Loop
for (let i = 0; i < 5; i++) {
console.log(i); // Outputs 0, 1, 2, 3, 4
}
// While Loop
let count = 0;
while (count < 5) {
console.log(count); // Outputs 0, 1, 2, 3, 4
count++;
}
// For...of Loop (for arrays)
for (let hobby of hobbies) {
console.log(hobby); // Outputs each hobby
}
// For...in Loop (for objects)
for (let key in person) {
console.log(key + ': ' + person[key]); // Outputs each property
}
```
#### Functions
```javascript
// Function Declaration
function greet(name) {
return 'Hello, ' + name + '!';
}
// Function Expression
const sayGoodbye = function(name) {
return 'Goodbye, ' + name + '!';
};
// Arrow Function (ES6)
const multiply = (a, b) => a * b;
// Calling Functions
console.log(greet('Alice')); // Hello, Alice!
console.log(sayGoodbye('Bob')); // Goodbye, Bob!
console.log(multiply(4, 5)); // 20
```
### 4. DOM Manipulation
The Document Object Model (DOM) is a programming interface for HTML documents. JavaScript can access and change all the elements of an HTML document through the DOM.
```javascript
// Selecting elements
const heading = document.getElementById('main-heading');
const paragraphs = document.getElementsByTagName('p');
const buttons = document.getElementsByClassName('btn');
const firstLink = document.querySelector('a');
const allLinks = document.querySelectorAll('a');
// Changing content
heading.textContent = 'New Heading'; // Changes text
heading.innerHTML = 'New Heading'; // Changes HTML
// Changing styles
heading.style.color = 'blue';
heading.style.fontSize = '24px';
// Adding/removing classes
heading.classList.add('highlight');
heading.classList.remove('old-class');
heading.classList.toggle('active');
// Creating new elements
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph.';
document.body.appendChild(newParagraph);
// Removing elements
const oldElement = document.getElementById('old-element');
oldElement.parentNode.removeChild(oldElement);
// or in modern browsers:
oldElement.remove();
```
### 5. Event Handling
Events are actions or occurrences that happen in the browser which you can respond to using JavaScript.
```javascript
// Adding an event listener
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Button was clicked!');
});
// Common events
// click, dblclick, mouseover, mouseout, keydown, keyup, submit, load
// Event object
button.addEventListener('click', function(event) {
console.log('Event type:', event.type);
console.log('Target element:', event.target);
event.preventDefault(); // Prevents the default action
});
// Event delegation
document.getElementById('parent-list').addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
console.log('List item clicked:', event.target.textContent);
}
});
```
## Practice Exercises
1. Create a simple to-do list app where users can add and remove tasks
2. Build a form that validates user input (e.g., checking if all required fields are filled)
3. Create a simple calculator that performs basic arithmetic operations
4. Build an image slider that changes images when clicked
5. Create a countdown timer that updates in real-time
## Additional Resources
- [MDN Web Docs - JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript)
- [JavaScript.info](https://javascript.info/)
- [W3Schools JavaScript Tutorial](https://www.w3schools.com/js/)
- [Eloquent JavaScript](https://eloquentjavascript.net/)
- [JavaScript 30](https://javascript30.com/) - 30 Day Vanilla JS Coding Challenge
## Next Steps
Now that you understand the basics of JavaScript, you're ready to move on to [Session 5: Ready to build a WebApp?](Session-5-WebApp-Intro.md) where you'll learn about databases, backend, and frontend development to build a complete web application.