*Programs*
#advanced
1.call
//Calls (executes) a function and sets its this to the provided value, arguments can be passed as they are.
var firstName=
name:"Thomas",
sayHello:function(name)
console.log(name+" "+this.name);
var lastName=
name:"Edison"
firstName.sayHello.call(lastName,"Thomas");
// call ([thisObj, [arg1[, arg2[, [, argN]]]]])
// thisObj [Optional] : The object to be used as the current object.
// arg1, arg2, argN : Optional. A list of arguments to be passed to the method.
2.closure
// A closure is an inner function that has access to the outer (enclosing) function’s variables—scope
chain.
//The closure has three scope chains (its own scope,outer function’s variables,global variables).
function showName(firstName,lastName)
var nameIntro="Your name is :";
// this inner function has access to the outer function's variables, including the parameter.
function makeFullName()
return nameIntro+firstName+" "+lastName;
return makeFullName();
showName("michael","action");
3.global scope
// A global variable has global scope means all scripts and functions on a web page can access it.
var Name="Michel";
getName();
//Here, getName using 'Name' variable is declared in global scope.
function getName()
console.log("My name is "+Name);
4.bind
// If we assign a method that uses “this” to a variable, then “this” will have value of the global data array,
and not the data array of the user object.
//solution is bind() method.
// Example showing binding some parameters
var sum=function(a, b)
return a + b;
};
var add5=sum.bind(null, 5);
console.log(add5(10));
5.local variabel
//Variables declared within a JavaScript function, become LOCAL to the function.
//In following example,'Name' is a LOCAL variable.
function writeName()
var Name = "Michel";
console.log("I am " + Name);
writeName();
6.objects
// A JavaScript object is an unordered collection of variables called named values.
var person = {
firstname : "Bob",
lastname : "Marley",
age : 50
};
console.log("Your name is "+person.firstname+" "+person.lastname+".Age is "+person.age);
7.this
//this keyword gets the value of the object that invokes the function where this is used.
var person={
firstName:"Harry",
lastName:"Edison",
fullName:function()
{
console.log(this.firstName + " " + this.lastName);
console.log(person.firstName + " " + person.lastName);
person.fullName();
8.this in global scope
var firstName = "Harry",
lastName = "Edison";
function showFullName ()
//"this" inside this function will have the value of the window object
console.log (this.firstName + " " + this.lastName);
var person =
firstName :"Mary",
lastName :"Thomas",
showFullName : function ()
{
//"this" on the line below refers to the person object, because
//the showFullName function will be invoked by person object.
console.log (this.firstName + " " + this.lastName);
showFullName (); // Harry Edison
window.showFullName (); // Harry Edison
person.showFullName (); // Mary Thomas
#basic
1.calling function
<!DOCTYPE html>
<html>
<body>
<h1>Calling a function</h1>
<p id="myPar">I am a paragraph.</p>
<div id="myDiv">I am a div.</div>
<p>
<button type="button" onclick="myFunction()">Change</button>
</p>
<script>
function myFunction() {
document.getElementById("myPar").innerHTML = "Hello";
document.getElementById("myDiv").innerHTML = "How are you?";
</script>
<p>When you click on "Change", the two elements will change.</p>
</body>
</html>
2.apply
// The apply() method allows to borrow functions /switch the context and set the this value in function
invocation.
// It allows an object to use another object's.method for its own designs.
var person=
firstName :"Harry",
lastName :"Edison",
showFullName :function()
//The "context"
console.log(this.firstName + " " + this.lastName);
}
};
//when we invoke showFullName() on the person object, the context becomes person object.
person.showFullName(); //Harry Edison
//another object
var anotherPerson=
firstName :"Mary",
lastName :"Thomas"
};
//By using apply() method, "this" gets the value of whichever object invokes the "this" function
person.showFullName.apply(anotherPerson);//Mary Thomas
//So the context is now anotherPerson
3.change html elements
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Change HTML</h1>
<p id="demo">This is a para.</p>
<script>
document.getElementById("demo").innerHTML = "Changed Para.";
</script>
</body>
</html>
4.hello world
<html>
<body>
<script>
document.write("Hello World");
</script>
</body>
</html>
5.Multiline commens
<!DOCTYPE html>
<html>
<body>
<h1 id="myHeader"></h1>
<p id="myPara"></p>
<script>
/*
document.getElementById("myHeader").innerHTML = "Welcome to JavaScript";
document.getElementById("myPara").innerHTML = "This is a paragraph.";
*/
</script>
<p>
<strong>Note:</strong> The comments are not executed.
</p>
</body>
</html>
6.singleline commens
<!DOCTYPE html>
<html>
<body>
<h1 id="myHeader"></h1>
<p id="myPara"></p>
<script>
// Write to a heading:
document.getElementById("myHeader").innerHTML = "Welcome to JavaScript";
// Write to a paragraph:
document.getElementById("myPara").innerHTML = "This is a paragraph.";
</script>
<p>
<strong>Note:</strong> The comments are not executed.
</p>
</body>
</html>
7.using a variable
<!DOCTYPE html>
<html>
<body>
<script>
var firstname;
firstname = "Goku";
document.write(firstname);
document.write("<br>");
firstname = "Krillin";
document.write(firstname);
</script>
<p>The script above declares a variable, assigns a value to it,
displays the value, changes the value, and displays the value again.</p>
</body>
</html>
8.writting to the document
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Example</h1>
<script>
document.write("<p>This is a paragraph</p>");
</script>
</body>
</html>
#conditional
1.if else example
<!DOCTYPE html>
<html>
<body>
<p>
If time is less than 16 it will show "Have a nice day".
<br />
else it will show "Good night".
</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = "";
var time = new Date().getHours();
if (time < 16) {
x = "Have a nice day";
} else {
x = "Good night";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
2.if example
<!DOCTYPE html>
<html>
<body>
<p>
Click the button to get a "Have a nice day" greeting if the time is
less than 21:00.
<br />
If the time is greater than 21:00 the greeting
will not be displayed.
</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = "";
var time = new Date().getHours();
if (time < 21) {
x = "Have a nice day";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
3.switch statement
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display what day it is today.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
var x;
var d = new Date().getDay();
switch (d) {
case 0:
x = "Today is Sunday";
break;
case 1:
x = "Today is Monday";
break;
case 2:
x = "Today is Tuesday";
break;
case 3:
x = "Today is Wednesday";
break;
case 4:
x = "Today is Thursday";
break;
case 5:
x = "Today is Friday";
break;
case 6:
x = "Today is Saturday";
break;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
#error handling
1.oneerror event example
<!DOCTYPE html>
<html>
<head>
<script>
onerror = handleErr;
var txt = "";
function handleErr(msg, url, l) {
txt = "There was an error on this page.\n\n";
txt += "Error: " + msg + "\n";
txt += "URL: " + url + "\n";
txt += "Line: " + l + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
return true;
function message() {
alertMe("Welcome guest!");
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
2.try catch example
<!DOCTYPE html>
<html>
<head>
<script>
var txt = "";
function message() {
try {
alertMe("Welcome guest!");
} catch (err) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
3.try catch with confirm box
<!DOCTYPE html>
<html>
<head>
<script>
var txt = "";
function message() {
try {
adddlert("Welcome guest!");
} catch (err) {
txt = "There was an error on this page.\n\n";
txt += "Click OK to continue viewing this page,\n";
txt += "or Cancel to return to the home page.\n\n";
if (!confirm(txt)) {
//action on confirm
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
#function
1.function that returns velue
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
return ("Hello world!");
</script>
</head>
<body>
<script>
document.write(myFunction())
</script>
</body>
</html>
2.function with argument and return velue
<!DOCTYPE html>
<html>
<body>
<p>This example calls a function which performs a calculation, and
returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {
return a * b;
document.getElementById("demo").innerHTML = myFunction(4, 5);
</script>
</body>
</html>
3.function with one argument
<!DOCTYPE html>
<html>
<head>
<script>
function myfunction(txt) {
alert(txt);
</script>
</head>
<body>
<form>
<input type="button" onclick="myfunction('Good Morning!')"
value="It's Morning"> <input type="button"
onclick="myfunction('Good Evening!')" value="It's Evening">
</form>
<p>When you click on one of the buttons, a function will be called.
The function will alert the argument that is passed to it.</p>
</body>
</html>
4.function with two argument
<!DOCTYPE html>
<html>
<body>
<p>Click the button to call a function with arguments</p>
<button onclick="myFunction('Goku','Saiyan')">Click me</button>
<script>
function myFunction(name, job) {
alert("Welcome " + name + ", the " + job + "!!");
</script>
</body>
</html>
#loop
1.break statement
<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a loop with a break.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = "", i = 0;
for (i = 0; i < 10; i++) {
if (i == 3) {
break;
x = x + "number = " + i + "<br>";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
2.continue statement
<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a loop which will skip the step where i =
3.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = "", i = 0;
for (i = 0; i < 10; i++) {
if (i == 3) {
continue;
x = x + "number = " + i + "<br>";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
3.do while loop
<!DOCTYPE html>
<html>
<body>
<p>
Click the button to loop through a block of as long as <em>i</em> is
less than 5.
</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = "", i = 0;
do {
x = x + "number = " + i + "<br>";
i++;
} while (i < 5)
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
4.for in loop/enhanced for loop
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var txt = "";
var person = {
fname : "John",
lname : "Doe",
age : 20
};
for ( var x in person) {
txt = txt + " " + person[x];
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
5.for loop with array
<!DOCTYPE html>
<html>
<body>
<script>
fruits = [ "Apple", "Mango", "Banana", "Grapes" ];
for (var i = 0; i < fruits.length; i++) {
document.write(fruits[i] + "<br>");
</script>
</body>
</html>
6.looping through html headers
<!DOCTYPE html>
<html>
<body>
<p>Click the button to loop from 1 to 6, to make HTML headings.</p>
<button onclick="myFunction()">Click me</button>
<div id="demo"></div>
<script>
function myFunction() {
var x = "", i;
for (i = 1; i <= 6; i++) {
x = x + "<h" + i + ">Heading " + i + "</h" + i + ">";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
7.simple for loop
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var x = "";
for (var i = 0; i < 5; i++) {
x = x + "number = " + i + "<br>";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
8.while loop
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var x = "", i = 0;
while (i < 5) {
x = x + "number = " + i + "<br>";
i++;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
#numbers
1.fibonnaci
<html>
<body>
<script type="text/javascript">
var a = 0, b = 1, c = 0;
document.write("Fibonacci Series<br/>");
while (b <= 20) {
document.write(c);
document.write("<br/>");
c = a + b;
a = b;
b = c;
</script>
</body>
</html>
2.leap year
<html>
<body>
Enter Year: <input type="number" id="year"/> <br><br>
<input type="button" onclick="leapYear()" value="Check"/> <br><br>
Result : <h3 id="res"> </h3>
<script>
function leapYear()
{
var yr=document.getElementById('year').value;
x = (yr % 100 === 0) ? (yr % 400 === 0) : (yr % 4 === 0);
if(x==true)
document.getElementById('res').innerHTML="Leap Year";
else{
document.getElementById('res').innerHTML="Not a Leap Year";
</script>
</body>
</html>
3.palindrome
<html>
<body>
<script type="text/javascript">
function Palindrome() {
var revStr = "";
var str = document.getElementById("str").value;
var i = str.length;
for (var j = i; j >= 0; j--) {
revStr = revStr + str.charAt(j);
if (str == "") {
alert("Please Enter a number or some text");
else if (str == revStr) {
alert(str + " is Palindrome");
} else {
alert(str + " is not a Palindrome");
</script>
<form>
Enter a String/Number: <input type="text" id="str" name="string" /><br />
<input type="button" value="Check" onclick="Palindrome();" />
</form>
</body>
</html>
4.prime number
function Prime(max)
var temp = [], i, j, primes = [];
for (i = 2; i <= max; ++i)
if (!temp[i])
// i has not been marked -- it is prime
primes.push(i);
for (j = i << 1; j <= max; j += i)
temp[j] = true;
return primes;
}
Prime(50);
5.random numbers
//Math.floor(Math.random() * end_number) + start_number
Math.floor(Math.random() * 10) + 1
6.swap numbers with two variables only
<html>
<body>
<script>
a=10;
b=15;
document.write("Values before swipe :<br>");
document.write("a="+a+" and b="+b+"<br>");
//------Method 1 Using add and subtract -----
a=a+b;
b=a-b;
a=a-b;
document.write("---- Using Method 1 ----<br>");
document.write("a="+a+" and b="+b+"<br>");
//------Method 2 Using XOR operation------
a=10;
b=15;
a=a^b;
b=a^b;
a=a^b;
document.write("---- Using Method 2 ----<br>");
document.write("a="+a+" and b="+b+"<br>");
//-----Method 3 Using Multiplication and division----
a=10;
b=15;
a=a*b;
b=a/b;
a=a/b;
document.write("---- Using Method 3 ----<br>");
document.write("a="+a+" and b="+b+"<br>");
//-----Method 4 Using formula a=b-a+(b=a) -----
/*
Working of Formula :
Browser first evaluates (b=a) expression based on BODMAS rule
then b-a expression
So a=15-10+(10)=15 and b=10
*/
a=10;
b=15;
a=b-a+(b=a) ;
document.write("---- Using Method 4 ----<br>");
document.write("a="+a+" and b="+b+"<br>");
</script>
</body>
</html>
#popup
1.alert example
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display an alert box.</p>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
alert("I am an alert box!");
</script>
</body>
</html>
2.alert with line breaks
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate line-breaks in a popup box.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
alert("Hello\nHow are you?");
</script>
</body>
</html>
3.confirm example
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a confirm box.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
var x;
var r = confirm("Press a button!");
if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
4.promt example
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
var x;
var person = prompt("Please enter your name", "BatMan");
if (person != null) {
x = "Hello " + person + "! How are you today?";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>