You are on page 1of 10

Kuch nai hone wala tumhara..

ek din muth maar k mar


jaoge
JavaScript exercises and solutions

1. Write a JavaScript program to display the current day and time in the following format.
Today is : Friday.
Current time is : 4 PM : 50 : 22
Sample Solution : HTML Code :
view plaincopy to clipboardprint?

1. <!DOCTYPE html>
2.

<html>

3.

<head>

4.

<meta charset="utf-8">

5.

<title>JavaScript current day and time</title>

6.

</head>

7.

<body></body>

8. </html>

JavaScript Code :

view plaincopy to clipboardprint?

1. var today = new Date();


2. var day = today.getDay();
3. var daylist = ["Sunday","Monday","Tuesday","Wednesday ","Thursday","Friday","Saturday"]
;
4. console.log("Today is : " + daylist[day] + ".");
5. var hour = today.getHours();
6. var minute = today.getMinutes();
7. var second = today.getSeconds();
8. var prepand = (hour >= 12)? " PM ":" AM ";
9. hour = (hour >= 12)? hour - 12: hour;

10. if (hour===0 && prepand===' PM ')


11. {
12. if (minute===0 && second===0)
13. {
14. hour=12;
15. prepand=' Noon';
16. }
17. else
18. {
19. hour=12;
20. prepand=' PM';
21. }
22. }
23. if (hour===0 && prepand===' AM ')
24. {
25. if (minute===0 && second===0)
26. {
27. hour=12;
28. prepand=' Midnight';
29. }
30. else
31. {
32. hour=12;
33. prepand=' AM';
34. }
35. }
36. nsole.log("Current Time : "+hour + prepand + " : " + minute + " : " + second);

Explanation :

Declaring a JavaScript date : In JavaScript Date objects are based on a time value that is
the number of milliseconds since 1 January, 1970 UTC. You can declare a date in the
following ways :
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);

The getDay() method is used to get the day of the week for the specified date according to
local time, where 0 represents Sunday. The value returned by getDay() is an integer
corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so
on.
The getHours() method is used to get the hour for a given date, according to local time.
The value returned by getHours() is an integer between 0 and 23.
The getMinutes() method is used to get the minutes in the specified date according to local
time. The value returned by getMinutes() is an integer between 0 and 59.
The getSeconds() method is used to get the seconds in the specified date according to
local time. The value returned by getSeconds() is an integer between 0 and 59.
AM and PM : AM stands for 'ante meridiem', which means 'before noon' in Latin, while PM
stands for 'post meridiem', which means 'after noon' in Latin.
12-Hour Periods : Nowadays most clocks are 12-hour clocks they divide the 24 hours in
a day into two 12-hour periods.
Ante meridiem: Before noon - Between midnight (0:00) & noon (12:00)
Post meridiem: After noon Between noon (12:00) & midnight (0:00)

2. Print the contents of the current window.


Sample Solution : HTML Code :
view plaincopy to clipboardprint?

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset=utf-8 />
5. <title>Print the current page.</title>
6. </head>

7. <body>
8. <p></p>
9. <p>Click the button to print the current page.</p>
10. <button onclick="print_current_page()">Print this page</button>
11. </body>
12. </html>

JavaScript Code :

view plaincopy to clipboardprint?

1. function print_current_page()
2. {
3. window.print();
4. }

Explanation :
window.print() : The window object represents a window containing a DOM document; the
document property points to the DOM document loaded in that window, window.print() is
used to open the Print Dialog to print the current document.

3. Write a JavaScript program to get the current date.


Expected Output :
mm-dd-yyyy, mm/dd/yyyy or dd-mm-yyyy, dd/mm/yyyy
Sample Solution : HTML Code :
view plaincopy to clipboardprint?

1. <!DOCTYPE html>
2.

<html>

3.

<head>

4.

<meta charset="utf-8">

5.

<title>Write a JavaScript program to get the current date.</title>

6.

</head>

7.

<body>

8.

</body>

9.

</html>

10.

JavaScript Code :

view plaincopy to clipboardprint?

1. var today = new Date();


2. var dd = today.getDate();
3.
4. var mm = today.getMonth()+1;
5. var yyyy = today.getFullYear();
6. if(dd<10)
7. {
8.

dd='0'+dd;

9. }
10.
11. if(mm<10)
12. {
13.

mm='0'+mm;

14. }
15. today = mm+'-'+dd+'-'+yyyy;
16. console.log(today);
17. today = mm+'/'+dd+'/'+yyyy;
18. console.log(today);
19. today = dd+'-'+mm+'-'+yyyy;
20. console.log(today);
21. today = dd+'/'+mm+'/'+yyyy;
22. console.log(today);

Explanation :

Declaring a JavaScript date : In JavaScript Date objects are based on a time value that is
the number of milliseconds since 1 January, 1970 UTC. You can declare a date in the
following ways :
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);

The getDate() method is used to get the day of the month for the specified date according
to local time. The value returned by getDate() is an integer between 1 and 31.
The getMonth() method returns the month in the specified date according to local time, as
a zero-based value (where zero indicates the first month of the year). The value returned
by getMonth() is an integer between 0 and 11. 0 corresponds to January, 1 to February,
and so on.
The getFullYear() method is used to get the year of the specified date according to local
time. The value returned by the method is an absolute number. For dates between the
years 1000 and 9999, getFullYear() returns a four-digit number, for example, 1985.

4. Rotate the string 'w3resource' in right direction by periodically removing one letter from
the end of the string and attaching it to the front.
Sample Solution : HTML Code :
view plaincopy to clipboardprint?

1. <!DOCTYPE html>
2.

<html>

3.

<head>

4.

<title>JavaScript basic animation</title>

5.

<script type="text/javascript">

6.

</script>

7.

</head> <body onload="animate_string('target')"

8.

<pre id="target">w3resource </pre>

9.

</body>

10. </html>

JavaScript Code :

view plaincopy to clipboardprint?

1. function animate_string(id)
2. {
3.

var element = document.getElementById(id);

4.

var textNode = element.childNodes[0]; // assuming no other children

5.

var text = textNode.data;

6.
7. setInterval(function ()
8. {
9.

text = text[text.length - 1] + text.substring(0, text.length - 1);

10. textNode.data = text;


11. }, 100);
12. }

Explanation :
document.getElementById(id) : Returns a reference to the element by its ID; the ID is a
string which can be used to identify the element; it can be established using the id attribute
in HTML, or from script.
Parameters : id is a case-sensitive string representing the unique ID of the element being
sought.
element.childNodes[0] will produce the same result as the HTML content of the first child
node.
text.length : The length property represents the length of a string. It returns the number of
code units in the string.

5. Write a JavaScript program to find which 1st January is being a Sunday between 2014
and 2050.
Sample Solution : HTML Code :
view plaincopy to clipboardprint?

1. <!DOCTYPE html>
2. <html>

3. <head>
4. <meta charset=utf-8 />
5. <title>A Program to find 1st January <span class="heading">is being </span>a Sunday
between 2014 and 2050.</title>
6. </head>
7. <body>
8. </body>
9. </html>

JavaScript Code :

view plaincopy to clipboardprint?

1. console.log('--------------------');
2. for (var year = 2014; year <= 2050; year++)
3.

4.

var d = new Date(year, 0, 1);

5.

if ( d.getDay() === 0 )

6.
7.

console.log("1st January is being a Sunday "+year);


}

8. console.log('--------------------');

Explanation :
Declaring a JavaScript date : In JavaScript Date objects are based on a time value that is
the number of milliseconds since 1 January, 1970 UTC. You can declare a date in the
following ways :
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);

The getDay() method is used to get the day of the week for the specified date according to
local time, where 0 represents Sunday. The value returned by getDay() is an integer
corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so
on.

6. Write a JavaScript program where the program takes a random integer between 1 to 10,
the user is then prompted to input a guess number. If the user input matches with guess
number, the program will display a message "Good Work" otherwise display a message
"Not matched"
Sample Solution : HTML Code :
view plaincopy to clipboardprint?

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset=utf-8 />
5. <title>Guess a number</title>
6. </head>
7. <body>
8. </body>
9. </html>

JavaScript Code :

view plaincopy to clipboardprint?

1. // Get a random integer from 1 to 10 inclusive


2.

var num = Math.ceil(Math.random() * 10);

3.

var gnum = prompt('Guess the number between 1 and 10 inclusive');

4.

if (gnum == num)

5.

alert('Matched');

6.
7.

else
alert('Not matched, the number was ' + num);

Explanation :
The Math.ceil() function is used to get the smallest integer greater than or equal to a given
number.
The Math.random() function is used to get a floating-point, pseudo-random number in the
range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can
then scale to your desired range.

7. Write a JavaScript program to get the website URL (loading page).


Sample Solution : HTML Code :
view plaincopy to clipboardprint?

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="utf-8">
5. <title>Write a JavaScript program to get the website URL (loading page)</title>
6. </head>
7. <body>
8. </body>
9. </html>

JavaScript Code :

view plaincopy to clipboardprint?

1. //Write a JavaScript program to get the website URL (loading page)


2. alert(document.URL);

Explanation :
document.URL : The URL read-only property of the Document interface returns the
document location as a string.