JavaScript Examples
In this page we have simple solved examples for the lessons.
Example 1: Input and output
Read a number from the user and display it on the page.
var num;
num = Number(prompt("Enter a number"));
document.write("You entered: " + num);
Example 2: Basic numeric operators
Read two numbers and display their sum.
var a, b, result;
a = Number(prompt("Enter first number"));
b = Number(prompt("Enter second number"));
result = a + b;
document.write("Sum = " + result);
Example 3: Conditions
Read a grade and display Pass or Fail.
var grade;
grade = Number(prompt("Enter your grade"));
if (grade >= 50) {
document.write("Pass");
} else {
document.write("Fail");
}
Example 4: Loops
Display the numbers from 1 to 5.
var i;
for (i = 1; i <= 5; i++) {
document.write(i + "<br>");
}