Sei sulla pagina 1di 12

Hello and fuck of

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?

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

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

</head>

<body></body>

</html>

JavaScript Code :

view plaincopy to clipboardprint?

var today = new Date();

var day = today.getDay();

var daylist = ["Sunday","Monday","Tuesday","Wednesday ","Thursday","Fri


day","Saturday"];

console.log("Today is : " + daylist[day] + ".");

var hour = today.getHours();

var minute = today.getMinutes();

var second = today.getSeconds();

var prepand = (hour >= 12)? " PM ":" AM ";

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 + " : " + seco
nd);

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?

<!DOCTYPE html>

<html>

<head>

<meta charset=utf-8 />

<title>Print the current page.</title>

</head>

<body>

<p></p>

<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?

function print_current_page()

window.print();

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?

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

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

</head>

<body>

</body>

</html>

10

JavaScript Code :

view plaincopy to clipboardprint?

var today = new Date();

var dd = today.getDate();

3
4

var mm = today.getMonth()+1;

var yyyy = today.getFullYear();

if(dd<10)

8
9

dd='0'+dd;
}

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
2

<!DOCTYPE html>
<html>

<head>

<title>JavaScript basic animation</title>

<script type="text/javascript">

</script>

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

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

</body>

10

</html>

JavaScript Code :

view plaincopy to clipboardprint?

function animate_string(id)

var element = document.getElementById(id);

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

var text = textNode.data;

6
7

setInterval(function ()

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?

<!DOCTYPE html>

<html>

<head>

<meta charset=utf-8 />

<title>A Program to find 1st January <span class="heading">is being </


span>a Sunday between 2014 and 2050.</title>

</head>

<body>

</body>

</html>

JavaScript Code :

view plaincopy to clipboardprint?

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

for (var year = 2014; year <= 2050; year++)

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

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

6
7
8

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


}
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?

<!DOCTYPE html>

<html>

<head>

<meta charset=utf-8 />

<title>Guess a number</title>

</head>

<body>

</body>

</html>

JavaScript Code :

view plaincopy to clipboardprint?

// Get a random integer from 1 to 10 inclusive

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

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

if (gnum == num)

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?

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>Write a JavaScript program to get the website URL (loading page)<


/title>

</head>

<body>

</body>

</html>

JavaScript Code :

view plaincopy to clipboardprint?

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

alert(document.URL);

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

Potrebbero piacerti anche