Java-Script Examples Discussed in Class
Example: Internal JavaScript
<html>
<head><title>First js code</title></head>
<body>
<script>
x = 10;
y = 15;
z = x + y;
debugger;
[Link](z);
[Link](a);
</script>
</body>
</html>
Example: Java Script using window console page
var n=100
[Link](n+" ") //Error that [Link] cannot execute html commands
[Link](n)
var x=200
[Link](x+" ") //Error that [Link] cannot execute html commands
var y=300
[Link](y+" ") //Error that [Link] cannot execute html commands
Example: Variable Hoisting using “var” keyword
var n=20
[Link](n)
var n=20 //Allowed redaclaring variable outside block scope
[Link](n)
{
var n=30
[Link](n)
var n=40 //Allowed redaclaring variable inside block scope
[Link](n)
}
var n=40
[Link](n)
Example: Variable Hoisting using “let” keyword
let n=20
[Link](n)
let n=20
[Link](n) //Not Allowed redeclaring same variable name outside block
scope
{
let n=30
[Link](n)
let n=0 //Not Allowed redeclaring same variable name within a block
scope
[Link](n)
}
let n=50
[Link](n) //Not Allowed redeclaring same variable name outside block
scope
Example: Variable Hoisting using “const” keyword
const n=20 //variable name declared as const can not be reuse
[Link](n)
const n=400 //Not Allowed redeclaring same variable name within a block
scope
[Link](n)
{
const n=30
[Link](n)
const n=50 //Not Allowed redeclaring same variable name within a block
scope
[Link](n)
Example: Defining and invoking function
<!DOCTYPE html>
<html>
<head>
<script>
function First() //JavaScript in head
{
[Link]("demo").innerHTML = "Hello Buddies.";
}
</script>
</head>
<body>
<h2>Demo JavaScript in Head</h2>
<p id="demo">A Paragraph</p>
<button onclick="First()">Try it</button>
</body>
</html>
Example: Defining and invoking function using DOM and BOM
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="first()">Try it</button>
<button type="button" onclick="second()">Alert..!</button>
<button onclick="[Link]()">Print this page</button>
<script>
function first() //JavaScript in body
{
[Link]("demo").innerHTML = "THE ADDITION RESULT IS:" + 19 +
6;
[Link](5 + 6);
}
function second()
{
[Link]("THE ADDITION RESULT IS: " + 15 + 26);
}
</script>
</body>
</html>
Example: Defining and invoking function
<html>
<body>
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="click here">
</body>
</html>
<!-- With parameter in function -->
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<input type="button" value="click" onclick="getcube(4)">
</body>
</html>
<!-- function with return value -->
<html>
<body>
<script>
function bhimu(){
return "This my return value..! How r u?";
}
[Link](bhimu());
[Link](bhimu());
</script>
</body>
</html>
Example: Dynamic activity within a HTML using Document Object
Model(DOM)
<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript</h1>
<p>JavaScript can change the content of an HTML element:</p>
<button type="button" onclick="display()" >Click here..!</button><br> <br>
<button type="button" onclick="styles()" >Click here for css..!</button>
<p id="demo">This is a demonstration.</p>
<script src="data_types/[Link]">
function display()
{
[Link]("demo").innerHTML = "JavaScript!";
}
function styles() {
[Link]("demo").[Link] = "25px";
[Link]("demo").[Link] = "red";
[Link]("demo").[Link] = "yellow";
}
</script>
<noscript>Sorry, your browser does not support JavaScript!</noscript>
</body>
</html>
Example: Declaring variable using window prompt()
<!DOCTYPE html>
<html>
<head>
<title>Variable Declaration</title>
</head>
<body>
<script>
let fname =prompt("Enter Your First Name");
let lname =prompt("Enter Your Last Name");
var age =prompt("Enter Your Age");
let isStudent =prompt("Are You an Student Yes/No");
[Link](fname + lname + "<br>");
[Link](age + "<br>");
[Link](isStudent + "<br>");
const PI = 3.14;
[Link](PI);
</script>
</body>
</html>
Example: String Inbuilt Methods
let text = "Apple, Banana, Kiwi";
let part = [Link](7,13);
[Link](part);
//substring()
let part1 = [Link](9, 17);
[Link](part1);
let text1 = "This is the first text";
[Link](text1);
let newText = [Link]("This is ", "Overrided text ");
[Link](newText);
//toUpperCase()
let text3 = [Link]();
[Link](text3);
//concat()
let text4 = "Am adding...!";
let text5 = [Link](" ", text4);
[Link](text5);
//trim()
let totrim = " Hello World! ";
let trimmed = [Link]();
[Link]("Length totrim =" + [Link] + " Trimmed Length = " +
[Link]);
Example: String Inbuilt Methods
let text = "Please locate where 'locate' occurs!";
[Link](text);
let index = [Link]("locate");
[Link](index);
//lastIndexOf()
let index1 = [Link]("locate");
[Link](index1);
//search()
let index2=[Link]("locate");
[Link](index2);
//startsWith()
let index3=[Link]("Please");
[Link](index3);
Example: Variable Substitution
let firstName = "Ethnotech";
let lastName = "Acadamics";
let text = `Welcome to ${firstName}, ${lastName}!`;
[Link](text);
let price = 10;
let VAT = 0.25;
let total = `Total: ${(price * (1 + VAT))}`;
[Link](total);
Example: Number Methods
let x1 = 123;
[Link]([Link]() + " " + " " +(111 + 32).toString());
let x = 9.656;
//toPrecision()
[Link]([Link]() + "\n "
+[Link](2) + "\n "
+ [Link](4) + "\n " +
[Link](6) );
[Link](Number(true) + "<br>" +
Number(false) + "\n" +
Number("10") + "\n" +
Number(" 10") + "\n" +
Number("10 ") + "\n" +
Number(" 10 ") + "\n" +
Number("10.33") + "\n" +
Number("10,33") + "\n" +
Number("10 33") + "\n" +
Number("John")+ "\n"+
Number(new Date("1970-01-01")));
Example: Events in Java Script
<html>
<head><title>Events</title></head>
<body>
<script src="[Link]"></script>
<h3>onmouseout</h3>
<input type="button" value="SUBMIT" onmouseout="fun1()">
<br><br>
<h2>onmouseover</h2>
<button onmouseover="displayDate()">The time is?</button>
<p id="date"></p>
<br><br>
<h3>onclick</h3>
<input type="button" value="SUBMIT" onclick="fun2()">
<br><br>
<h3>onload</h3>
<input type="button" value="SUBMIT" onclick="fun2()">
<br><br>
<h3>onchange</h3>
<select id="sep" onchange="fun()">
<option>SELECT</option>
<option value="RED">RED</option>
<option value="BLUE">BLUE</option>
<option value="BLACK">BLACK</option>
<option value="PINK">PINK</option>
</body>
</html>
Example: User defined Objects in Javascript
/* creating object */
var dog=
{
name: "puppy",
age:12,
}
[Link](dog)
[Link](typeof(dog))
//accessing value from an object
[Link]([Link]+" "+[Link])
[Link](dog["name"])
[Link](dog["age"])
//adding properties to dog object
dog["color"]="brown"
[Link](dog)
//changed the value for key age
dog["age"]=30
[Link](dog)
//Object creating using new keyword
var emp=new Object();
[Link]=101;
[Link]="Ravi";
[Link]=50000;
[Link]([Link]+" "+[Link]+" "+[Link]);
Example: Pre-defined Objects in Javascript
//using assign()
var object1 = {a: 11, b: 12, c: 33 };
[Link](object1);
var object2 = [Link](object1,{c: 19, d: 5, e:4});
[Link](object2.c,object2.e, object2.d);
[Link](object2);
//using create()
const people = {
printIntroduction: function ()
{ [Link](`My name is ${[Link]}. Am I human? ${[Link]}`); }
};
const me = [Link](people);
[Link] = "Marry";
[Link] = true;
[Link]();
//using entries()
var obj = { 1:'marrc', 2:'sort', 3:'carry' };
[Link]([Link](obj)[2]);
//freeze()
const object1 = { property1: 22 };
const object2 = [Link](object1);
object2.property1 = 33;
[Link](object2.property1);
//getOwnPropertyDescriptor()
const object1 = { a: 42 }
const object2 = { c: 34 }
const descriptor1 = [Link](object1, 'a');
const descriptor2 = [Link](object2, 'c');
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
Example: Creating objects by passing constructor parameters ([Link])
//object constructor
class Fan
{
constructor(name,wings)
{ [Link]=name
[Link]=wings }
rotate()
{ [Link]("Fan is rotating") }
}
var f1=new Fan("Bajaj",3)
[Link](f1)
[Link](typeof(f1))
[Link]([Link]+" "+[Link])
[Link]()
//object constructor
function emp(id,name,salary){
[Link]=id;
[Link]=name;
[Link]=salary;
}
e=new emp(103,"Yashasvi Jaiswal",30000);
[Link]([Link]+" "+[Link]+" "+[Link]);
Example: To over-ride value of user-defined object ([Link])
/* Defining method in JavaScript
We can define method in JavaScript object. But before defining method,
we need to add property in the function with same name as method.
*/
function emp(id,name,salary){
[Link]=id;
[Link]=name;
[Link]=salary;
[Link]=changeSalary; //defining method to change salary
function changeSalary(updateSal)
{
[Link]=updateSal;
}
}
e=new emp(103,"Yashasvi Jaiswal",30000);
[Link]([Link]+" "+[Link]+" "+[Link]);
[Link](45000);
[Link]([Link]+" "+[Link]+" "+[Link]);
Example: BOM Predefined methods ([Link])
//using open()
var win_open=function()
{
[Link]("[Link]
}
//using close()
var win_close=function()
{
[Link]()
}
//using setTimeOut()
function msg(){
setTimeout(function()
{
alert("Welcome to alertbox after 2 seconds")
},2000);
}
Example: Creating an Array
//By passing string in an Array
// Using object Literal
var emp=["Virat","Devil","Ratan"];
for (i=0;i<[Link];i++){
[Link](emp[i] + " ");
}
// Using new keyword
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<[Link];i++){
[Link](emp[i] + " ");
console
}
[Link](typeof(emp));
//Using Constructor
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<[Link];i++){
[Link](emp[i] + " ");
}
Example: Performing Tasks Using Array pre-defined methods
//Sorting in an Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](fruits);
[Link]();
[Link](fruits);
//Reversing an Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](fruits);
// First sort the array
[Link]();
[Link](fruits);
// Then reverse it:
[Link]();
[Link](fruits);
//Sorting an Array
const points = [40, 100, 1, 5, 25, 10];
[Link](points);
[Link](function(a, b){return a - b}); //if b is negative, it means 'a'
should
[Link](points); //come before 'b'
//Randomising the Array elements
const points = [40, 100, 1, 5, 25, 10];
[Link](points);
[Link](function(){return 0.5 - [Link]()});
[Link](points);
//to find highest number in an Array using [Link]
const points = [40, 100, 1, 5, 25, 10];
[Link](points);
function myArrayMax(arr) {
return [Link](null, arr);
}
[Link](myArrayMax(points));
//largest element using statements
const points = [40, 100, 1, 5, 25, 10];
[Link](points);
function myArrayMax(arr) {
let len = [Link];
let max = -Infinity;
while (len--) {
if (arr[len] > max) {
max = arr[len];
}
}
return max;
}
[Link](myArrayMax(points) );
//using map()
const arr1 = [45, 4, 9, 16, 25];
[Link](arr1);
const arr2 = [Link](multi); //map() will calls the specified function
function multi(value, index, array)
{
return value * 2;
}
[Link](arr2);
// using filter()
const numbers = [45, 4, 9, 16, 25];
[Link](numbers);
const over18 = [Link](myFunction);
function myFunction(value, index, array)
{
return value > 18;
}
[Link](over18);
//using reduce() to get the result of an Array
const numbers = [45, 4, 9, 16, 25];
[Link](numbers);
let sum = [Link](myFunction);
function myFunction(total, value, index, array) {
return total + value;
}
[Link]("The sum is " + sum);
//using every() to check elements in an array
const numbers = [45, 4, 9, 16, 25];
[Link](numbers);
let allOver18 = [Link](myFunction);
function myFunction(value, index, array) {
return value > 18;
}
[Link]("all my elements over 18: " + allOver18);
//some()
let checkSome = [Link](myFunction);
function myFunction(value, index, array) {
return value > 18;
}
[Link]("some of my elements over 18: " + checkSome);
//index()
let position = [Link](45) + 1;
[Link]("Number is found in position " + position);
//lastIndexOf()
const fruits = ["Apple", "Orange", "Apple", "Mango"];
[Link](fruits);
let position1 = [Link]("Apple") + 1;
[Link]("Number is found in position " + position1);
//find()
const number = [4, 9, 16, 25, 29];
[Link](number);
let first = [Link](myFunction);
function myFunction(value, index, array) {
return value > 18;
}
[Link]("First number over 18 is " + first);
//push() , pop()
const cars = ["Saab", "Volvo", "BMW"];
// Change an element:
cars[0] = "Toyota";
// Add an element:
[Link]("Audi");
[Link](cars);
[Link]();
[Link](cars);
Example: Form validation using JavaScript
.html
<html>
<head><title>Text box validation</title></head>
<body>
<script src="[Link]"></script>
<form onsubmit="return validate()" action="[Link]
<label>fullname</label>
<input type="text" name="fname" id="fname">
<span style="color: brown;" id="msg">*</span>
<br><br>
<input type="submit">
</form>
</body>
</html>
.js
function validate()
{
var res=[Link]("fname").value
if([Link]==0)
{
[Link]("msg").innerHTML="fname is required"
return false
}
else if([Link]<3)
{
[Link]("msg").innerHTML="fname should more than 3
letters"
return false
}
else if([Link]>15)
{
[Link]("msg").innerHTML="fname must less than 15 letters"
return false
}
}
Example: Form validation using JavaScript ( Forgot pass)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function matchpass(){
var firstpassword=[Link];
var secondpassword=[Link];
if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}}
</script></head>
<body>
<form name="f1" action="[Link] onsubmit="return matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>
</body>
</html>
Example: Form validation using JavaScript
.html
<html>
<body>
<script src="[Link]"></script>
<form name="myform" method="post" action="[Link]
onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
<a href="forget_pass.html">forgot password</object>
</body>
</html>
.js
function validateform()
{
var name=[Link];
var password=[Link];
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
} }
//number validation
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value
only";
return false;
}else{
return true;
}
}
Example: Form validation using JavaScript (Phone number)
.html
<html>
<head><title>Phone number validation</title></head>
<body>
<script src="ph_no.js"></script>
<form onsubmit="return validate()" action="[Link]
<label>Ph_number</label>
<input type="text" name="phone" id="phone">
<span style="color: brown;" id="msg">*</span>
<br><br>
<input type="submit">
</form>
</body>
</html>
.js
function validate()
{
var res=[Link]("phone").value
if([Link]==0)
{ [Link]("msg").innerHTML="phone number is required"
return false
}
else if(isNaN(res)==true)
{
[Link]("msg").innerHTML="Enter only numbers...!"
return false
}
else if([Link]<10)
{ [Link]("msg").innerHTML="phone number should more than 3
letters"
return false
}
else if([Link]>10)
{
[Link]("msg").innerHTML="phone number must 10 letters"
return false
}
else if([Link](0)<7)
{[Link]("msg").innerHTML="starting digit must more than 7"
return false
}}
Example: Types of errors in JavaScript
<!DOCTYPE html>
<html><head><style>h2{color: seagreen;text-decoration: underline;}p{color:
red}</style></head>
<body>
<h1>JavaScript Errors</h1>
<h2>The RangeError</h2>
<pre>You cannot set the number of significant digits too high</pre>
<p id="demo">
<script>
let num1 = 1;
try {
[Link](500);
}
catch(err) {
[Link]("demo").innerHTML = [Link];
}
</script>
<h2>The ReferenceError</h2>
<pre>You cannot use the value of a non-existing variable:</pre>
<p id="demo1"></p>
<script>
let x = 5;
try {
x = y + 1;
}
catch(err) {
[Link]("demo1").innerHTML = [Link];
}
</script>
<h2>The URIError</h2>
<pre>Some characters cannot be decoded with decodeURI():</pre>
<p id="demo2"></p>
<script>
try {
decodeURI("%%%");
}
catch(err) {
[Link]("demo2").innerHTML = [Link];
}
</script>
<h2>The SyntaxError</h2>
<pre>You cannot evaluate code that contains a syntax error:</pre>
<p id="demo3"></p>
<script>
try {
eval("alert('Hello)");
}
catch(err) {
[Link]("demo3").innerHTML = [Link];
}
</script>
<h2>The TypeError</h2>
<pre>You cannot convert a number to upper case:</pre>
<p id="demo4"></p>
<script>
let num = 1;
try {
[Link]();
}
catch(err) {
[Link]("demo4").innerHTML = [Link];
}
</script>
</body>
</html>
Example: Exception Handling in JavaScript
<html>
<head> Exception Handling</br></head>
<body>
<script>
try{
var a= ["34","32","5","31","24","44","67"]; //a is an array
[Link](a); // displays elements of a
[Link](b); //b is undefined but still trying to fetch its value. Thus
catch block will be invoked
}
catch(e){
alert("There is a error in here "+[Link]); //Handling error
}
</script>
</body>
</html>
<!-- user defined throw exception -->
<html>
<head>Exception Handling</head>
<body>
<script>
try {
throw new Error('This is the throw keyword'); //user-defined throw
statement.
}
catch (e) {
[Link]([Link]); // This will generate an error message
}
</script>
</body>
</html>
<!-- try…catch…finally -->
<html>
<head></head>
<body>
<script>
try{
var a=4;
if(a==2)
[Link]("ok");
}
catch(Error){
[Link]("Error found"+[Link]);
}
finally{
[Link]("Value of a is 2 ");
}
</script>
</body>
</html>
Example: JavaScript outputs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>JavaScript Output Examples</title></head>
<body>
<h1>JavaScript Output Example</h1>
<script>
var outputContainer = [Link]("div");
var userInput = [Link]('Enter something:');
var output = [Link]("p");
[Link]([Link]('You entered: ' +
userInput));
[Link](output);
[Link](outputContainer);
</script>
</body>
</html>