How to display JavaScript variable value in alert box?

To display JavaScript variable values in an alert box, you can pass variables directly to the alert() function. This is useful for debugging or showing information to users.

Basic Syntax

alert(variableName);
alert("Text: " + variableName);
alert(`Template: ${variableName}`);

Example: Displaying Single Variable

<html>
  <head>
    <script>
      function showSingle() {
        var message = "Hello World!";
        alert(message);
      }
    </script>
  </head>
  <body>
    <button onclick="showSingle()">Show Single Variable</button>
  </body>
</html>

Example: Concatenating Multiple Variables

<html>
  <head>
    <script>
      function display() {
        var a = "Simple";
        var b = "Learning";
        alert(a + " Easy " + b);
      }
    </script>
  </head>
  <body>
    <button onclick="display()">Click me!</button>
  </body>
</html>

Example: Using Template Literals

<html>
  <head>
    <script>
      function showTemplate() {
        var name = "John";
        var age = 25;
        alert(`Name: ${name}, Age: ${age}`);
      }
    </script>
  </head>
  <body>
    <button onclick="showTemplate()">Show Template Example</button>
  </body>
</html>

Different Data Types

<html>
  <head>
    <script>
      function showTypes() {
        var number = 42;
        var boolean = true;
        var array = [1, 2, 3];
        
        alert("Number: " + number);
        alert("Boolean: " + boolean);
        alert("Array: " + array);
      }
    </script>
  </head>
  <body>
    <button onclick="showTypes()">Show Different Types</button>
  </body>
</html>

Key Points

  • Use + operator to concatenate strings and variables
  • Template literals with ${} provide cleaner syntax for modern browsers
  • JavaScript automatically converts most data types to strings in alert boxes
  • Objects and arrays are converted to their string representation

Conclusion

Displaying variables in alert boxes is straightforward using string concatenation or template literals. This technique is essential for debugging and user interaction in JavaScript applications.

Updated on: 2026-03-15T23:18:59+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements