JavaScript – Exercises, Practice, Solution | JavaScript programming Examples

1.   Write a program in JavaScript to print Welcome to JavaScript.
<html>
<head>
<script language=”JavaScript”>
document.write(“<font color=’red’ size=’7′ face=’monotype corsiva’>Welcome to JavaScript</font>”)
document.bgColor=”teal”
</script>
</head>
</html>

Output:

2. Write a program to add two numbers.

<html>

<head>

<title>Adding two numbers </title>

<script>

var num1 = 10;

var num2 = 40;

var sum = num1+num2;

document.write(“Sum = ” + sum);

</script>

</head>

</html>

Output:

3. Write a program to add, subtract, multiply, and divide two numbers.

<html>

<head>

<script>

 var num1=100, num2=10, result;

 result=num1+num2;

 document.write(“Add = ” + result + “<br>”);

 result=num1-num2;

 document.write(“Subtract = ” + result + “<br>”);

 result=num1*num2;

 document.write(“Multiply = ” + result + “<br>”);

 result= num1/num2;

 document.write(“Divide = ” + result + “<br>”);

</script>

</head>

</html>

Output:

4. Write a program to input value from the user using prompt.

<html>

<head>

<script>

var name=prompt(“Enter your name: “);

document.write(“Welcome “+ name);

</script>

<style>

body {

        color: #992288;

        background: #ffddff;

font-size: 20px;  }

</style>

</head>

<body>

</body>

</html>

Output:

5. Write a program in JavaScript to input an integer value and print it.

<html>

<head>

<script>

var num = prompt(“Enter an integer value:”);

document.write(“Entered integer is : “,num);

</script>

</head> 

</html>

Output:

6. Write a program to add two numbers taking input from user.

<html>

<head>

<title>Add two numbers</title>

<script language=”JavaScript”>

var num1=parseInt(prompt(“Enter first number: “));

var num2 =parseInt(prompt(“Enter second number: “));

var sum=num1+num2

alert(“Sum of “+num1+” and “+num2+” is: ” + sum)

</script>

</head>

</html>

Output:

7. Write a program to add two float values.

<html>

<head>

<script>

var num1 = 4.12, num2 = 9.87, result;

result=num1+num2;

// Without rounding the result

document.write(“Result without rounding: ” + result)

// Rounding the result to 2 digits after decimal

result = result.toFixed(2);

document.write(“<br>Result with rounding: ” + result)

</script>

</head>

</html>

Output:

8. Write a program to swap values of two variables.

<html>

<head>

<title>Swapping values of two variables</title>

<script>

//take input from the users

let a = prompt(‘Enter the value of a: ‘);

let b = prompt(‘Enter the value of b: ‘);

document.write(“Before swapping…”)

document.write(“a= “ + a + ” b= ” + b)

//create a temporary variable

let temp;

//swap variables

temp = a;

a = b;

b = temp;

document.write(“<br>After swapping…”)

document.write(“a= “ + a + ” b= ” + b)

</script>

</head>

</html>

Output:

9. Write a program to check if the number is even or odd.

<html>

<head>

<script>

// take input from the user

var num= prompt(“Enter a number: “);

//check if the number is even

if(num%2==0)

document.write(num + ” is an Even Number”);

else

document.write(num + ” is an Odd Number”);

</script>

</head>

</html>

Output-1:

Output-2:

10. Write a program to check leap year.

<html>

<head>

<script>

// take input from the user

var year=prompt(‘Enter a year: ‘);

if(year%4==0)

document.write(year + ‘ is a leap year’);

else

document.write(year + ‘ is not a leap year’)

</script>

</head>

</html>

Output:

11. Write a program to find the largest number among three numbers.

<html>

<head>

<script>

// take input from the user

var num1 = prompt(“Enter first number: “);

var num2 = prompt(“Enter second number: “);

var num3 = prompt(“Enter third number: “);

var largest;

// check the condition

if(num1>num2&& num1>num3)

largest= num1;

else if (num2>num1&&num2>num3)

largest = num2;

else

largest = num3;

// display the result

document.write(“The largest number is: ” + largest);

</script>

</head>

<html>

Output:

12. Write a program that checks if the number is positive, negative or zero.

<html>

<head>

<script>

// input from the user

var number = prompt(“Enter a number: “));

// check if number is greater than 0

if (number > 0)

document.write(“The number is positive”);

// check if number is 0

else if (number == 0)

document.write(“The number is zero”);

// if number is less than 0

else

document.write(“The number is negative”);

</script>

</head>

</html>

Output:

13. Write a program to input age and check the person is eligible for voting or not.

<html>

<head>

<script>

var age=prompt(“Enter age: “);

if(age>=18)

ans=”eligible”;

else

ans=”not eigible”;

document.write(“You are <b>”+ans+”</b> for Vote”);

</script>

</head>

</html>

Output:

14. Write a program in JavaScript using Switch Case statement.

<html>

<head>

<script>

var day,dayName;

day=parseInt(prompt(“Enter number of weekdays: “));

switch(day) {

case 1:

dayName=”Monday”;

break;

case 2:

dayName=”Tuesday”;

break;

case 3:

dayName=”Wednesday”;

break;

case 4:

dayName=”Thursday”;

break;

case 5:

dayName=”Friday”;

break;

case 6:

dayName=”Saturday”;

break;

case 7:

dayName=”Sunday”;

break;

default:

dayName=”Wrong Choice..”;

}

alert(“It is “+ dayName)

</script>

</head>

</html>

Output-1:

Output-2:

OR

<html>

<head>

<script>

var day;

switch(new Date().getDay()){

case 0:

day=”Sunday”;

break;

case 1:

day=”Monday”;

break;

case 2:

day=”Tuesday”;

break;

case 3:

day=”Wednesday”;

break;

case 4:

day=”Thursday”;

break;

case 5:

day=”Friday”;

break;

case 6:

day=”Saturday”;

}

alert(“Today is “+ day)

</script>

</head>

</html>

Output:

15. Write a program in JavaScript to print numbers from 1 to 30.

    <html>

    <head>

    <script>

    document.write(“Numbers from 1 to 30 :<br><br>”)

    for(let i=1; i<=30;i++)

    {

        document.write(i,” “);

    }

    </script>

    </head>

    </html>

    Output:

    16. Write a JavaScript program to find the Sum of Natural Numbers.

    <html>

    <head>

    <script>

    // take input from the user

    let num=parseInt(prompt(‘Enter a positive integer: ‘));

    let sum=0;

    for(let i=1; i<=num;i++) {

        sum+= i;

    }

    document.write(‘The sum of ‘,num,’ natural numbers:’, sum);

    </script>

    </head>

    </html>

    Output:

    17. Write a program to add n numbers using array.

    <html>

    <head>

    <script>

    var i,sum=0;

    arr=new Array(20, 22, 13, 15, 19);

    for(i=0; i<5; i++) {

    sum = sum + arr[i];

     }

    document.write(“Sum of 5 numbers: ” + sum);

    </script>

    </head>

    </html>

    Output:

    18. Write a program to demonstrate Popup Boxes in JavaScript.

    <html>

    <head>

    <title>Popup Boxes in JavaScript</title>

    <script>

    alert(“This is an example of alert box!”);

    confirm(“It is a Confirm popup box!”);

    var name=prompt(“This is a prompt box!”, “Enter your name: “);

    alert(“Welcome “+ name);

    </script>

    </head>

    <body style=”background-color:seagreen”>

    <h1 style=”text-align:center;color: #FFFF00;background: #EE82EE;font-size: 30px;”>JavaScript Example to Demonstrate Popup Boxes!</h1>

    </body>

    </html>

    Output:

    19. Write a program in JavaScript using Date, Day and Time methods.

    <html>

    <head>

    <script language=”JavaScript”>

    RightNow=new Date();

    document.write(“Today’s date is ” + (RightNow.getMonth()+1) + “-” + RightNow.getDate() + “-” + RightNow.getFullYear())

    document.write(“<br>You entered this web page at exactly: ” + RightNow.getHours() + “:” + RightNow.getMinutes() + ” and ” + RightNow.getSeconds() + ” seconds”);

    </script>

    </head>

    </html>

    Output:

    20. Write a JavaScript program using user defined function.

    <html>

    <head>

    <script>

    function displayMessage() {

     document.write(“Welcome to JavaScript World”);

    }

    displayMessage();

    </script>

    </head>

    </html>

    Output:

    21. Write a program to use button and pass parameter to a function.

    <html>

    <head>

    <script language=”javascript”>

    function newcolor(color)

    {

    alert(“You Choose ” + color)

    document.bgColor=color

    }

    </script>

    </head>

    <body>

    <h1>Select a background color</h1>

    <form>

    <input type=”button” value=”Pink” onClick=”newcolor(‘pink’)”>

    <input type=”button” value=”Violet” onClick=”newcolor(‘violet’)”>

    </form>

    </body>

    </html>

    Output:

    22. Write a program in JavaScript to demonstrate Animation.

    (Following Exercise demonstrate animation by calling script from another script. Copy any five image files to your current directory so that these files can be used in this exercise.)

    <html>

    <head>

    <SCRIPT LANGUAGE =”JavaScript”>

    num=0

    img1=new Image()

    img1.src=”pic1.jpg”

    img2=new Image()

    img2.src=”pic2.png”

    img3=new Image()

    img3.src=”pic3.jpg”

    img4=new Image()

    img4.src=”pic4.png”

    img5=new Image()

    img5.src=”th.jpg”

    img6=new Image()

    img6.src=”img.jpg”

    function startanimation()

    {

    num=num+1

    if(num>6)

    num=1

    document.mypic.src=eval(“img”+num+”.src”)

    setTimeout(“startanimation()”,500)

    document.bgColor=”teal”

    }

    </script>

    </head>

    <body>

    <center>

    <img src=”pic1.jpg” name=”mypic” border=”0″>

    <script language=”javascript”>

    startanimation()   //calling script from another script

    </script>

    </center>

    </body>

    </html>

    Output:

    23. Exercise to present a slide show. (Copy any 3 picture files to your folder so that these files can be used in the place of pic1.jpg, pic2.jpg, pic3.jpg and pic4.jpg as done in this exercise.)

    <HTML>

    <HEAD>

    <SCRIPT LANGUAGE =”JavaScript”>

    num=1

    img1=new Image()

    img1.src=”pic1.jpg”

    img2=new Image()

    img2.src=”pic2.png”

    img3=new Image()

    img3.src=”pic3.jpg”

    img4=new Image()

    img4.src=”pic4.png”

    function slideshow()

    {

    document.mypic.src=eval(“img”+num+”.src”)

    num=num+1

    if(num>=4)

    num=1

    }

    </SCRIPT>

    </HEAD>

    <BODY>

    <CENTER>

    <IMG SRC=”pic4.png” NAME=”mypic” BORDER=4>

    <p><A HREF=”JavaScript:slideshow()”>Click for next picture</A>

    </CENTER>

    </BODY>

    </HTML>

    Output:

    24. Write a JavaScript program using Windows and Functions.

    <html>

    <head>

    <script language=”javascript”>

    function dca()

    { var d=window.open(“”,”dcaWin”,”height=400, width=400,menubar=yes”);

      with(d.document)

      {   write(“<html><head><title>New Window</title></head>”)

          write(“<body bgColor=’pink’><p>Diploma in Computer Applications<p><ul><li>Information Technology <li>MS Office with MS Access <li>Programming in C <li>Business System <li>My-SQL <li>Webpage Design <li>Web Publishing <li>HTML,CSS,Java Script</ul><p>You can close this Window by clicking on the button “)

          write(“<a href=” onClick=self.close()>Close Window</a>”)

          write(“</body></html>”)

       }

    }

    function adca()

    { var j=window.open(“”,”AdcaWin”,”height=400, width=400,menubar=yes”);

      with(j.document)

      {   write(“<html><head><title>New Window</title></head>”)

          write(“<body bgColor=’aqua’><p>Advanced Diploma in Computer Application<p><ul><li>Information Technology <li>MS Office with MS Access <li>Linux <li>Cascading Style Sheet (CSS) <li>Database Management with MySql <li>Programming with Python <li>Internet Technology and Webpage Design <li>HTML,Java Script</ul><p>You can close this Window by clicking on the button “)

          write(“<a href=” onClick=self.close()>Close Window</a>”)

          write(“</body></html>”)

       }

    }

    function pgdcsa()

    { var c=window.open(“”,”PgdcsaWin”,”height=400, width=400,menubar=yes”);

      with(c.document)

      {   write(“<html><head><title>New Window</title></head>”)

          write(“<body bgColor=’blue’><p>Post Graduate Diploma in Computer Science and Application<p><ul><li>IT Tools and Business System <li>Computer System Architecture <li>Programming with C and C++ Language <li>Systems Concept & Introduction to Database Management <li>Data Structure using ‘C++'<li>Computer Network & Web Technologies <li>Introduction to Open Source using Linux <li>Object Oriented Programming Using Java</ul><p>You can close this Window by clicking on the button “)

          write(“<a href=” onClick=self.close()>Close Window</a>”)

          write(“</body></html>”)

       }

    }

    </script>

    </head>

    <body bgcolor=”black” text=”white”>

    <center>

    <h1>Welcome to DCC (District Computer Center</h1>

    <font size=”5″>

    <p>We Offer the following Courses:

    <form>

    <input type=”button” name=”b1″ value=”DCA” onClick=”dca()”>

    <input type=”button” name=”b2″ value=”ADCA” onClick=”adca()”>

    <input type=”button” name=”b3″ value=”PGDCSA” onClick=”pgdcsa()”>

    </form>

    </body>

    </html>

    Output:

    Leave a Comment