In this chapter, we will cover the fundamental concepts of JavaScript, including variables, data types, and operators. These are the building blocks of JavaScript programming.
What is JavaScript?
Example 1: Displaying a Message in the Console
console.log("Hello, World!");
Example 2: Displaying a Message on a Webpage
document.write("Welcome to JavaScript!");
Example 3: Showing an Alert Box
alert("This is an alert box!");
Variables in JavaScript
JavaScript has three ways to declare variables:
Example 1: Declaring Variables
let name = "John";
const age = 30;
var isStudent = true;
Example 2: Understanding Data Types
let score = 100;
let message = "JavaScript is fun!";
let isActive = false;
Example 3: Checking Data Types with typeof
console.log(typeof 42);
console.log(typeof "Hello");
console.log(typeof true);
Operators perform actions on variables and values. The main types are:
Used for mathematical operations:
Example 1: Performing Arithmetic Operations
let a = 10;
let b = 3;
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
console.log(a % b);
console.log(a ** b);
Example 2: Increment and Decrement
let x = 5;
x++;
console.log(x);
let y = 10;
y--;
console.log(y);
Example 3: Using Arithmetic Operators in Expressions
let num1 = 15;
let num2 = 5;
let result = (num1 + num2) * 2;
console.log(result);
Used to compare values and return true or false:
Example 1: Basic Comparison
console.log(5 == "5");
console.log(5 === "5");
console.log(10 > 5);
console.log(10 < 5);
Example 2: Comparing Strings
console.log("apple" > "banana");
console.log("100" > "50");
console.log("A" < "B");
Example 3: Checking Inequality
let num = 10;
console.log(num != 5);
console.log(num !== "10");
Used to combine multiple conditions:
Example 1: Using && (AND Operator)
let isLoggedIn = true;
let hasPermission = false;
console.log(isLoggedIn && hasPermission);
console.log(true && true);
console.log(false && true);
Example 2: Using || (OR Operator)
let isWeekend = true;
let isHoliday = false;
console.log(isWeekend || isHoliday);
console.log(false || false);
console.log(true || false);
Example 3: Using ! (NOT Operator)
let isAvailable = false;
console.log(!isAvailable);
console.log(!true);
console.log(!false);
In this chapter, we covered:
This knowledge forms the foundation for writing JavaScript programs. In the next chapter, we will learn about Control Flow (If-Else Statements & Loops)!
Control flow determines how a program executes based on conditions and loops. This chapter covers conditional statements (if-else, switch) and loops (for, while, do-while).
Conditional statements allow the program to execute different code blocks based on conditions.
Executes a block of code only if a condition is true.
Example 1: Checking Age
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
}
// Output: "You are an adult." (because 20 is greater than 18)
Example 2: Checking a Number's Sign
let num = -5;
if (num > 0) {
console.log("Positive number.");
}
if (num < 0) {
console.log("Negative number.");
}
// Output: "Negative number." (because -5 is less than 0)
Example 3: Checking if a Variable is Defined
let name = "John";
if (name) {
console.log("The variable has a value.");
}
// Output: "The variable has a value."
Executes one block if the condition is true, otherwise, executes the else block.
Example 1: Checking Voting Eligibility
let age = 16;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You cannot vote.");
}
// Output: "You cannot vote."
Example 2: Checking Even or Odd Number
let number = 9;
if (number % 2 === 0) {
console.log("Even number.");
} else {
console.log("Odd number.");
}
// Output: "Odd number." (because 9 is not divisible by 2)
Example 3: Checking User Login Status
let isLoggedIn = false;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in.");
}
// Output: "Please log in."
Checks multiple conditions one by one.
Example 1: Grading System
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
// Output: "Grade: B"
Example 2: Temperature Check
let temperature = 15;
if (temperature >= 30) {
console.log("It's hot.");
} else if (temperature >= 20) {
console.log("It's warm.");
} else {
console.log("It's cold.");
}
// Output: "It's cold."
Example 3: Checking Password Strength
let password = "abc";
if (password.length >= 8) {
console.log("Strong password.");
} else if (password.length >= 5) {
console.log("Moderate password.");
} else {
console.log("Weak password.");
}
// Output: "Weak password."
Used for multiple exact value comparisons.
Example 1: Day of the Week
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}
// Output: "Wednesday"
Example 2: Checking Traffic Light
let signal = "red";
switch (signal) {
case "red":
console.log("Stop.");
break;
case "yellow":
console.log("Slow down.");
break;
case "green":
console.log("Go.");
break;
default:
console.log("Invalid signal.");
}
// Output: "Stop."
Example 3: Choosing a Beverage
let choice = "coffee";
switch (choice) {
case "tea":
console.log("Serving tea.");
break;
case "coffee":
console.log("Serving coffee.");
break;
case "juice":
console.log("Serving juice.");
break;
default:
console.log("Invalid choice.");
}
// Output: "Serving coffee."
Loops repeat a block of code multiple times. The main types are:
Repeats a block a specific number of times.
Example 1: Printing Numbers 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1, 2, 3, 4, 5
Example 2: Looping Through an Array
let fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Output: "Apple", "Banana", "Cherry"
Example 3: Printing Even Numbers
for (let i = 2; i <= 10; i += 2) {
console.log(i);
}
// Output: 2, 4, 6, 8, 10
Runs while the condition is true.
Example 1: Printing Numbers 1 to 5
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
// Output: 1, 2, 3, 4, 5
Example 2: Countdown from 5
let count = 5;
while (count > 0) {
console.log(count);
count--;
}
// Output: 5, 4, 3, 2, 1
Example 3: User Login Attempt
let attempts = 3;
while (attempts > 0) {
console.log("Enter your password. Attempts left: " + attempts);
attempts--;
}
// Output: 3 messages prompting for password
Runs at least once, then checks the condition.
Example 1: Executing a Block Once
let x = 5;
do {
console.log("Runs at least once.");
} while (x < 5);
// Output: "Runs at least once."
These control flow concepts help make programs dynamic and responsive!
Functions are blocks of reusable code that perform a specific task. They help in code organization, reusability, and modularity.
A function declaration is the traditional way of defining a function. It can be called before its definition due to JavaScript's hoisting.
function greet() {
console.log("Hello, welcome to JavaScript!");
}
greet();
Output: "Hello, welcome to JavaScript!"
function square(num) {
console.log("The square of", num, "is", num * num);
}
square(4);
square(7);
Output:
"The square of 4 is 16"
"The square of 7 is 49"
// Function with two parameters function add(a, b) { console.log("The sum of", a, "and", b, "is", a + b); } // Calling the function add(5, 10); add(3, 8); // Output: // "The sum of 5 and 10 is 15" // "The sum of 3 and 8 is 11"
// Function to check even or odd function checkEvenOdd(num) { if (num % 2 === 0) { console.log(num, "is even."); } else { console.log(num, "is odd."); } } // Calling the function checkEvenOdd(10); checkEvenOdd(7); // Output: // "10 is even." // "7 is odd."
Explanation: Uses % (modulo) operator to check if a number is divisible by 2.
// Function to convert Celsius to Fahrenheit function celsiusToFahrenheit(celsius) { let fahrenheit = (celsius * 9/5) + 32; console.log(celsius, "Celsius is", fahrenheit, "Fahrenheit."); } // Calling the function celsiusToFahrenheit(0); celsiusToFahrenheit(25); // Output: // "0 Celsius is 32 Fahrenheit." // "25 Celsius is 77 Fahrenheit."
Explanation: Uses the formula F = (C * 9/5) + 32 to convert Celsius to Fahrenheit.
A function expression assigns a function to a variable. Unlike function declarations, it cannot be called before its definition.
const multiply = function(a, b) {
console.log("Product:", a * b);
};
multiply(5, 3);
Output: "Product: 15"
Arrow functions provide a shorter syntax for writing functions.
()
in arrow functionsIf the function has a single expression that needs to be returned, you don't need {}
and can write it without return
:
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
This is called implicit return.
const getUser = () => ({ name: "John", age: 30 });
console.log(getUser()); // { name: "John", age: 30 }
{}
in arrow functionsIf the function has multiple lines or you need to write additional logic, you must use {}
and explicitly use return
:
const multiply = (a, b) => {
let result = a * b;
return result;
};
console.log(multiply(2, 3)); // 6
💡 Note: When using {}
, you must explicitly write return
if you want to return a value.
()
for short, single-expression functions (implicit return).{}
when the function body has multiple statements or requires return
.const double = (num) => {
console.log(num, "doubled is", num * 2);
};
double(4);
double(7);
Output:
"4 doubled is 8"
"7 doubled is 14"
function area(length, width) {
return length * width;
}
let result = area(5, 10);
console.log("Area:", result);
Output: "Area: 50"
// Function that returns a greeting message
function getGreeting(name) {
return "Hello, " + name + "!";
}
// Storing and printing the result
let message = getGreeting("Michael");
console.log(message);
// Output: "Hello, Michael!"
Explanation:
function processUserInput(name, callback) {
callback(name);
}
function sayHello(userName) {
console.log("Hello,", userName);
}
processUserInput("Alice", sayHello);
Output: "Hello, Alice"
// Function using setTimeout with callback
setTimeout(() => {
console.log("This message appears after 3 seconds.");
}, 3000);
// Output (after 3 seconds):
// "This message appears after 3 seconds."
Explanation:
A callback function is a function passed as an argument to another function, allowing us to execute code later or under specific conditions.
// Function that processes an array using a callback const numbers = [1, 2, 3, 4, 5]; // Using map with a callback arrow function const squaredNumbers = numbers.map(num => num * num); // Printing the result console.log("Original numbers:", numbers); console.log("Squared numbers:", squaredNumbers); // Output: // "Original numbers: [1, 2, 3, 4, 5]" // "Squared numbers: [1, 4, 9, 16, 25]" // Explanation: // .map() is an array method that applies a function to each element. // The arrow function (num => num * num) takes a number, squares it, and returns the result. // The squaredNumbers array stores the modified values.
const processMessage = (message, callback) => { console.log("Processing message:", message); callback(); }; const displayComplete = () => { console.log("Message processing complete."); }; processMessage("Hello, this is a callback example!", displayComplete); // Output: // "Processing message: Hello, this is a callback example!" // "Message processing complete."
Explanation: The processMessage function accepts a message and a callback function. It prints the message and then executes the callback (displayComplete). The callback function executes only after the message is processed.
const loadData = (callback) => { console.log("Loading data..."); setTimeout(() => { console.log("Data loaded successfully!"); callback(); }, 2000); }; const onComplete = () => { console.log("Load operation complete."); }; loadData(onComplete); // Output: // "Loading data..." // (after 2 seconds) // "Data loaded successfully!" // "Load operation complete."
Explanation: The loadData function simulates loading using setTimeout(). After 2 seconds, it executes the callback function (onComplete). This technique is used in asynchronous operations like API calls.
const filterNumbers = (numbers, callback) => { return numbers.filter(callback); }; const isEven = num => num % 2 === 0; const nums = [10, 15, 22, 33, 40]; const evenNumbers = filterNumbers(nums, isEven); console.log("Original numbers:", nums); console.log("Even numbers:", evenNumbers); // Output: // "Original numbers: [10, 15, 22, 33, 40]" // "Even numbers: [10, 22, 40]"
Explanation: The filterNumbers function accepts an array and a callback function. The callback function (isEven) checks if a number is even. .filter() removes numbers that do not satisfy the condition.
This chapter covered fundamental function concepts that are essential in JavaScript programming!
JavaScript is single-threaded, meaning it executes one task at a time. To handle long-running tasks (e.g., fetching data from a server), JavaScript provides asynchronous programming techniques to prevent blocking execution.
A callback function is executed after another function finishes.
const readFile = (fileName, callback) => { console.log(`Reading file: ${fileName}...`); setTimeout(() => { console.log("File read complete."); callback("File data: Lorem ipsum..."); // Pass file data to callback }, 2000); }; const displayFile = (fileData) => { console.log("Displaying file content:", fileData); }; readFile("document.txt", displayFile); // Output: // Reading file: document.txt... // (after 2 seconds) // File read complete. // Displaying file content: File data: Lorem ipsum...
Explanation: The readFile function simulates reading a file and delays the response using setTimeout(). The callback is called only after the file is read, ensuring we get the correct data.
A Promise is an object representing a value that may be available now, later, or never.
const fetchUserData = (userId) => { return new Promise((resolve, reject) => { console.log(`Fetching user data for ID: ${userId}...`); setTimeout(() => { if (userId === 1) { resolve({ id: 1, name: "Michael", email: "michael@example.com" }); } else { reject("User not found."); } }, 3000); }); }; fetchUserData(1) .then(user => console.log("User data:", user)) // Runs if resolved .catch(error => console.log("Error:", error)); // Runs if rejected // Output (after 3 seconds): // Fetching user data for ID: 1... // User data: { id: 1, name: "Michael", email: "michael@example.com" }
Explanation: fetchUserData() returns a Promise that resolves with user data if the userId is 1. If userId !== 1, the Promise rejects, returning an error message. .then() executes if the Promise resolves successfully, and .catch() handles errors (e.g., user not found).
The async/await syntax makes handling Promises more readable.
const getProduct = async (productId) => { console.log(`Fetching product details for ID: ${productId}...`); return new Promise((resolve, reject) => { setTimeout(() => { if (productId === 100) { resolve({ id: 100, name: "Laptop", price: 1200 }); } else { reject("Product not found."); } }, 2000); }); }; const displayProduct = async () => { try { const product = await getProduct(100); // Waits for the Promise to resolve console.log("Product details:", product); } catch (error) { console.log("Error:", error); // Catches rejection } }; displayProduct(); // Output: // Fetching product details for ID: 100... // (after 2 seconds) // Product details: { id: 100, name: "Laptop", price: 1200 }
Explanation: getProduct() simulates fetching product details using a Promise. await getProduct(100) waits until the Promise resolves or rejects. try...catch handles both successful and failed requests.
Let's simulate fetching data from an API using the Fetch API with async/await.
const fetchPosts = async () => { try { console.log("Fetching posts..."); const response = await fetch("https://jsonplaceholder.typicode.com/posts"); // Fetch data const posts = await response.json(); // Convert response to JSON console.log("Posts fetched successfully:", posts.slice(0, 2)); // Display first 2 posts } catch (error) { console.log("Error fetching posts:", error); } }; fetchPosts(); // Output (Example): // Fetching posts... // Posts fetched successfully: [{ id: 1, title: "Post 1", body: "Lorem ipsum..." }, { id: 2, title: "Post 2", body: "Lorem ipsum..." }]
Explanation: fetch() sends a network request to fetch posts. await response.json() parses the response into a JavaScript object. If successful, the first two posts are displayed.
Mastering asynchronous programming is crucial for handling real-world JavaScript applications!
Events are actions that happen in the browser, such as user interactions or system-generated actions. JavaScript allows us to handle events and execute code in response to them.
An event is a user interaction or system-triggered action that JavaScript can respond to. Examples of events include:
Event listeners are functions that wait for an event to occur and execute a callback when the event happens.
// Function to display a message when the button is clicked const handleClick = () => { console.log("Button clicked!"); }; // Adding event listener for a click event document.getElementById("myButton").addEventListener("click", handleClick); Explanation: • getElementById("myButton"): This selects the button by its ID. • .addEventListener("click", handleClick): Adds an event listener to the button for the click event. • When the button is clicked, the handleClick function is executed, which prints "Button clicked!".
JavaScript supports many types of events that correspond to user interactions and browser behaviors. Common event types include:
// Function to handle key press event // const handleKeyPress = (event) => { // console.log("Key pressed:", event.key); // Displays the key that was pressed // }; // Adding event listener for the 'keydown' event // document.addEventListener("keydown", handleKeyPress); // Explanation: // • event.key: Accesses the specific key pressed on the keyboard. // • The handleKeyPress function is executed whenever a key is pressed, printing the key to the console.
When an event is triggered, the browser passes an event object to the event handler. This object contains useful information about the event, such as the target element and the type of event.
// Function to handle click event and display event details // const handleClick = (event) => { // console.log("Event Type:", event.type); // Displays the event type (e.g., "click") // console.log("Clicked Element:", event.target); // Displays the element that was clicked // }; // Adding event listener for click event // document.getElementById("myButton").addEventListener("click", handleClick); // Explanation: // • event.type: Displays the type of the event (e.g., click). // • event.target: Refers to the HTML element that triggered the event (the button in this case).
// Parent element click handler // const handleParentClick = () => { // console.log("Parent clicked!"); // }; // Child element click handler // const handleChildClick = (event) => { // console.log("Child clicked!"); // // Stopping event propagation (bubbling) // event.stopPropagation(); // }; // Adding event listeners // document.getElementById("parent").addEventListener("click", handleParentClick); // document.getElementById("child").addEventListener("click", handleChildClick); // Explanation: // • Event Bubbling: If you click the child element, both the child and parent elements will trigger their click handlers. // • event.stopPropagation() stops the event from bubbling to the parent element. The child click handler will be executed, but the parent will not be triggered.
Some events have default behaviors, such as form submissions or anchor tag navigation. You can prevent
this default behavior using event.preventDefault()
.
// Function to handle form submission and prevent default behavior const handleSubmit = (event) => { event.preventDefault(); // Prevent the form from submitting console.log("Form submission prevented!"); }; Adding event listener for form submit event document.getElementById("myForm").addEventListener("submit", handleSubmit); Explanation: • event.preventDefault() stops the form from submitting when the user clicks the submit button. • This is useful for validating form data before submission.
Object-Oriented Programming (OOP) is a paradigm that organizes code into objects, which contain properties (data) and methods (functions) to manipulate that data. JavaScript supports OOP using prototypes and classes.
Objects store key-value pairs and allow us to group related data and functions.
// Defining an object using object literal syntax const person = { name: "Michael", // Property: name age: 30, // Property: age greet: function() { // Method: greet() return `Hello, my name is ${this.name}.`; } }; // Accessing properties and calling a method console.log(person.name); // Output: Michael console.log(person.age); // Output: 30 console.log(person.greet()); // Output: Hello, my name is Michael.
person
is an object with properties (name
, age
) and a method (greet
).this
keyword refers to the current object.person.name
).person.greet()
).// Adding a new property dynamically person.job = "Software Developer"; // Removing a property delete person.age; console.log(person); // Output: { name: 'Michael', greet: [Function: greet], job: 'Software Developer' }
person.job
.delete
.A constructor function is a blueprint for creating multiple objects.
// Constructor function for a Car object function Car(brand, model, year) { this.brand = brand; // Assigning parameters to object properties this.model = model; this.year = year; this.getDetails = function() { return `${this.brand} ${this.model} (${this.year})`; }; } // Creating instances of Car const car1 = new Car("Toyota", "Corolla", 2022); const car2 = new Car("Honda", "Civic", 2023); console.log(car1.getDetails()); // Output: Toyota Corolla (2022) console.log(car2.getDetails()); // Output: Honda Civic (2023)
Car
is a constructor function that initializes a new object with brand
, model
, and year
.new Car(...)
creates new instances.getDetails()
returns a formatted string.In JavaScript, objects inherit properties and methods from their prototype.
// Constructor function function Person(name, age) { this.name = name; this.age = age; } // Adding a method using prototype Person.prototype.sayHello = function() { return `Hi, I'm ${this.name} and I'm ${this.age} years old.`; }; const person1 = new Person("Alice", 25); const person2 = new Person("Bob", 28); console.log(person1.sayHello()); // Output: Hi, I'm Alice and I'm 25 years old. console.log(person2.sayHello()); // Output: Hi, I'm Bob and I'm 28 years old.
Person.prototype
are shared across all instances.sayHello()
is available to all Person
objects.ES6 introduced the class
keyword for a cleaner syntax.
// Defining a class class Animal { constructor(name, species) { this.name = name; this.species = species; } makeSound() { return `${this.name} makes a sound.`; } } // Creating instances const dog = new Animal("Buddy", "Dog"); const cat = new Animal("Whiskers", "Cat"); console.log(dog.makeSound()); // Output: Buddy makes a sound. console.log(cat.makeSound()); // Output: Whiskers makes a sound.
class Animal
defines a blueprint with a constructor.makeSound()
).new
.