Javascript Examples
File Name: scriptBlock.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
<script>
alert('Hello World!');
</script>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
Notes: JavaScript is a dynamic scripting language that allows you to build interactivity into otherwise static HTML pages. This is done by embedding blocks of JavaScript code almost anywhere in your Web page.
The JavaScript code here uses alert(); function to display alert message.
File Name: order.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
<script>
alert("Alert message from head section.");
</script>
</head>
<body>
<h1>Hello World!</h1>
<script>
alert("Alert message from body section, before html code!");
</script>
</body>
</html>
<script>
alert("Alert message from body section, after html code!");
</script>
Notes: We can place any number of <script> element in a single document. However, they are executed in the order in which they appear in the document, from top to bottom.
File Name: externalJs.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Java Script Examples</title>
<script src="app.js"></script>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
app.js
alert("Hell, World! From external file.");
Notes: When scripts are long or need to be shared by other pages, they are usually placed inexternal files, separate from the HTML page.
File Name: inlineJs.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Java Script Examples</title>
</head>
<body>
<button onclick="alert('Hello World!')">Click Me</button>
</body>
</html>
Notes: You can also place JavaScript code inline by inserting it directly inside the HTML tag using the special tag attributes such as onclick, onmouseover, onkeypress, onload, etc.
However, you should avoid placing large amount of JavaScript code inline as it clutters up your HTML with JavaScript and makes your JavaScript code difficult to maintain.
File Name: commenting.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
// This is a one-line comment
document.write("Hello");
/* This is a
multiline
comment
*/
</script>
</body>
</html>
Notes: Comments are non-executable statements in a program.A comment is text that describes what the program or a particular part of the program is trying to do and is ignored by the JavaScript interpreter.
Commenting your code is considered good programming practice regardless of the language you are programming in. Writing clear, concise, meaningful comments to describe your code allows other developers you might work with to understand your code. Plus, they can help you as well: If you come back to your code after a long absence they remind you of the logic you used in building your programs or scripts.
File Name: consoleLog.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
console.log("Hello World via the console!");
</script>
</body>
</html>
Notes: console.log() simply displays the message on the web browser's window. It is primarily used for debugging purposes.
File Name: documentWrite.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
document.write("Welcome to the JavaScript Programming!");
document.write("<h2>Welcome to the JavaScript Programming!</h2>");
</script>
</body>
</html>
Notes: document.write() is used whenever we want to print the content onto the HTML page. It is a simple, easy-to-use method for displaying content on to a web page.
File Name: alert.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
alert("Thanks for your input!");
</script>
</body>
</html>
Notes: alert() is used to display a message on the web page. Using alert() triggers a pop-up window with the specified message. It provides a dialog box with a button that displays "ok". This is generally used to provide some warning or information to the user.
File Name: variable.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
let firstName;
firstName = "SriRam";
let age = 25;
</script>
</body>
</html>
Notes: Variables are the names given to storage locations in JavaScript. These storage locations can then be used to store any type of data by directly referring them via their assigned names.
File Name: displayVariable.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
let name ="Sri Ram";
document.write(name);
</script>
</body>
</html>
Notes: To display a variable value, we can pass the variable name to the document.write() method but without enclosing it in quotation marks.
File Name: concatenating.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
let name = "Sri rama";
alert(name + " Thanks for your input!");
</script>
</body>
</html>
Notes: Concatenation refers to the act of combining two text strings into one longer text string.
File Name: prompt.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
let name = prompt("Enter Your Name!");
alert("Hello! " + name);
</script>
</body>
</html>
Notes: prompt() dialog box is used to take input from the user.
File Name: confirm.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
let response = confirm("Do you want to close the page?");
alert(response);
</script>
</body>
</html>
Notes: confirm() is the built-in function used to ask confirmation from the user. It displays the message and provides the user with two buttons, "ok" and "cancel".
File Name: convertingData.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
document.write(
Number(true) + "<br>" +
Number(false) + "<br>" +
Number("10") + "<br>" +
Number(" 10") + "<br>" +
Number("10 ") + "<br>" +
Number(" 10 ") + "<br>" +
Number("10.33") + "<br>" +
Number("10,33") + "<br>" +
Number("10 33") + "<br>" +
Number("John") + "<br>" );
document.write(parseInt("10.33")+ "<br>");
document.write(parseFloat("10.33")+ "<br>");
</script>
</body>
</html>
File Name: random.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
document.write(Math.random());
//document.write(Math.random()*100);
//document.write(Math.round(Math.random()*100));
</script>
</body>
</html>
Notes: Math.random() command is used to create a random number between 0 and 1.
File Name: bmi.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
let weight = parseFloat(prompt("Enter Weight in Kilograms"));
let height = parseFloat(prompt("Height in meters"));
let bmi = (weight / (height * height));
alert("BMI is: " + bmi.toFixed(2));
</script>
</body>
</html>
Notes: JavaScript Number toFixed( ) method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal.
Conditional Statements (Decision Making)
File Name: ifStatement.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
let member = confirm("Are you a member of this society?");
let interestRate = 12;
if (member == true) {
interestRate = 10;
}
alert("Interest rateis : " + interestRate );
</script>
</body>
</html>
Notes: The if statement is used to execute a block of code based upon a logical condition. The block following the condition is executed only when the condition specified resolves to true. If the condition evaluates to false, the statements following the if block are not executed.
File Name: ifelseStatement.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
let age = prompt("Enter your Age");
if( age > 18 ){
alert("Qualifies for driving");
}else{
alert("Does not qualify for driving");
}
</script>
</body>
</html>
Notes: The if...else statement allows you to execute one block of code if the specified condition is results to true and another block of code if it is results to false. The if...else statement enhances the decision making capabilities of JavaScript program by providing an alternative choice.
File Name: ifelseifStatement   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
let score = prompt("Enter your score","like 80 (0-100)");
if (score >= 90)
alert ("Grade: A");
else if (score >= 80)
alert ("Grade: B");
else if (score >= 70)
alert ("Grade: C");
else if (score >= 60)
alert ("Grade: D");
else
alert("Grade: F");
</script>
</body>
</html>
Notes: The 'if...else if...else' statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.
File Name: switchcase.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
let day = parseInt(prompt("Enter day number"," 0 for sun day"));
switch (day) {
case 0:
alert ("Sunday");
break;
case 1:
alert ("Monday");
break;
case 2:
alert ("Tuesday");
break;
case 3:
alert ("Wednesday");
break;
case 4:
alert ("Thursday");
break;
case 5:
alert ("Friday");
break;
case 6:
alert ("Saturday");
break;
default:
alert ("Invalid Input");
break;
</script>
</body>
</html>
Notes: The switch statements provide a more readable way of writing elseif statements. The switch..case statement is an alternative to the if...else if...else statement. The switch...case statement tests a variable or expression against a series of values until it finds a match, and then executes the block of code corresponding to that match.
File Name: ternaryOpe.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
let age = prompt("Enter your Age");
let eligibleToVote = (age >= 18) ? "Qualifies for driving": "Does not qualify for driving";
alert(eligibleToVote);
</script>
</body>
</html>
Notes: The ternary operator is a special operator that operates on three operands and hence ternary in nature. The logical expression and two values (or expression) from which one will be used as a result based upon the logical expression or condition being passed. It is useful in writing single line conditional statements, which can replace the if else code.
JavaScript Loops (Repeat a sequence of statements)
File Name: while.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
let i = 0;
while (i < 10) {
document.write("<p>The number is " + i + "</p>");
i++;
}
</script>
</body>
</html>
Notes: The while loop will only be executed as long as the condition is true, so if the condition is false to begin with, the code inside will be skipped.
Make sure that the condition specified in your loop eventually goes false. Otherwise, the loop will never stop iterating which is known as infinite loop.
File Name: dowhile.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
let number;
do {
number = prompt("Please enter a number between 0 and 100: ");
} while ((number >= 0 && number < 100));
alert("Number is < 0 && number > 100");
</script>
</body>
</html>
Notes: The do-while loop is a specialized form of while loop where the code block is executed at least once and then the condition is checked to determine further execution. If the condition resolves to true, code block is executed again.
File Name: forloop.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
for (i = 1; i <= 10; i++){
document.write ("value of i is "+i + "<br>");
}
</script>
</body>
</html>
Notes: The for loop is the simplest of all and very comprehensive to write. The for loops take an initial value, termination condition and increment/decrement condition as input. The initial value is used only once for initialization purposes. The termination condition is tested, and the block is executed. Once the block is executed, the increment/decrement condition is evaluated to update the value of counter. The test condition is checked again, and the code is executed if the counter satisfies the condition. This way the loop continues to execute until the counter value fails to meet the criteria or the termination condition is met.
File Name: nestedLoop.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
var str = "@";
for (var row = 0; row < 6; row++){
for (var col=0; col < row; col++){
document.write(str);
}
document.write("<br>");
}
</script>
</body>
</html>
Notes: A loop within a loop is a nested loop. A common use for nested loops is to display data in rows and columns.
Functions (Reusable blocks of code)
File Name: definition.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
// Defining function
function sayHello() {
alert("Hello, welcome to this website!");
}
// Calling function
sayHello(); // Outputs: Hello, welcome to this website!
</script>
</body>
</html>
Notes: Functions must be declared before they can be used. Function definitions are often stored in external JavaScript files or libraries.
To define a function, the function keyword is followed by the name of the function and a set of parentheses. The parentheses are used to hold parameters, values that are received by the function.
The function’s statements are enclosed in curly braces. The function statements will be executed when they get called. JavaScript will not run the statements when the functions do not get invoked.
Once you define a function, you can use it. JavaScript functions are invoked by calling the function
File Name: functionDef.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
// Defining function
function addTwoNumbers(number1, number2) {
let total = number1 + number2;
alert(total);
}
// Calling function
addTwoNumbers (3, 10); // 0utputs: 13
addTwoNumbers (12, -7); // 0utputs: 5
</script>
</body>
</html>
Notes: If a user wants to send values to a function, the values are enclosed in the parentheses right after the function name and sent as a comma-separated list of arguments when the function is called. The arguments are received by the function in a list of corresponding values called parameters.
The names of the arguments are not necessarily the same names in the parameter list, but they correspond to the same values. These values can be assigned to local variables within the function. Local variables disappear when the function exits.
File Name: functionPara.html   View
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Examples </title>
</head>
<body>
<script>
// Defining function
function addTwoNumbers(number1, number2) {
let total = number1 + number2;
alert(total);
}
// Calling function
addTwoNumbers (3, 10); // 0utputs: 13
addTwoNumbers (12, -7); // 0utputs: 5
</script>
</body>
</html>
Notes: If a user wants to send values to a function, the values are enclosed in the parentheses right after the function name and sent as a comma-separated list of arguments when the function is called. The arguments are received by the function in a list of corresponding values called parameters.
The names of the arguments are not necessarily the same names in the parameter list, but they correspond to the same values. These values can be assigned to local variables within the function. Local variables disappear when the function exits.