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;
document.write(z);
document.write(a);
</script>
</body>
</html>
Example: Java Script using window console page
var n=100
document.write(n+" ") //Error that node.js cannot execute html commands
console.log(n)
var x=200
document.write(x+" ") //Error that node.js cannot execute html commands
var y=300
document.write(y+" ") //Error that node.js cannot execute html commands
Example: Variable Hoisting using “var” keyword
var n=20
console.log(n)
var n=20 //Allowed redaclaring variable outside block scope
console.log(n)
{
var n=30
console.log(n)
var n=40 //Allowed redaclaring variable inside block scope
console.log(n)
}
var n=40
console.log(n)
Example: Variable Hoisting using “let” keyword
let n=20
console.log(n)
let n=20
console.log(n) //Not Allowed redeclaring same variable name outside block
scope
{
let n=30
console.log(n)
let n=0 //Not Allowed redeclaring same variable name within a block
scope
console.log(n)
}
let n=50
console.log(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
console.log(n)
const n=400 //Not Allowed redeclaring same variable name within a block
scope
console.log(n)
{
const n=30
console.log(n)
const n=50 //Not Allowed redeclaring same variable name within a block
scope
console.log(n)
Example: Defining and invoking function
<!DOCTYPE html>
<html>
<head>
<script>
function First() //JavaScript in head
{
document.getElementById("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="window.print()">Print this page</button>
<script>
function first() //JavaScript in body
{
document.getElementById("demo").innerHTML = "THE ADDITION RESULT IS:" + 19 +
6;
console.log(5 + 6);
}
function second()
{
window.alert("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?";
}
document.write(bhimu());
console.log(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/datatypes.JS">
function display()
{
document.getElementById("demo").innerHTML = "JavaScript!";
}
function styles() {
document.getElementById("demo").style.fontSize = "25px";
document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.backgroundColor = "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");
document.write(fname + lname + "<br>");
document.write(age + "<br>");
document.write(isStudent + "<br>");
const PI = 3.14;
document.write(PI);
</script>
</body>
</html>
Example: String Inbuilt Methods
let text = "Apple, Banana, Kiwi";
let part = text.slice(7,13);
console.log(part);
//substring()
let part1 = text.substring(9, 17);
console.log(part1);
let text1 = "This is the first text";
console.log(text1);
let newText = text1.replace("This is ", "Overrided text ");
console.log(newText);
//toUpperCase()
let text3 = text1.toUpperCase();
console.log(text3);
//concat()
let text4 = "Am adding...!";
let text5 = text1.concat(" ", text4);
console.log(text5);
//trim()
let totrim = " Hello World! ";
let trimmed = totrim.trim();
console.log("Length totrim =" + totrim.length + " Trimmed Length = " +
trimmed.length);
Example: String Inbuilt Methods
let text = "Please locate where 'locate' occurs!";
console.log(text);
let index = text.indexOf("locate");
console.log(index);
//lastIndexOf()
let index1 = text.lastIndexOf("locate");
console.log(index1);
//search()
let index2=text.search("locate");
console.log(index2);
//startsWith()
let index3=text.startsWith("Please");
console.log(index3);
Example: Variable Substitution
let firstName = "Ethnotech";
let lastName = "Acadamics";
let text = `Welcome to ${firstName}, ${lastName}!`;
console.log(text);
let price = 10;
let VAT = 0.25;
let total = `Total: ${(price * (1 + VAT))}`;
console.log(total);
Example: Number Methods
let x1 = 123;
console.log(x1.toString() + " " + " " +(111 + 32).toString());
let x = 9.656;
//toPrecision()
console.log(x.toPrecision() + "\n "
+x.toPrecision(2) + "\n "
+ x.toPrecision(4) + "\n " +
x.toPrecision(6) );
console.log(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="events.js"></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,
}
console.log(dog)
console.log(typeof(dog))
//accessing value from an object
console.log(dog.name+" "+dog.age)
console.log(dog["name"])
console.log(dog["age"])
//adding properties to dog object
dog["color"]="brown"
console.log(dog)
//changed the value for key age
dog["age"]=30
console.log(dog)
//Object creating using new keyword
var emp=new Object();
emp.id=101;
emp.name="Ravi";
emp.salary=50000;
console.log(emp.id+" "+emp.name+" "+emp.salary);
Example: Pre-defined Objects in Javascript
//using assign()
var object1 = {a: 11, b: 12, c: 33 };
console.log(object1);
var object2 = Object.assign(object1,{c: 19, d: 5, e:4});
console.log(object2.c,object2.e, object2.d);
console.log(object2);
//using create()
const people = {
printIntroduction: function ()
{ console.log(`My name is ${this.name}. Am I human? ${this.human}`); }
};
const me = Object.create(people);
me.name = "Marry";
me.human = true;
me.printIntroduction();
//using entries()
var obj = { 1:'marrc', 2:'sort', 3:'carry' };
console.log(Object.entries(obj)[2]);
//freeze()
const object1 = { property1: 22 };
const object2 = Object.freeze(object1);
object2.property1 = 33;
console.log(object2.property1);
//getOwnPropertyDescriptor()
const object1 = { a: 42 }
const object2 = { c: 34 }
const descriptor1 = Object.getOwnPropertyDescriptor(object1, 'a');
const descriptor2 = Object.getOwnPropertyDescriptor(object2, 'c');
console.log(descriptor1.enumerable);
console.log(descriptor1.value);
console.log(descriptor2.value);
Example: Creating objects by passing constructor parameters (External.js)
//object constructor
class Fan
{
constructor(name,wings)
{ this.name=name
this.wings=wings }
rotate()
{ console.log("Fan is rotating") }
}
var f1=new Fan("Bajaj",3)
console.log(f1)
console.log(typeof(f1))
console.log(f1.name+" "+f1.wings)
f1.rotate()
//object constructor
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Yashasvi Jaiswal",30000);
console.log(e.id+" "+e.name+" "+e.salary);
Example: To over-ride value of user-defined object (External.js)
/* 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){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary; //defining method to change salary
function changeSalary(updateSal)
{
this.salary=updateSal;
}
}
e=new emp(103,"Yashasvi Jaiswal",30000);
console.log(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
console.log(e.id+" "+e.name+" "+e.salary);
Example: BOM Predefined methods (External.js)
//using open()
var win_open=function()
{
window.open("https://ethnotech.in/")
}
//using close()
var win_close=function()
{
window.close()
}
//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<emp.length;i++){
console.log(emp[i] + " ");
}
// Using new keyword
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
console.log(emp[i] + " ");
console
}
console.log(typeof(emp));
//Using Constructor
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
console.log(emp[i] + " ");
}
Example: Performing Tasks Using Array pre-defined methods
//Sorting in an Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits);
fruits.sort();
console.log(fruits);
//Reversing an Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits);
// First sort the array
fruits.sort();
console.log(fruits);
// Then reverse it:
fruits.reverse();
console.log(fruits);
//Sorting an Array
const points = [40, 100, 1, 5, 25, 10];
console.log(points);
points.sort(function(a, b){return a - b}); //if b is negative, it means 'a'
should
console.log(points); //come before 'b'
//Randomising the Array elements
const points = [40, 100, 1, 5, 25, 10];
console.log(points);
points.sort(function(){return 0.5 - Math.random()});
console.log(points);
//to find highest number in an Array using math.max
const points = [40, 100, 1, 5, 25, 10];
console.log(points);
function myArrayMax(arr) {
return Math.max.apply(null, arr);
}
console.log(myArrayMax(points));
//largest element using statements
const points = [40, 100, 1, 5, 25, 10];
console.log(points);
function myArrayMax(arr) {
let len = arr.length;
let max = -Infinity;
while (len--) {
if (arr[len] > max) {
max = arr[len];
}
}
return max;
}
console.log(myArrayMax(points) );
//using map()
const arr1 = [45, 4, 9, 16, 25];
console.log(arr1);
const arr2 = arr1.map(multi); //map() will calls the specified function
function multi(value, index, array)
{
return value * 2;
}
console.log(arr2);
// using filter()
const numbers = [45, 4, 9, 16, 25];
console.log(numbers);
const over18 = numbers.filter(myFunction);
function myFunction(value, index, array)
{
return value > 18;
}
console.log(over18);
//using reduce() to get the result of an Array
const numbers = [45, 4, 9, 16, 25];
console.log(numbers);
let sum = numbers.reduce(myFunction);
function myFunction(total, value, index, array) {
return total + value;
}
console.log("The sum is " + sum);
//using every() to check elements in an array
const numbers = [45, 4, 9, 16, 25];
console.log(numbers);
let allOver18 = numbers.every(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
console.log("all my elements over 18: " + allOver18);
//some()
let checkSome = numbers.some(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
console.log("some of my elements over 18: " + checkSome);
//index()
let position = numbers.indexOf(45) + 1;
console.log("Number is found in position " + position);
//lastIndexOf()
const fruits = ["Apple", "Orange", "Apple", "Mango"];
console.log(fruits);
let position1 = fruits.lastIndexOf("Apple") + 1;
console.log("Number is found in position " + position1);
//find()
const number = [4, 9, 16, 25, 29];
console.log(number);
let first = number.find(myFunction);
function myFunction(value, index, array) {
return value > 18;
}
console.log("First number over 18 is " + first);
//push() , pop()
const cars = ["Saab", "Volvo", "BMW"];
// Change an element:
cars[0] = "Toyota";
// Add an element:
cars.push("Audi");
console.log(cars);
cars.pop();
console.log(cars);
Example: Form validation using JavaScript
.html
<html>
<head><title>Text box validation</title></head>
<body>
<script src="textboxvalidation.js"></script>
<form onsubmit="return validate()" action="https://ethnotech.in/">
<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=document.getElementById("fname").value
if(res.length==0)
{
document.getElementById("msg").innerHTML="fname is required"
return false
}
else if(res.length<3)
{
document.getElementById("msg").innerHTML="fname should more than 3
letters"
return false
}
else if(res.length>15)
{
document.getElementById("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=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}}
</script></head>
<body>
<form name="f1" action="https://ethnotech.in/" 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="form.js"></script>
<form name="myform" method="post" action="https://ethnotech.in/"
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=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
} }
//number validation
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("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="https://www.kodnest.com/">
<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=document.getElementById("phone").value
if(res.length==0)
{ document.getElementById("msg").innerHTML="phone number is required"
return false
}
else if(isNaN(res)==true)
{
document.getElementById("msg").innerHTML="Enter only numbers...!"
return false
}
else if(res.length<10)
{ document.getElementById("msg").innerHTML="phone number should more than 3
letters"
return false
}
else if(res.length>10)
{
document.getElementById("msg").innerHTML="phone number must 10 letters"
return false
}
else if(res.charAt(0)<7)
{document.getElementById("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 {
num1.toPrecision(500);
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
</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) {
document.getElementById("demo1").innerHTML = err.name;
}
</script>
<h2>The URIError</h2>
<pre>Some characters cannot be decoded with decodeURI():</pre>
<p id="demo2"></p>
<script>
try {
decodeURI("%%%");
}
catch(err) {
document.getElementById("demo2").innerHTML = err.name;
}
</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) {
document.getElementById("demo3").innerHTML = err.name;
}
</script>
<h2>The TypeError</h2>
<pre>You cannot convert a number to upper case:</pre>
<p id="demo4"></p>
<script>
let num = 1;
try {
num.toUpperCase();
}
catch(err) {
document.getElementById("demo4").innerHTML = err.name;
}
</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
document.write(a); // displays elements of a
document.write(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 "+e.message); //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) {
document.write(e.message); // This will generate an error message
}
</script>
</body>
</html>
<!-- try…catch…finally -->
<html>
<head></head>
<body>
<script>
try{
var a=4;
if(a==2)
document.write("ok");
}
catch(Error){
document.write("Error found"+e.message);
}
finally{
document.write("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 = document.createElement("div");
var userInput = window.prompt('Enter something:');
var output = document.createElement("p");
output.appendChild(document.createTextNode('You entered: ' +
userInput));
outputContainer.appendChild(output);
document.body.appendChild(outputContainer);
</script>
</body>
</html>