1. Home
image

JavaScript Tutorial Concepts - From Beginner to Pro

Learn JavaScript from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 24
  • 9 Hours
right-top-arrow
2

JavaScript Examples

Updated on 12/08/2024452 Views

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.

Top 10 Javascript Examples

Let us check out some basic Javascript examples with source code so that you can try them out whenever you want.

Example 1: Area of a Circle

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.

Example 2: Checking Prime Numbers

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.

Example 3: Generating Random Numbers

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.

Example 4: Sorting an Array

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.

Example 5: String Manipulation

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.

Example 6: Palindrome Checker

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.

Example 7: Factorial Finder

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.

Example 8: Removing Duplicates from an Array

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.

Example 9:  Counting Word Occurrences

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.

Example 10: Simple Countdown Timer

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

More JavaScript Examples

Let us look at some more JavaScript examples so that you can experiment with more JavaScript example projects.

Getting the Current Date and Time

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));

Calculating Distance Between Two Coordinates

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)); 

Simple Password Generator

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);

Simple Temperature Converter

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();

Word Scramble Game

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.

Even/Odd Number Checker with User Input

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;

}

Events in JavaScript Examples

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 

});

HTML with CSS and JavaScript Example

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.

D3 JavaScript Examples

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>

Wrapping Up

If you wish to master JS and check out more advanced JavaScript examples, you can sign up for upGrad’s software engineering courses.

Frequently Asked Questions

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>.

image

mukesh

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...