JavaScript is a powerful, versatile language used for adding interactivity to websites. If you're just starting with web development, JavaScript is an essential tool in your toolkit. In this post, we’ll cover the basics of JavaScript, including how to add JavaScript to your HTML, basic syntax, variables, data types, functions, and event handling.
1. Adding JavaScript to Your HTML
You can add JavaScript directly into your HTML file. The simplest way is by using the <script>
tag.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Basics</title>
</head>
<body>
<h1>Hello, World!</h1>
<script>
alert("Welcome to JavaScript!");
</script>
</body>
</html>
In this example, the alert()
function will display a pop-up message saying "Welcome to JavaScript!" as soon as the page loads. This method is great for testing simple scripts, but for larger projects, it’s better to link an external JavaScript file.
2. Variables and Data Types
Variables store information that can be used later in the program. In JavaScript, you can declare variables using let
, const
, or var
.
Example: Declaring Variables
let name = "Alice"; // A string
const age = 25; // A number
var isStudent = true; // A boolean
Explanation:
let
allows you to reassign the variable later, while const
is used for values that shouldn’t change.var
is an older way of declaring variables but is still used. Generally, use let
and const
in modern JavaScript.
Data Types
JavaScript supports several data types:
- String: Text data, e.g.,
"Hello"
- Number: Numeric data, e.g.,
10
- Boolean: True or false, e.g.,
true
- Array: A list of items, e.g.,
[1, 2, 3]
- Object: A collection of key-value pairs, e.g.,
{ name: "Alice", age: 25 }
3. Basic Operations
You can perform operations like addition, subtraction, and concatenation.
let x = 5;
let y = 10;
let sum = x + y; // 15
let greeting = "Hello" + " " + "World"; // "Hello World"
4. Functions
Functions allow you to define reusable code blocks.
Example: Basic Function
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Output: Hello, Alice!
Explanation:
function
declares a function.- Functions can take parameters (like
name
in this example) and return values.
5. Conditional Statements
Conditions allow you to make decisions in your code.
Example: If-Else Statement
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
6.Looping Statement
JavaScript provides several types of looping statements, which allow you to execute code multiple times. Here are the main looping statements:
1. for Loopfor (let i = 0; i < 5; i++) {
console.log("Iteration:", i);
}
2.while loop
let i = 0;
while (i < 5) {
console.log("Iteration:", i);
i++;
}
3.do while loop
let i = 0;
do {
console.log("Iteration:", i);
i++;
} while (i < 5);
4. for...of Looplet numbers = [10, 20, 30];for (let number of numbers) {
console.log(number);
}
5. for...in Loop
let person = { name: "Alice", age: 25 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
7. Event Handling
JavaScript is often used to handle events like clicks or key presses.
Example: Button Click Event
<!DOCTYPE html>
<html>
<body>
<button onclick="showMessage()">Click Me</button>
<script>
function showMessage() {
alert("Button was clicked!");
}
</script>
</body>
</html>
In this example, clicking the button triggers the showMessage()
function, which shows an alert.
Example: Adding two Numbers
<!DOCTYPE html>
<html>
<head>
<title>Add Two Numbers</title>
</head>
<body>
<h1>Add Two Numbers</h1>
<input type="number" id="num1" placeholder="Enter first number">
<br>
<input type="number" id="num2" placeholder="Enter second number">
<br>
<button onclick="addNumbers()">Add</button>
<h2 id="result"></h2>
<script>
function addNumbers() {
// Get the values from the input fields
let num1 = parseFloat(document.getElementById("num1").value);
let num2 = parseFloat(document.getElementById("num2").value);
// Check if the inputs are valid numbers
if (isNaN(num1) || isNaN(num2)) {
document.getElementById("result").innerText = "Please enter valid numbers.";
} else {
// Calculate the sum
let sum = num1 + num2;
// Display the result
document.getElementById("result").innerText = "Sum: " + sum;
}
}
</script>
</body>
</html>
Explanation:
HTML Structure:
- There are two input fields for entering numbers and a button to trigger the addition.
- The result will be displayed in an
<h2>
element with the id result
.
JavaScript Function addNumbers()
:
- The function retrieves the values from the input fields, converts them to numbers using
parseFloat()
, and checks if they are valid numbers. - If valid, it calculates the sum and displays the result in the
<h2>
element. - If invalid, it displays an error message asking for valid numbers.
Example: Finding Prime Numbers
<!DOCTYPE html>
<html>
<head>
<title>Prime Numbers</title>
</head>
<body>
<h1>Prime Number Finder</h1>
<p>Enter a number:</p>
<input type="number" id="num" placeholder="Enter N">
<button onclick="findPrimes()">Show Prime Numbers</button>
<h2>Prime Numbers:</h2>
<p id="result"></p>
<script>
function isPrime(number) {
if (number <= 1) return false;
for (let i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) {
return false;
}
}
return true;
}
function findPrimes() {
let num = parseInt(document.getElementById("num").value);
let primes = [];
for (let i = 2; i <= num; i++) {
if (isPrime(i)) {
primes.push(i);
}
}
document.getElementById("result").innerText = primes.join(", ");
}
</script>
</body>
</html>
Explanation:HTML Structure:- An input field to enter the maximum number.
- A button that, when clicked, calls the findPrimes() function to display prime numbers.
- A <p> element with the id result to show the output.
JavaScript Functions:- isPrime(number): Checks if a number is prime by seeing if it has any divisors other than 1 and itself.
- findPrimes(): Retrieves the user's input, iterates through numbers from 2 up to the entered number, and calls isPrime(i) for each. If isPrime(i) returns true, the number is added to the primes array.
- Finally, the function displays the list of prime numbers in the <p id="result"> element.
University website needs to display a dynamic countdown timer for an upcoming events using JavaScript. ( University Question)
<!DOCTYPE html>
<html>
<head>
<title>Event Countdown</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
#countdown {
font-size: 30px;
color: #333;
}
</style>
</head>
<body>
<h1>Countdown to University Event</h1>
<p id="countdown">Loading...</p>
<script>
// Set the event date and time (Year, Month (0–11), Day, Hour, Minute, Second)
const eventDate = new Date("2025-05-01T10:00:00").getTime();
// Update the countdown every second
const countdownTimer = setInterval(function() {
const now = new Date().getTime();
const distance = eventDate - now;
// Time calculations
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result
document.getElementById("countdown").innerHTML =
days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// If the countdown is over
if (distance < 0) {
clearInterval(countdownTimer);
document.getElementById("countdown").innerHTML = "🎉 The event has started!";
}
}, 1000);
</script>
</body>
</html>
Note:The setInterval()
function in JavaScript is used to run a block of code repeatedly at a fixed time interval — in milliseconds.
setInterval(function, delay);
function
– the code you want to run.
delay
– time between executions in milliseconds (1000 ms = 1 second).
Example:
setInterval(function() {
console.log("Hello every 2 seconds");
}, 2000);
This prints "Hello every 2 seconds"
to the console every 2000 milliseconds (i.e., every 2 seconds).
A simple HTML form with JavaScript validation for:
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<script>
function validateForm() {
var email = document.getElementById("email").value;
var mobile = document.getElementById("mobile").value;
// Simple email pattern
var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// Mobile number pattern (10 digits only)
var mobilePattern = /^[0-9]{10}$/;
if (!emailPattern.test(email)) {
alert("Please enter a valid email address.");
return false;
}
if (!mobilePattern.test(mobile)) {
alert("Please enter a valid 10-digit mobile number.");
return false;
}
alert("Form submitted successfully!");
return true;
}
</script>
</head>
<body>
<h2>Student Details Form</h2>
<form onsubmit="return validateForm();">
<label>Email ID:</label><br>
<input type="text" id="email" name="email"><br><br>
<label>Mobile Number:</label><br>
<input type="text" id="mobile" name="mobile"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Explanation:
-
emailPattern
uses a basic regular expression to check email structure.
-
mobilePattern
ensures the number is exactly 10 digits.
-
onsubmit="return validateForm();"
runs the JavaScript function when the form is submitted.
-
alert()
is used to show messages.
Note:
A regular expression (regex) is a pattern used to match character combinations in strings — and it's perfect for validating formats like email addresses.
Example:
/^[^\s@]+@[^\s@]+\.[^\s@]+$/
[^\s@]+ | One or more characters that are not a space (\s ) or @ |
@ | The "@" symbol must appear |
[^\s@]+ | Again, one or more characters not space or @ (the domain) |
\. | A literal dot . (needs escape \ ) |
[^\s@]+ | One or more characters for domain extension (e.g., .com ) |
Comments
Post a Comment