Module 1: Introduction to JavaScript
1. What is JavaScript?
JavaScript is a programming language used to create interactive and dynamic content on
websites. It is an essential part of front-end web development, working alongside HTML
(structure) and CSS (styling).
JavaScript enables things like form validation, dynamic content loading, animations, and user
interaction with the page (clicks, hover effects, etc.).
Module 2: Basic JavaScript Syntax
1. Variables and Data Types
Variables are used to store data. In JavaScript, you can declare variables using var, let, or const.
var: Used in older JavaScript versions. It has a function scope and can be re-assigned.
let: Preferred for modern JavaScript. It has a block-level scope and can be re-assigned.
const: Used for constants (values that don’t change), also block-scoped.
Example:
let message = "Hello, World!"; // String
const pi = 3.14159; // Constant value
var age = 30; // Number
console.log(message, pi, age); // Output: Hello, World! 3.14159 30
JavaScript has primitive types (like string, number, boolean, etc.) and complex types (like objects and
arrays).
2. Operators
JavaScript includes a variety of operators for performing arithmetic, comparisons, and logic.
Arithmetic operators: (+,*, -, /)
o + adds two numbers, * multiplies them, etc.
Comparison operators: (==, ===, >, <)
o == checks if values are equal, while === checks both value and type.
Logical operators: (&&, ||, !)
o && checks if both conditions are true, || checks if at least one is true, ! negates a
condition.
Example:
let a = 5, b = 10;
console.log(a + b); // Addition: 15
console.log(a === b); // Comparison: false
console.log(a > b && b > a); // Logical AND: false
3. Control Flow Statements
Control flow statements allow you to control the execution flow of your code based on certain
conditions.
if-else: Used to execute a block of code based on a condition.
switch: Useful when you have multiple options based on the value of a variable.
Example:
let number = 15;
if (number % 2 === 0) {
console.log('Even number'); // Output: Odd number
} else {
console.log('Odd number');
let fruit = 'apple';
switch(fruit) {
case 'apple':
console.log('Fruit is apple');
break;
default:
console.log('Unknown fruit');
Module 3: Functions and Scope
1. Defining Functions
Functions are reusable blocks of code designed to perform a specific task.
Function Declaration: The classic way of defining a function.
Arrow Function: A more concise way to define functions in modern JavaScript.
Example:
function greet(name) {
return `Hello, ${name}!`;
console.log(greet('John')); // Output: Hello, John!
const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
2. Scope and Closures
Local Scope: Variables defined inside a function are accessible only within that function.
Global Scope: Variables declared outside any function are accessible throughout the code.
Closure: A closure is created when a function remembers the environment in which it was
created, even if it's executed outside that environment.
Example:
let outerVar = 'I am outside!';
function outer() {
let innerVar = 'I am inside!';
function inner() {
console.log(outerVar); // Lexical scoping
console.log(innerVar); // Closure
inner();
outer();
Module 4: Arrays and Objects
1. Arrays
Arrays are ordered collections of elements. You can use various methods to manipulate arrays like
adding/removing elements.
Example:
let fruits = ['apple', 'banana', 'cherry'];
fruits.push('orange'); // Adds 'orange' to the end
fruits[1] = 'blueberry'; // Modifies the second element
console.log(fruits); // Output: ['apple', 'blueberry', 'cherry', 'orange']
2. Objects
Objects are collections of key-value pairs. You can use objects to represent more complex data, like a
person with a name and age.
Example:
const person = { name: 'Alice', age: 25 };
console.log(person.name); // Output: Alice
person.age = 26; // Modifies the value of the age property
person.greet = function() {
console.log('Hello ' + this.name);
};
person.greet(); // Output: Hello Alice
Module 5: Advanced JavaScript Concepts
1. Asynchronous JavaScript
JavaScript is synchronous by default, meaning it executes code line by line. Asynchronous operations
(like fetching data from an API) allow your program to continue executing while waiting for a task to
finish.
Callback: A function passed as an argument to be executed later.
Promises: Objects representing the eventual completion (or failure) of an asynchronous
operation.
Async/Await: Modern syntax for handling promises more easily.
Example:
// Callback
setTimeout(function() {
console.log('This is a callback!');
}, 1000);
// Promise
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve('Operation successful');
} else {
reject('Operation failed');
});
promise.then(message => console.log(message)).catch(error => console.log(error));
// Async/Await
async function fetchData() {
let data = await fetch('https://jsonplaceholder.typicode.com/users');
let json = await data.json();
console.log(json);
fetchData();
2. Error Handling
Error handling ensures your code doesn’t crash when something goes wrong. The try, catch, and finally
blocks are used to manage errors in JavaScript.
Example:
try {
let result = 10 / 0;
if (result === Infinity) throw "Cannot divide by zero";
} catch (error) {
console.log('Error:', error); // Output: Error: Cannot divide by zero
} finally {
console.log('Execution finished'); // This always runs
Module 6: DOM Manipulation and Events
1. DOM Basics
The DOM (Document Object Model) allows you to interact with and manipulate HTML elements using
JavaScript. You can access elements, change their content, or modify their styles.
Example:
document.getElementById('myButton').onclick = function() {
document.getElementById('myText').textContent = "Button clicked!";
}
2. Handling Events
Events are actions that occur in the browser, like a button click or a form submission. JavaScript allows
you to handle these events with event listeners.
Example:
const button = document.getElementById('btn');
button.addEventListener('click', (event) => {
alert('Button clicked!');
});
Module 7: Object-Oriented Programming (OOP) in JavaScript
1. Classes and Objects
Classes are blueprints for creating objects. Objects are instances of classes. JavaScript also supports
inheritance, allowing one class to extend another.
Example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
greet() {
console.log('Hello, ' + this.name);
const person1 = new Person('Alice', 25);
person1.greet(); // Output: Hello, Alice
2. Prototypal Inheritance
JavaScript uses prototypes to allow one object to inherit properties and methods from another object.
Example:
function Animal(name) {
this.name = name;
Animal.prototype.speak = function() {
console.log(this.name + ' makes a sound.');
};
const dog = new Animal('Dog');
dog.speak(); // Output: Dog makes a sound.