JavaScript is a programming language commonly used for web development. It allows you to add interactivity and dynamic behavior to your web pages.
In this tutorial, we will cover the basics of JavaScript, including variables, data types, control flow, functions, DOM manipulation, asynchronous programming, and more. By the end of the tutorial, you will have a solid understanding of JavaScript and be able to build interactive web applications.
To use JavaScript in your web pages, you can include a<script>
element within the HTML<head>
section or at the end of the<body>
element.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
<!-- JavaScript code goes here -->
</script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
The assignment operator (=) is used to assign a value to a variable:
var x = 5; // Assigning a value to a variable
Comparison expressions compare values and return a boolean result (true or false). Here are some examples:
JavaScript supports various comparison operators:
Equal to (==): checks if two values are equal
5 == 5; // true
Not equal to (!=): checks if two values are not equal
5 != 3; // true
Strict equal to (===):
checks if two values are equal and have the same type
5 === "5";// false
Strict not equal to (!==):
checks if two values are not equal or do not have the same type
5 !== "5";// true
Greater than (>):
checks if the first value is greater than the second
5 > 3; // true
Less than (<):
checks if the first value is less than the second
5 < 3; // false
Greater than or equal to (>=):
checks if the first value is greater than or equal to the second
5 >= 5; // true
Less than or equal to (<=):
checks if the first value is less than or equal to the second
5 <= 3; // false
JavaScript includes several logical operators:
Logical AND (&&): returns true if both operands are true
(5 > 3) && (10 < 20); // true
Logical OR (||): returns true if at least one operand is true
(5 > 10) || (3 > 1); // true
Logical NOT (!): inverts the logical state of an operand
!(5 > 3); // false
The conditional operator is a shorthand way to write an if-else statement:
var age = 18;
// If age is greater than or equal to 18, assign "Yes" to canVote, otherwise assign "No"
var canVote = (age >= 18) ? "Yes" : "No";
JavaScript provides arithmetic operators for mathematical calculations:
Addition (+): adds two values
5 + 3; // 8
Subtraction (-): subtracts the second value from the first
5 - 3; // 2
Multiplication (*): multiplies two values
5 * 3; // 15
Division (/): divides the first value by the second
15 / 3; // 5
Modulus (%): returns the remainder after division
5 % 3; // 2
Increment (++): increases the value of a variable by 1
var x = 5; x++; // x becomes 6
Decrement (--): decreases the value of a variable by 1
var y = 5; y--; // y becomes 4
The string concatenation operator (+) is used to concatenate strings:
var firstName = "John";
var lastName = "Doe";
var fullName = firstName + " " + lastName; // Concatenates the two strings
The typeof operator is used to determine the data type of a variable:
var x = 5;
typeof x; // "number"
The if statement is used to perform a certain block of code if a specified condition is true. Here's an example:
let num = 5;
if (num > 0) {
console.log("Number is positive");
}
The switch statement is used to select one of many code blocks to be executed. It evaluates an expression and matches the expression's value to a case clause. Here's an example:
let day = "Monday";
switch (day) {
case "Monday":
console.log("It's Monday");
break;
case "Tuesday":
console.log("It's Tuesday");
break;
default:
console.log("It's another day");
}
The while loop is used to execute a block of code as long as a specified condition is true. Here's an example:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
The do-while loop is similar to the while loop, but it executes the block of code at least once before checking the condition. Here's an example:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
The break statement is used to exit a loop or switch statement. It terminates the current loop and transfers control to the next statement outside the loop. Here's an example:
for (let i = 0; i < 5; i++) {
if (i === 3) {
break;
}
console.log(i);
}
The continue statement is used to skip the current iteration of a loop and continue with the next iteration. Here's an example:
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue;
}
console.log(i);
}
The for loop is used to execute a block of code a specified number of times. Here's an example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
The for...in loop is used to iterate over the properties of an object. Here's an example:
const person = {
name: "John",
age: 30,
occupation: "Developer"
};
for (let key in person) {
console.log(key + : +person[key] );
}
The for...of loop is used to iterate over the elements of an iterable object, such as an array or a string. Here's an example:
const numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number);
}
The forEach loop is a method available for arrays in JavaScript. It allows you to iterate over each element of the array and perform a specified action. Here's an example:
const fruits = ["apple","banana","orange"];
fruits.forEach((fruit) => {
console.log(fruit);
});
Functions in JavaScript allow you to group and reuse blocks of code.
You can declare a function using the function
keyword:
function greet() {
console.log('Hello, world!');
}
You can call a function by using its name followed by parentheses:
greet();
Functions can accept parameters, which are values passed to the function:
function greet(name) {
console.log('Hello, ' + name + '!');
}
greet('John');
Functions can return a value using the return
statement:
function add(a, b) {
return a + b;
}
const result = add(3, 5);
console.log(result); // Output: 8
Scope determines the accessibility and lifetime of variables and functions.
Variables declared outside of any function have global scope and can be accessed anywhere in the code:
const globalVariable = 'I am global';
function printGlobal() {
console.log(globalVariable);
}printGlobal(); // Output: I am global
Variables declared inside a function have local scope and can only be accessed within that function:
function printLocal() {
const localVariable = 'I am local';
console.log(localVariable);
}printLocal(); // Output: I am local
console.log(localVariable); // Throws an error: localVariable is not defined
Variables declared with let
and const
have block scope and are only accessible within the block they are defined in:
function printBlock() {
if (true) {
let blockVariable = 'I am inside a block';
console.log(blockVariable);
}
console.log(blockVariable); // Throws an error: blockVariable is not defined
}printBlock(); // Output: I am inside a block
Each function creates its own scope, and variables declared inside a function are only accessible within that function:
function outerFunction() {
const outerVariable = 'I am outer';
function innerFunction() {
const innerVariable = 'I am inner';
console.log(innerVariable);
console.log(outerVariable);
}
innerFunction(); // Output: I am inner, I am outer
console.log(innerVariable); // Throws an error: innerVariable is not defined
}outerFunction();
Arrays are used to store multiple values in a single variable. You can perform various operations on arrays, such as accessing elements, adding or removing elements, and manipulating the array:
const numbers = [1,2,3,4,5];
const fruits = ['apple','banana','orange'];
const numbers = [1,2,3,4,5];console.log(numbers[0] ); // Output: 1
const fruits = ['apple','banana','orange'];console.log(fruits[1] ); // Output: banana
JavaScript provides several built-in methods to work with arrays:
Removing elements using shift:
const numbers = [1,2,3,4,5];
// Removing elements
numbers.shift(); // Removes the first element /* Output: [2, 3, 4, 5] */
Removing elements using pop:
const numbers = [1,2,3,4,5];
// Removing elements
numbers.pop(); // Removes the last element /* Output: [1, 2, 3, 4] */
Manipulating the array using splice:
const numbers = [1,2,3,4,5];
// splice(startIndex, deleteCount, InsertValue)
splice(1, 2, 3) would remove 2 elements stqring from index 1 and insert 3 at index 11
numbers.splice(1, 2); /* Output: [1, 4, 5] */
numbers.splice(1, 2, 3); /* Output: [1, 6, 4, 5] */
Reversing the order of elements:
const numbers = [1,2,3,4,5];
// Reversing the order of elements
numbers.reverse(); /* Output: [5, 4, 3, 2, 1] */
Sorting the array:
const numbers = [5,2,3,1,4];
numbers.sort(); /* Output: [1, 2, 3, 4, 5] */
Getting the length of the array:
const numbers = [1,2,3,4,5];
numbers.length; /* Output: 5 */
Finding the index of an element:
const numbers = [1,2,3,4,5];
numbers.indexOf(3); /* Output: 2 */
Checking if an element exists in the array:
const numbers = [1,2,3,4,5];
numbers.includes(4); /* Output: true */
Slicing a portion of an array:
const numbers = [1,2,3,4,5];
numbers.slice(1, 3); /* Output: [2, 3, 4] */
Filtering elements based on a condition:
const numbers = [1,2,3,4,5];
numbers.filter(num => num % 2 === 0); /* Output: [2, 4] */
Mapping over elements and applying a function:
const numbers = [1,2,3,4,5];
numbers.map(num => num * 2); /* Output: [2, 4, 6, 8, 10] */
Iterating over elements and executing a function:
const numbers = [1,2,3,4,5];
numbers.forEach(num => console.log(num) ); /* Output: 1, 2, 3, 4, 5 */
Joining elements of an array into a string:
const numbers = [1,2,3,4,5];
numbers.join(', '); /* Output: "1, 2, 3, 4, 5" */
Adding elements using unshift:
const numbers = [2,3,4,5];
numbers.unshift(1); /* Output: [1, 2, 3, 4, 5] */
Objects are used to store collections of key-value pairs. You can create objects, access object properties, and manipulate the object:
Defining a person object:
const person = {
name: 'John Doe',
age: 30,
address: '123 Main St'
};
Accessing properties of the person object:
const person = {
name: 'John Doe',
age: 30,
address: '123 Main St'
};
console.log(person.name); // Output: John Doe
console.log(person['age']); // Output: 30
Manipulating properties of the person object:
const person = {
name: 'John Doe',
age: 30,
address: '123 Main St'
};
person.age = 35; // Modifies the value of age
person.job = 'Developer'; // Adds a new property
delete person.address; // Removes the address property
Objects can also have methods, which are functions defined as object properties:
const person = {
name: 'John Doe',
age: 30,
greet: function() {
return `Hello, my name is ${person.name} and I am ${person.age} years old.`;
}
};
console.log(person.greet() ); /* Output: Hello, my name is John Doe and I am 30 years old. */
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a document as a tree of objects that can be accessed and manipulated using JavaScript. With the DOM, you can dynamically modify the content, structure, and styles of a web page.
To select elements from the DOM, you can use various methods such asgetElementById
, querySelector
, querySelectorAll
, and more. Here are some examples:
// Select an element by its ID
const elementById = document.getElementById("myElement");
// Select the first element that matches a CSS selector
const element = document.querySelector(".myClass");
// Select all elements that match a CSS selector
const elements = document.querySelectorAll("p");
Once you have selected an element, you can manipulate its properties, attributes, and content using JavaScript. Here are some common operations:
/* Change the text content of an element */
element.textContent = "New text";
/* Change the HTML content of an element */
element.innerHTML = "Updated content";
/* Change the value of an input element */
inputElement.value = "New value";
/* Add a CSS class to an element */
element.classList.add("newClass");
/* Remove a CSS class from an element */
element.classList.remove("oldClass");
/* Toggle a CSS class on an element */
element.classList.toggle("active");
Events are actions or occurrences that happen in the browser, such as a button click, mouse movement, or key press. You can handle events by attaching event listeners to elements. Here's an example of attaching a click event listener to a button:
/* Create a reference to a button element */
const button = document.getElementById("myButton");
/* Define a function to handle click events */
function handleClick(event) /* Handle the click event here */
/* Add an event listener to the button */
button.addEventListener("click", handleClick );
In this example, when the button is clicked, the handleClick
function will be called.
You can also remove an event listener using the removeEventListener
method:
/* Remove an event listener from the button */
button.removeEventListener("click",handleClick);
Event listeners can be attached to various events such as "click", "mouseover", "keydown", "keyup", "keypress", "change", "input", "focus", "blur", "submit", "scroll", and many more. Additionally, you can use event delegation to handle events on multiple elements efficiently:
/* Add event listener to the parent element */
parentElement.addEventListener("click",function(event) {
/* Check if the clicked element has a class "child" */
if (event.target.classList.contains("child") {
/* Handle the click event on child elements */
}});
Event | Explanation |
---|---|
click | Triggered when a mouse click is detected. |
mouseover | Fired when the mouse pointer enters an element. |
keydown | Fired when a key is pressed down. |
keyup | Fired when a key is released. |
keypress | Fired when a key is pressed down and then released. |
change | Fired when the value of an input element changes. |
input | Fired when the value of an input element is changed by the user. |
focus | Fired when an element receives focus. |
blur | Fired when an element loses focus. |
submit | Fired when a form is submitted. |
scroll | Fired when the user scrolls the page. |
By using event delegation, you attach a single event listener to a parent element and handle events for its child elements.
Remember to access and manipulate elements within the appropriate scope, ensuring that the DOM is fully loaded before accessing elements using the DOMContentLoaded
event or placing the script at the bottom of the HTML file.
You can modify the styles of elements using JavaScript. The style
property allows you to access and modify inline styles directly. Here's an example:
/* Select an element by its ID */
const element = document.getElementById("myElement");
/* Modify styles directly */
element.style.color = "red";
element.style.fontSize = "20px";
Alternatively, you can add or remove CSS classes to apply predefined styles or toggle specific styles. This approach is more flexible and recommended when working with complex style changes or multiple elements. Here's an example:
/* Modify classes */
const element = document.getElementById("myElement");
/* Add a CSS class */
element.classList.add("highlight");
/* Remove a CSS class */
element.classList.remove("highlight");
/* Toggle a CSS class */
element.classList.toggle("active");
You can create new elements dynamically and add them to the DOM using JavaScript. The createElement
method creates a new element, and you can modify its properties and content before appending it to the document. Here's an example:
/* Create a new element */
const newElement = document.createElement("div");
newElement.textContent = "New element content";
newElement.classList.add("customClass");
/* Append the new element */
const container = document.getElementById("container");
container.appendChild(newElement);
You can also modify existing elements by changing their attributes or content. Here are a few examples:
/* Modify element content */
element.textContent = "Updated content";
/* Change an attribute */
element.setAttribute("src", "new-image.jpg");
/* Remove an attribute */
element.removeAttribute("disabled");
When working with events, it's essential to understand event propagation and the event object. Event propagation refers to how events propagate through the DOM hierarchy, and it can be either capturing or bubbling. The event object contains information about the event and provides methods and properties to interact with it. Here's an example:
/* Preventing default behavior */
const container = document.getElementById("container");
const button = document.getElementById("myButton");
/* Function to handle click event */
function handleClick(event) {
/* Preventing default behavior */
event.preventDefault();
/* Stopping event propagation */
event.stopPropagation();
/* Accessing event properties */
console.log(event.target); /* Element that triggered the event */
console.log(event.type); /* Type of event (e.g., "click", "mouseover") */
}
/* Adding event listeners */
container.addEventListener("click", handleClick);
button.addEventListener("click", handleClick);
In this example, the preventDefault
method prevents the default behavior of the event (e.g., preventing a form submission). The stopPropagation
method stops the event from propagating further in the DOM hierarchy, preventing it from triggering other event listeners.
These are just a few examples of the many possibilities offered by the DOM API for element manipulation, style modification, creating new elements, and working with events and event objects.
That covers more relevant utilizations of DOM manipulation. Feel free to explore the DOM API documentation for further details and examples.Functions are a fundamental concept in JavaScript that allow you to encapsulate reusable blocks of code. They can be defined and invoked, accept parameters, and return values. In addition, JavaScript supports callback functions and higher-order functions, which provide powerful ways to work with functions.
In JavaScript, you can define a function using the function
keyword followed by the function name, a list of parameters (optional), and the function body enclosed in curly braces. Here's an example:
function sayHello () {
console.log("Hello!");
}
// Invoke the function
sayHello();
In this example, the function sayHello
is defined without any parameters. The function body contains the code that will be executed when the function is invoked. To invoke a function, you simply write its name followed by parentheses.
Functions can accept parameters, which are values passed to the function when it's invoked. Parameters allow you to provide dynamic input to a function. Here's an example:
function greet (name) {
console.log("Hello, " + name + "!");
}
// Invoke the function with a parameter
greet("John");
In this example, the function greet
accepts a name
parameter. When the function is invoked with the value "John," it will print "Hello, John!" to the console. Parameters allow functions to work with different values without having to rewrite the function logic.
Functions can also return values using the return
keyword. The returned value can be used by the code that invoked the function. Here's an example:
function add (a, b) {
return a + b;
}
// Invoke the function and store the result
const sum = add(2, 3);
// Output: 5
console.log(sum);
In this example, the function add
takes two parameters a
and b
. It returns the sum of the two numbers. The returned value is stored in the sum
variable and then printed to the console.
In JavaScript, functions are first-class objects, which means they can be assigned to variables, passed as arguments to other functions, and returned as values from other functions. This enables the use of callback functions and higher-order functions.
A callback function is a function that is passed as an argument to another function and is invoked inside that function. Callback functions are commonly used for asynchronous operations, event handling, and more. Here's an example:
function greet(name, callback) {
console.log("Hello, " + name + "!");
callback();
}
function sayGoodbye() {
console.log("Goodbye!");
}
// Invoke the function with a callback
const sum = add(2, 3);
// Output: 5
console.log(sum);
In this example, the function greet
accepts a name
parameter and a callback
parameter. After greeting the person, it invokes the callback
function, which, in this case, is sayGoodbye
. The output will be "Hello, John!" followed by "Goodbye!".
Higher-order functions are functions that can accept other functions as arguments and/or return functions. They provide a way to abstract and manipulate code behavior. Common examples of higher-order functions in JavaScript are map
, filter
, and reduce
. Here's an example using map
:
const numbers = [1, 2, 3, 4, 5];
function double(number) {
return number * 2;
}
const doubledNumbers = numbers.map(double);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
In this example, the map
function is a higher-order function that accepts the double
function as an argument. It applies the double
function to each element in the numbers
array and returns a new array with the doubled values.
Understanding and utilizing functions, along with callback functions and higher-order functions, is essential for writing modular and reusable code in JavaScript.
ES6+ (ECMAScript 6 and later versions) introduced several powerful features that enhance JavaScript functionality and make code more concise and expressive. Let's explore some of these features.
Arrow functions provide a concise syntax for writing functions. They capture the lexical scope of the surrounding code, which means they inherit the context in which they are defined. Here's an example:
const greet = (name) => {
console.log("Hello, " + name);
};
greet("John"); // Output: Hello, John
Destructuring allows you to extract values from arrays or objects into individual variables. It provides a convenient way to access and use specific values. Object shorthand notation simplifies object creation by directly using variable names as object properties. Here's an example of both features:
// Array Destructuring
const [x, y] = [1, 2];
console.log(x, y); // Output: 1 2
// Object Shorthand
const name = "John";
const age = 30;
const person = { name, age };
console.log(person); // Output: { name: "John", age: 30 }
Modules allow you to organize and separate code into reusable components. You can use the import
and export
keywords to define dependencies between modules and share functionality across files. Here's an example:
// File: module.js
export const greeting = "Hello, world!";
// File: main.js
import { greeting } from "./module.js";
console.log(greeting); // Output: Hello, world!
Classes provide a way to define objects with shared properties and methods. You can create class instances using the new
keyword. Classes also support inheritance through the extends
keyword, allowing you to create subclasses that inherit from a base class. Here's an example:
class Shape { constructor(color) { this.color = color; } getColor() { return this.color; } }
class Square extends Shape { constructor(color, side) { super(color); this.side = side; } getArea() { return this.side ** 2; } }
const square = new Square("red", 5);console.log(square.getColor()); // Output: red
console.log(square.getArea()); // Output: 25
These are just a few examples of the powerful features introduced in ES6+. They contribute to writing more concise and readable code, improving developer productivity and code maintainability.
APIs (Application Programming Interfaces) allow applications to interact and exchange data with external systems. JavaScript provides various techniques to work with APIs effectively. Let's explore some of these techniques.
JavaScript provides several methods to make HTTP requests to retrieve data from APIs. The most commonly used methods are fetch
andAxios
. Here's an example using the fetch
method:
// GET request
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => {
// Handle the retrieved data
}).catch((error) => {
// Handle any errors
});
// POST request
fetch("https://api.example.com/data",{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ key: "value" }),
}).then((response) => response.json()).then((data) => {
// Handle the response data
}).catch((error) => {
// Handle any errors
});
In the example above, a GET request is made to retrieve data, while a POST request is made to send data to the API. The POST request includes the request method, headers, and body with JSON data.
Alternatively, you can also use async/await
to handle HTTP requests without using then
. Here's an example using async/await
with fetch
:
async function fetchData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
// Handle the retrieved data
} catch (error) {
// Handle any errors
}
fetchData();
The fetchData
function is declared as async
, and the await
keyword is used to wait for the response and data. Any errors are caught and handled using try/catch
.
Third-party APIs offer a wide range of services and data that you can integrate into your applications. To use a third-party API, you typically need an API key or access token, which you include in your requests. Here's an example of making a request to a weather API:
fetch("https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London")
.then((response) => response.json()).then((data) => {
// Handle the weather data
}).catch((error) => {
// Handle any errors
});
When using third-party APIs, make sure to read their documentation for details on authentication, request parameters, and response formats.
Cookies are small pieces of data stored on a user's browser. They are commonly used for session management, user tracking, and storing user preferences. In JavaScript, you can use the `document.cookie` API to read, write, and delete cookies. Here's an example of setting a cookie:
document.cookie = "name=value; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";
In the example above, a cookie named "name" is set with the value "value". The cookie is set to expire on December 31, 2023, and is accessible from the entire website ("/").
Local Storage and Session Storage are web storage APIs that allow you to store key-value pairs on the client-side. The main difference between them is that Local Storage data persists even after the browser is closed, while Session Storage data is cleared when the browser session ends. Here's an example of using Local Storage:
// Storing data in Local Storage
localStorage.setItem("key", "value");
// Retrieving data from Local Storage
const value = localStorage.getItem("key");
// Removing data from Local Storage
localStorage.removeItem("key");
// Clearing all data from Local Storage
localStorage.clear();
Session Storage can be used in a similar way, but you replace "localStorage" with "sessionStorage".
IndexedDB is a more powerful client-side storage solution that allows you to store structured data, query it, and perform complex operations. It provides an asynchronous API for working with databases. Here's an example of using IndexedDB to store and retrieve data:
// Opening a database
const request = indexedDB.open('yourDatabaseName', versionNumber);
/* Replace 'yourDatabaseName' with the desired name for your database */
/* and versionNumber with the version number (integer) of the database. */
/* This will open a connection or create a new database if it doesn't already exist. */
const request = indexedDB.open("myDatabase", 1);
// Creating object stores and indexes
request.onupgradeneeded = function(event) => {
const db = event.target.result;
const objectStore = db.objectStore("myObjectStore", { keyPath: "id" });
objectStore.createIndex("name", "name", { unique: false });
};
// Storing data
request.onsuccess = function(event) => {
const db = event. target.result;
const transaction = db.transaction("myObjectStore", "readwrite");
const objectStore = transaction.objectStore("myObjectStore");
const data = { id: 1, name: "John" };
const request = objectStore.add(data);
};
// Retrieving data
request.onsuccess = function(event) => {
const db = event.target.result;
const transaction = db.transaction("myObjectStore", "readonly");
const objectStore = transaction. objectStore("myObjectStore");
const request =objectStore.get(1);
request.onsuccess = function(event) => {
const data = event.target.result;
console.log(data);
};
};
// Deleting data
request.onsuccess = function(event) => {
& nbsp;const db = event. target.result;
const transaction = db.transaction("myObjectStore", "readwrite");
const objectStore = transaction.objectStore("myObjectStore");
const request = objectStore.delete(1);
};
In the example above, an IndexedDB database named "myDatabase" is opened. Object stores and indexes are created, and then data is stored, retrieved, and deleted from the database using transactions and requests.
HTML forms are used to collect user input. JavaScript can be used to validate form data before submission. You can listen for the form's submit event and prevent the default form submission if the input is invalid. Here's an example of form validation and submission handling:
const form = document.querySelector("#myForm");
form.addEventListener("submit",function(event) {
event.preventDefault(); /* Prevent default form submission */
if (formIsValid(}) {
form.submit(); /* Submit the form */
} else {
const errorMessage = document.querySelector("#errorMessage");
errorMessage.textContent = "Please fill out all required fields.";
}
});
function formIsValid() {
// Get form input values
const nameInput = document.querySelector("#nameInput");
const emailInput = document.querySelector("#emailInput");
// Perform basic validation
if (nameInput.value.trim() === "" || emailInput.value.trim() === "") {
return false;
}
return true;
}
In the example above, the form's submit event is listened for, and the default submission is prevented using `event.preventDefault()`. The `formIsValid()` function is called to perform basic form validation. If the form is valid (in this case, if both the name and email fields are filled out), the form's `submit()` method is called to submit the form. Otherwise, an error message is displayed.
JavaScript provides various events that can be used to handle form interactions. Some common form events include `input` (fired when the value of an input element changes), `change` (fired when the value of a form element changes and loses focus), and `submit` (fired when the form is submitted). Here's an example of handling the `input` event on an input field:
const emailInput = document.querySelector("#emailInput");
emailInput.addEventListener("input",function(event) {
const inputValue = event.target.value;
// Perform actions based on the input value
if (inputValue.length > 0 && !isValidEmail(inputValue)) {
event.target.classList.add("error");
showErrorMessage("Please enter a valid email address.");
} else {
event.target.classList.remove("error");
hideErrorMessage();
}
});
function isValidEmail(email) {
// Basic email validation using regular expression
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(email);
}
function showErrorMessage(message) {
const errorMessage. = document.querySelector("#errorMessage");
errorMessage..textContent = message;
errorMessage..style.display = "block";
}
function hideErrorMessage() {
const errorMessage. = document.querySelector("#errorMessage");
errorMessage.style.display ="none";
}
In this example, the `input` event is used to handle changes in the email input field. When the input value changes, the `isValidEmail()` function is called to perform basic email validation using a regular expression. If the input value is not a valid email address, an error style is applied to the input field, and an error message is displayed. Otherwise, the error style is removed, and the error message is hidden.
JavaScript provides various methods to access and manipulate form data. You can use the `querySelector` method to select form elements and retrieve their values. Here's an example:
const form = document.querySelector("#myForm");
form.addEventListener("submit",function(event) {
event.preventDefault();
// Get form data
const nameInput = form.querySelector("#nameInput");
const emailInput = form.querySelector("#emailInput");
// Access and manipulate form data
const name = nameInput.value;
const email = emailInput.value;
// Perform actions with form data
console.log("Name:", name);
console.log("Email:", email);
});
function isValidEmail(email) {
// Basic email validation using regular expression
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(email);
}
function showErrorMessage(message) {
const errorMessage = document.querySelector("#errorMessage");
errorMessage.textContent = message;
errorMessage.style.display = "block";
}
function hideErrorMessage() {
const errorMessage = document.querySelector("#errorMessage");
errorMessage.style.display = "none";
}
In this example, the `querySelector` method is used to select the form and its input fields. The `value` property is used to access the input fields' values. The form data can then be accessed and manipulated as needed. In this case, the form data is logged to the console.
Regular expressions, also known as regex, are powerful tools for pattern matching and text manipulation. They allow you to define specific patterns and perform operations on strings. One common use case is validating user input, such as an email address or phone number. Let's take a look at an example of using a regular expression for email validation:
const email = "example@example.com";
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (emailRegex.test(email)) {
console.log("Valid email address");
} else {
console.log("Invalid email address");
}
In this example, we define a regular expression pattern /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/ for email validation. Let's break it down:
Pattern | Explanation |
---|---|
^ | Matches the beginning of the string. |
[a-zA-Z0-9._%+-] | Matches any alphanumeric character, period (.), underscore (_), percent (%), plus (+), or hyphen (-). |
+ | Matches one or more occurrences of the preceding pattern. |
@ | Matches the "@" symbol literally. |
[a-zA-Z0-9.-] | Matches any alphanumeric character, period (.), or hyphen (-). |
\. | Matches the dot (.) symbol literally. We use a backslash (\) to escape the dot and treat it as a literal character. |
[a-zA-Z]{2,} | Matches any alphabetical character (case-insensitive) repeated two or more times. |
$ | Matches the end of the string. |
By using the test()
method with the regular expression, we can check if an email address matches the defined pattern. If the email passes the test, it is considered valid; otherwise, it is considered invalid.
Here is another example, extracting Phone Numbers:
Regular expressions can also be used to extract specific information from strings. Here's an example of how to extract phone numbers from a string using a regular expression in JavaScript
const text = 'Contact us at 123-456-7890 or 987-654-3210.';
const phoneRegex = /\d3-\d3-\d4/g;
const phoneNumbers = text.match(phoneRegex);
console.log(phoneNumbers);
In this example, the phoneRegex regular expression pattern \d3-\d3-\d4 is used to match phone numbers in the format of three digits, followed by a hyphen, three more digits, another hyphen, and finally four digits. The match() function is used to extract all occurrences of phone numbers from the text variable and store them in the phoneNumbers array.
When you run this code, it will output an array containing the phone numbers found in the text: ['123-456-7890', '987-654-3210'].
Regular expressions consist of patterns and optional modifiers. Here are some commonly used patterns and modifiers:
Pattern | Explanation |
---|---|
^ | Matches the beginning of a string. |
$ | Matches the end of a string. |
[abc] | Matches any character within the brackets. |
[^abc] | Matches any character not within the brackets. |
\d | Matches any digit. |
\w | Matches any word character (alphanumeric and underscore). |
\s | Matches any whitespace character. |
* | Matches zero or more occurrences of the preceding pattern. |
+ | Matches one or more occurrences of the preceding pattern. |
? | Matches zero or one occurrence of the preceding pattern. |
These are just a few examples of the patterns and modifiers you can use in regular expressions. Regular expressions can become more complex and powerful, allowing you to create intricate search patterns and perform advanced string operations. As a beginner, it's helpful to refer to regular expression resources and practice with simpler patterns before diving into more advanced ones.