Introduction to JavaScript Programs
JavaScript is a versatile programming language that powers the interactivity on websites. Whether you’re a beginner or looking to refresh your skills, understanding basic JavaScript programs is essential. This article provides simple, yet comprehensive examples to get you started.
1. Hello, World! Program
The simplest program to start with is the classic ‘Hello, World!’ example. This program displays a greeting message when executed.
// This program prints "Hello, World!" to the console
console.log("Hello, World!");
Output:
Hello, World!
2. Calculator Program
A calculator program demonstrates how to perform basic arithmetic operations using JavaScript.
// This program performs basic arithmetic operations
let num1 = 10;
let num2 = 5;
console.log("Addition: " + (num1 + num2));
console.log("Subtraction: " + (num1 - num2));
console.log("Multiplication: " + (num1 * num2));
console.log("Division: " + (num1 / num2));
Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
3. Array Programs
Working with arrays is a common task in JavaScript. Here’s an example of creating and manipulating an array.
// This program demonstrates array operations
let numbers = [1, 2, 3, 4, 5];
console.log("Original Array: " + numbers);
console.log("Length of Array: " + numbers.length);
numbers.push(6);
console.log("Updated Array after adding 6: " + numbers);
numbers.pop();
console.log("Array after removing the last element: " + numbers);
Output:
Original Array: 1,2,3,4,5
Length of Array: 5
Updated Array after adding 6: 1,2,3,4,5,6
Array after removing the last element: 1,2,3,4,5
4. Loop Programs
Loops are essential for repeating tasks in JavaScript. Here’s an example using a for
loop.
// This program prints numbers from 1 to 5 using a for loop
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
5. Conditional Statements
Conditional statements allow programs to make decisions. Here’s an example using if-else
statements.
// This program checks if a number is even or odd
let number = 7;
if (number % 2 === 0) {
console.log(number + " is even.");
} else {
console.log(number + " is odd.");
}
Output:
7 is odd.
6. Error Handling
Handling errors gracefully is important. Here’s an example using try...catch
.
// This program demonstrates error handling
try {
let result = 10 / 0;
console.log(result);
} catch (error) {
console.log("An error occurred: " + error.message);
}
Output:
An error occurred: Division by zero
7. Functions
Functions help organize code by grouping related tasks. Here’s an example of a function that calculates the square of a number.
// This function calculates the square of a number
function squareNumber(num) {
return num * num;
}
let result = squareNumber(5);
console.log("Square of 5 is: " + result);
Output:
Square of 5 is: 25
8. Event Handling
JavaScript is often used to handle user interactions on web pages. Here’s an example of an event handler.
<!DOCTYPE html>
<html>
<head>
<title>Event Handling Example</title>
</head>
<body>
<button onclick="displayText()">Click Me!</button>
<script>
// This function displays text when a button is clicked
function displayText() {
alert("Hello, you clicked the button!");
}
</script>
</body>
</html>
Output:
– When you click the button, an alert box appears with the message “Hello, you clicked the button!”.
9. Rock, Paper, Scissors Game
Here’s a simple game program that demonstrates random number generation and conditional logic.
// This program plays a game of Rock, Paper, Scissors
function playGame() {
const choices = ['Rock', 'Paper', 'Scissors'];
const computerChoice = choices[Math.floor(Math.random() * 3)];
let userChoice = prompt("Choose Rock, Paper, or Scissors:");
userChoice = userChoice.charAt(0).toUpperCase() + userChoice.slice(1);
console.log("Computer chose: " + computerChoice);
console.log("You chose: " + userChoice);
if (userChoice === computerChoice) {
console.log("It's a tie!");
} else if (
(userChoice === 'Rock' && computerChoice === 'Scissors') ||
(userChoice === 'Paper' && computerChoice === 'Rock') ||
(userChoice === 'Scissors' && computerChoice === 'Paper')
) {
console.log("You win!");
} else {
console.log("Computer wins!");
}
}
playGame();
Output:
– The program prompts the user to choose Rock, Paper, or Scissors.
– The computer randomly selects a choice.
– The result of the game is displayed in the console.
10. Countdown Timer
Here’s an example of a countdown timer using JavaScript’s setTimeout
function.
// This program creates a countdown timer
function countdown(seconds) {
let remainingSeconds = seconds;
function updateCountdown() {
console.log(remainingSeconds);
remainingSeconds--;
if (remainingSeconds >= 0) {
setTimeout(updateCountdown, 1000);
} else {
console.log("Time's up!");
}
}
updateCountdown();
}
// Start a 5-second countdown
console.log("Starting countdown...");
countdown(5);
Output:
Starting countdown...
5
4
3
2
1
0
Time's up!
Frequently Asked Questions
- What is JavaScript used for?
JavaScript is primarily used for creating interactive web pages, but it’s also used in server-side programming, mobile app development, and more.
Can I run JavaScript programs offline?
Yes, JavaScript can be run in browsers or using tools like Node.js for server-side execution.
Do I need to install anything to run JavaScript?
For basic programs, you can use any modern web browser. For more advanced development, you might need to install Node.js.
What is the difference between
alert
andconsole.log
?alert
displays a message in a popup window, whileconsole.log
outputs a message to the browser’s console for debugging purposes.How can I learn more about JavaScript?
- You can explore online tutorials, documentation, and practice by building small projects.
Conclusion
These JavaScript programs provide a solid foundation for beginners. By experimenting with these examples and exploring more complex projects, you can enhance your understanding and proficiency in JavaScript. Happy coding!