JScript Examples





Generated by AI, corrected by PeatSoft

  1. Hello World (in a browser)
    
    alert("Hello, world!");
    

    This code will display a pop-up message box with the text "Hello, world!".

  2. Variables and Output
    
    var name = "Alice";
    var age = 30;
    document.write("Name: " + name + "<br>"); // Output to the web page
    document.write("Age: " + age + "<br>");
    

    This example declares two variables, `name` (a string) and `age` (a number), and then writes their values to the HTML document using `document.write()`. The `<br>` tag adds a line break. This is how you might output data to a web page using J(ava)Script.

  3. Simple Function
    
    function add(x, y) {
      return x + y;
    }
    
    var result = add(5, 3);
    alert("The sum is: " + result);
    

    This defines a function called `add` that takes two arguments (`x` and `y`) and returns their sum. It then calls the function with the numbers 5 and 3, stores the result in the `result` variable, and displays it in an alert box.

  4. Conditional Statement (if/else):
    
    var score = 75;
    
    if (score >= 60) {
      alert("Passed!");
    } else {
      alert("Failed.");
    }
    

    This code checks the value of the `score` variable. If the score is 60 or greater, it displays "Passed!"; otherwise, it displays "Failed.".

  5. Loop (for loop):
    
    for (var i = 1; i <= 5; i++) {
      document.write("Iteration: " + i + "
    "); }

    This `for` loop iterates five times. In each iteration, it outputs the current iteration number to the web page.

  6. Arrays:
    
    var colors = ["red", "green", "blue"];
    alert(colors[0]); // Output: red
    alert(colors[1]); // Output: green
    

    This example shows how to declare and access an array in JScript.