For working professionals
For fresh graduates
More
JavaScript Tutorial Concepts -…
1. Introduction to JavaScript
2. JavaScript Examples
Now Reading
3. Applications of JavaScript
4. JavaScript Hello World
5. JavaScript let
6. JavaScript Callbacks
7. JavaScript Arrays
8. JavaScript Array reduce()
9. JavaScript Loops
10. JavaScript Objects
11. DOM Model in JavaScript
12. JavaScript Form Validation
13. JavaScript Games
14. JavaScript Promises
15. JavaScript Async Await
16. JavaScript Closure
17. JavaScript this keyword
18. OOP in JavaScript
19. Operators in Javascript
20. Redirect in JavaScript
21. Express JS
22. Convert String to int in JavaScript
23. JavaScript Functions
24. JavaScript New Lines
25. JavaScript Regex
26. JavaScript Events
I think that JavaScript is a very versatile and powerful scripting language. Especially as a web developer, I feel that JS is one of the most useful scripting technologies for out there.
Let us check out some JavaScript examples in this tutorial so that I can help you master scripting in JS. I will first cover ten beginner JavaScript example programs with output which you can try out yourself. We will then move on to some more advanced JavaScript examples.
Let us check out some basic Javascript examples with source code so that you can try them out whenever you want.
Code:
function calculateArea(radius) {
const pi = 3.14159;
let area = pi * radius * radius;
return area;
}
let radius = 5;
let area = calculateArea(radius);
console.log("The area of the circle is:", area);
In the above code, the calculateArea(radius) function calculates the area of a circle given its radius. const pi = 3.14159; is a constant to approximate the value of pi. And let area = … calculates the area using the formula. Finally, console.log("The area of the circle is:", area); prints the result to the console.
Code:
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;
}
let number = 17; // Try changing this number
if (isPrime(number)) {
console.log(number, "is a prime number");
} else {
console.log(number, "is not a prime number");
}
In this program, isPrime(number) is a function to determine if a number is prime. It checks for divisibility by numbers up to the square root for efficiency. Also, if (isPrime(number)) ... logs an affirmative message to the console if the number is prime. Otherwise, it logs that the number is not prime.
Code:
function generateRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let randomNumber = generateRandomNumber(1, 10); // Between 1 and 10
console.log("Your random number is:", randomNumber);
In this code, generateRandomNumber(min, max) generates a random integer within a given range (inclusive) and Math.random() generates a random decimal between 0 (inclusive) and 1 (exclusive). The calculation ensures the random number falls between the provided minimum and maximum values.
Code:
let numbers = [5, 2, 8, 1, 9];
numbers.sort((a, b) => a - b); // Sorts in ascending order
console.log("Sorted array:", numbers);
In the above code, numbers.sort((a, b) => a - b) sorts the array of numbers in ascending order using the sort() method and a comparison function. The comparison function (a, b) => a - b subtracts two elements during the sorting process to determine their order.
Code:
let greeting = "Hello, World!";
let uppercaseGreeting = greeting.toUpperCase();
let reversedGreeting = greeting.split("").reverse().join("");
console.log("Uppercase:", uppercaseGreeting);
console.log("Reversed:", reversedGreeting);
Here, greeting.toUpperCase() converts the greeting to uppercase and greeting.split("").reverse().join("") reverses the greeting by splitting it into characters, reversing the array, and joining it back into a string.
Code:
function isPalindrome(word) {
let lowerCaseWord = word.toLowerCase();
let reversedWord = lowerCaseWord.split("").reverse().join("");
return lowerCaseWord === reversedWord;
}
let wordToCheck = "racecar";
console.log(wordToCheck, "is a palindrome?", isPalindrome(wordToCheck));
The isPalindrome(word) function that checks if a word reads the same forwards and backward. It converts the word to lowercase for case-insensitive comparison. It then reverses the word using string manipulation techniques and finally compares the original (lowercase) and reversed word.
Code:
function factorial(number) {
let result = 1;
if (number === 0) {
return 1;
} else {
for (let i = 1; i <= number; i++) {
result *= i;
}
return result;
}
}
console.log("The factorial of 5 is:", factorial(5));
In this program, factorial(number) calculates the factorial of a number (the product of all positive integers less than or equal to the number). The program also handles the special case of 0, where the factorial is 1. Finally, a for loop iterates and multiplies the result variable to calculate the factorial.
Code:
function removeDuplicates(array) {
return [...new Set(array)];
}
let numbersWithDuplicates = [1, 2, 2, 3, 4, 4, 5];
let uniqueNumbers = removeDuplicates(numbersWithDuplicates);
console.log("Array with duplicates removed:", uniqueNumbers);
In the above program, removeDuplicates(array) removes duplicate elements from an array and new Set(array) creates a Set object, which by nature only stores unique values. The spread operator [... ] converts the Set back into an array.
Code:
function countWordOccurrences(text) {
let words = text.toLowerCase().split(" ");
let wordCounts = {};
for (let word of words) {
if (wordCounts[word]) {
wordCounts[word]++;
} else {
wordCounts[word] = 1;
}
}
return wordCounts;
}
let sentence = "This is a sentence with some repeated words";
let counts = countWordOccurrences(sentence);
console.log("Word counts:", counts);
Here, countWordOccurrences(text) is a function to count how often each word appears in a text. The program converts the text to lowercase and splits it into words, then uses an object (wordCounts) to store word counts as key-value pairs. Finally, the code iterates over words, updating the count for each word in the wordCounts object.
Code:
function countdown(seconds) {
let intervalId = setInterval(() => {
seconds--;
console.log("Time remaining:", seconds);
if (seconds === 0) {
clearInterval(intervalId);
console.log("Time's up!");
}
}, 1000); // Update every 1 second
}
countdown(5); // Start a 5-second countdown
Let us look at some more JavaScript examples so that you can experiment with more JavaScript example projects.
Code:
function formatDate(date) {
let day = date.getDate();
let month = date.getMonth() + 1; // Months are zero-indexed
let year = date.getFullYear();
return `${month}/${day}/${year}`;
}
function formatTime(date) {
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
return `${hours}:${minutes}:${seconds}`;
}
let now = new Date();
console.log("Current Date:", formatDate(now));
console.log("Current Time:", formatTime(now));
Code:
function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // Radius of the earth in km
const toRadians = (deg) => deg * (Math.PI / 180);
let dLat = toRadians(lat2 - lat1);
let dLon = toRadians(lon2 - lon1);
let a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
let distance = R * c; // Distance in km
return distance;
}
// Example usage (adjust coordinates as needed)
let distance = calculateDistance(37.7749, -122.4194, 51.5074, 0.1278);
console.log("Distance in km:", distance.toFixed(2));
Code:
function generatePassword(length) {
const characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()";
let password = "";
for (let i = 0; i < length; i++) {
password += characters.charAt(Math.floor(Math.random() * characters.length));
}
return password;
}
let newPassword = generatePassword(12); // Adjust length as needed
console.log("Generated Password:", newPassword);
Code:
function convertTemperature() {
let temp = prompt("Enter a temperature (in Celsius or Fahrenheit): ");
let unit = temp.slice(-1).toUpperCase(); // Check if 'C' or 'F' is at the end
temp = parseFloat(temp);
if (unit === 'C') {
let fahrenheit = (temp * 9/5) + 32;
console.log(`${temp}°C is ${fahrenheit}°F`);
} else if (unit === 'F') {
let celsius = (temp - 32) * 5/9;
console.log(`${temp}°F is ${celsius}°C`);
} else {
console.log("Invalid temperature format.");
}
}
convertTemperature();
Code:
function scrambleWord(word) {
let wordArray = word.split('');
for (let i = wordArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[wordArray[i], wordArray[j]] = [wordArray[j], wordArray[i]]; // Swap
}
return wordArray.join('');
}
let wordToScramble = "hello";
let scrambledWord = scrambleWord(wordToScramble);
console.log("Scrambled word:", scrambledWord);
// Add game logic: Get user guesses, check if correct, etc.
Code:
function validateForm() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let isValid = true; // Start with assumption of validity
if (name === "") {
alert("Please enter your name.");
isValid = false;
}
if (!email.includes("@")) {
alert("Please enter a valid email address.");
isValid = false;
}
return isValid;
}
1. click: Occurs when the user clicks on an element.
Example:
let button = document.getElementById("myButton");
button.addEventListener("click", () => {
console.log("Button clicked!");
});
2. mouseover: Occurs when the mouse pointer hovers over an element.
Example:
let heading = document.querySelector("h1");
heading.addEventListener("mouseover", () => {
heading.style.color = "red"; // Change color on hover
});
3. mouseout: Occurs when the mouse pointer moves away from an element.
Example:
heading.addEventListener("mouseout", () => {
heading.style.color = "black"; // Reset color
});
Now that we have explored some JavaScript examples, I will show you a CSS HTML JavaScript example. Here is JavaScript example site:
Code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.min.css">
<title>DataTables Example</title>
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>32</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>Accountant</td>
<td>New York</td>
<td>28</td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
$('#myTable').DataTable();
});
</script>
</body>
</html>
The above program is a datatable in JavaScript example that uses HTML, CSS, and JavaScript. If you wish to check out more React JavaScript examples and Angular Javascript examples, you can check out upGrad’s React JS Course and Angular Course respectively.
Here is an example program that showcases a few instances of how we can use D3.js:
Code:
<!DOCTYPE html>
<svg width="600" height="400"></svg>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
const data = [
{ x: 10, y: 20 },
{ x: 20, y: 50 },
// ... more data points
];
const svg = d3.select("svg")
// ... set up scales for x and y axes
const line = d3.line()
.x(d => xScale(d.x))
.y(d => yScale(d.y));
svg.append("path")
.datum(data)
.attr("d", line)
// Add interactivity for tooltips, zooming, etc.
</script>
If you wish to master JS and check out more advanced JavaScript examples, you can sign up for upGrad’s software engineering courses.
1. What are the examples of JavaScript?
JavaScript examples include calculating values, validating forms, creating interactive web elements, displaying animations, and building games.
2. How to write a simple JavaScript?
You can write simple JavaScript with the alert() function: <script>alert("Hello, World!");</script>.
3.What is JavaScript in HTML with example?
JavaScript in HTML is used to add dynamic behavior to web pages, like this button click example:
<button onclick="alert('You clicked me!')">Click me</button>
4. Why JavaScript is used with example?
JavaScript is used to make web pages interactive, for example, responding to user actions, changingpage content without reloading, and validating user input.
5. What is the full form of JavaScript?
JavaScript has no official full form, though it's sometimes playfully referred to as Java-lite or loosely related to the Java programming language.
6. What is a simple example of code?
A simple example of code is the classic "Hello, World!" program: console.log("Hello, World!");
7. What is CSS with example?
CSS (Cascading Style Sheets) is used to style HTML elements, for example, changing font color: p { color: red; }
8. Where to write JS code?
You can write JS code within <script> tags in your HTML file or in a separate .js file and link it to your HTML with <script src="script.js"></script>.
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.