JScript Examples
Generated by AI, corrected by PeatSoft
-
Hello World (in a browser)
alert("Hello, world!");
This code will display a pop-up message box with the text "Hello, world!".
-
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.
-
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.
-
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.".