JavaScript is the programming language of HTML and the Web.
<!DOCTYPE html>
<html>
<body>
<h2>My First JavaScript</h2>
<button type="button"
onclick="document.getElementById('demo').innerHTML =
Date()">
Click me to display Date and Time.</button>
<p id="demo"></p>
</body>
</html>
Why Study JavaScript?
JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages
JavaScript Introduction
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().
This example uses the method to "find" an HTML element (with id="demo") and
changes the element content (innerHTML) to "Hello JavaScript":
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>
</body>
</html>
JavaScript accepts both double and single quotes:
JavaScript Can Change HTML Attributes
This example changes an HTML image by changing the src (source) attribute
of an <img> tag:
1
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attributes.</p>
<p>In this case JavaScript changes the src (source) attribute of an image.</p>
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the
light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the
light</button>
</body>
</html>
What Can JavaScript Do?
JavaScript can change HTML attributes.
In this case JavaScript changes the src (source) attribute of an image.
Turn on the light Turn off the light
JavaScript Can Change HTML Styles (CSS)
Changing the style of an HTML element, is a variant of changing an HTML attribute:
Example
document.getElementById("demo").style.fontSize = "25px";
or
document.getElementById('demo').style.fontSize = '25px';
2
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click
Me!</button>
</body>
</html>
JavaScript Can Hide HTML Elements
Hiding HTML elements can be done by changing the display style:
Example
document.getElementById("demo").style.display = "none";
or
document.getElementById('demo').style.display = 'none';
JavaScript Can Show HTML Elements
Showing hidden HTML elements can also be done by changing the display style:
Example
document.getElementById("demo").style.display = "block";
or
document.getElementById('demo').style.display = 'block';
The <script> Tag
In HTML, JavaScript code must be inserted between <script> and </script> tags.
Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
3
</script>
</body>
</html>
JavaScript Functions and Events
A JavaScript function is a block of JavaScript code, that can be executed when
"called" for.
For example, a function can be called when an event occurs, like when the user
clicks a button.
JavaScript in <head> or <body>
You can place any number of scripts in an HTML document.
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
4
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML
page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
External JavaScript
Scripts can also be placed in external files:
External file: myScript.js
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
External scripts are practical when the same code is used in many different
web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source)
attribute of a <script> tag:
5
Example
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where the <script> tag is located.
External JavaScript Advantages
Placing scripts in external files has some advantages:
It separates HTML and code
It makes HTML and JavaScript easier to read and maintain
Cached JavaScript files can speed up page loads
To add several script files to one page - use several script tags:
Example
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
External References
External scripts can be referenced with a full URL or with a path relative to the
current web page.
This example uses a full URL to link to a script:
Example
<script src="https://www.w3schools.com/js/myScript1.js"></script>
This example uses a script located in a specified folder on the current web site:
Example
<script src="/js/myScript1.js"></script>
This example links to a script located in the same folder as the current page:
Example
<script src="myScript1.js"></script>
6
JavaScript Output
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
Writing into an HTML element, using innerHTML.
Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
Using innerHTML
To access an HTML element, JavaScript can use
the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines
the HTML content:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
7
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using document.write() after an HTML document is fully loaded, will delete
all existing HTML:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button onclick="document.write(5 + 6)">Try it</button>
</body>
</html>
Using window.alert()
You can use an alert box to display data:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
8
Using console.log()
For debugging purposes, you can use the console.log() method to display data.
You will learn more about debugging in a later chapter.
Example
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed.
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by the computer.
In a programming language, these program instructions are called statements.
JavaScript is a programming language.
JavaScript statements are separated by semicolons:
Example
var x, y, z;
x = 5;
y = 6;
z = x + y;
In HTML, JavaScript programs are executed by the web browser.
9
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>Statements are separated by semicolons.</p>
<p>The variables x, y, and z are assigned the values 5, 6, and 11.</p>
<p>Then the value of z is displayed in the paragraph below:</p>
<p id="demo"></p>
<script>
var x, y, z;
x = 5;
y = 6;
z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
</body>
</html>
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments
JavaScript Values
The JavaScript syntax defines two types of values: Fixed values and variable
values.
Fixed values are called literals. Variable values are called variables.
JavaScript Literals
The most important rules for writing fixed values are:
Numbers are written with or without decimals:
10.50
1001
Strings are text, written within double or single quotes:
"John Doe"
'John Doe'
10
JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the var keyword to declare variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
var x;
x = 6;
JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10
JavaScript uses an assignment operator ( = ) to assign values to
variables:
var x, y;
x = 5;
y = 6;
JavaScript Expressions
An expression is a combination of values, variables, and operators, which computes
to a value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:
5 * 10
Expressions can also contain variable values:
x * 10
The values can be of various types, such as numbers and strings.
For example, "John" + " " + "Doe", evaluates to "John Doe":
"John" + " " + "Doe"
11
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
The var keyword tells the browser to create variables:
var x, y;
x = 5 + 6;
y = x * 10;
JavaScript Comments
Not all JavaScript statements are "executed".
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
var x = 5; // I will be executed
// var x = 6; I will NOT be executed
JavaScript Identifiers
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and functions,
and labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, or an underscore (_), or a dollar
sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
Numbers are not allowed as the first character.
This way JavaScript can easily distinguish identifiers from numbers.
JavaScript is Case Sensitive
All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different variables.
var lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
JavaScript and Camel Case
Historically, programmers have used different ways of joining multiple words into
one variable name:
Hyphens:
first-name, last-name, master-card, inter-city.
12
Hyphens are not allowed in JavaScript. It is reserved for subtractions.
Underscore:
first_name, last_name, master_card, inter_city.
Upper Camel Case (Pascal Case):
FirstName, LastName, MasterCard, InterCity.
Lower Camel Case:
JavaScript programmers tend to use camel case that starts with a lowercase
letter:
firstName, lastName, masterCard, interCity.
JavaScript Character Set
JavaScript uses the Unicode character set.
Unicode covers (almost) all the characters, punctuations, and symbols in the
world.
HTML Unicode (UTF-8) Reference
The Unicode Consortium
The Unicode Consortium develops the Unicode Standard. Their goal is to
replace the existing character sets with its standard Unicode Transformation
Format (UTF).
The Unicode Standard has become a success and is implemented in HTML,
XML, Java, JavaScript, E-mail, ASP, PHP, etc. The Unicode standard is also
supported in many operating systems and all modern browsers.
The Unicode Consortium cooperates with the leading standards development
organizations, like ISO, W3C, and ECMA.
The Unicode Character Sets
Unicode can be implemented by different character sets. The most
commonly used encodings are UTF-8 and UTF-16:
13
Char Description
acter
-set
UTF-8 A character in UTF8 can be from 1 to 4 bytes long. UTF-8 can represent any character in the Unicode
standard. UTF-8 is backwards compatible with ASCII. UTF-8 is the preferred encoding for e-mail and web
pages
UTF- 16-bit Unicode Transformation Format is a variable-length character encoding for Unicode, capable of
16 encoding the entire Unicode repertoire. UTF-16 is used in major operating systems and environments, like
Microsoft Windows, Java and .NET.
Tip: The first 128 characters of Unicode (which correspond one-to-one with
ASCII) are encoded using a single octet with the same binary value as
ASCII, making valid ASCII text valid UTF-8-encoded Unicode as well.
HTML 4 supports UTF-8. HTML 5 supports both UTF-8 and UTF-16!
The HTML5 Standard: Unicode UTF-8
Because the character sets in ISO-8859 was limited in size, and not
compatible in multilingual environments, the Unicode Consortium developed
the Unicode Standard.
The Unicode Standard covers (almost) all the characters, punctuations, and
symbols in the world.
Unicode enables processing, storage, and transport of text independent of
platform and language.
The default character encoding in HTML-5 is UTF-8.
If an HTML5 web page uses a different character set than UTF-8, it should be
specified in the <meta> tag like:
Example
<meta charset="ISO-8859-1">
The Difference Between Unicode and UTF-8
Unicode is a character set. UTF-8 is encoding.
Unicode is a list of characters with unique decimal numbers (code points). A
= 65, B = 66, C = 67, ....
This list of decimal numbers represent the string "hello": 104 101 108 108
111
14
Encoding is how these numbers are translated into binary numbers to be
stored in a computer:
UTF-8 encoding will store "hello" like this (binary): 01101000 01100101
01101100 01101100 01101111
Encoding translates numbers into binary. Character sets translates
characters to numbers.
HTML5 UTF-8 Character Codes
Below is a list of some of the UTF-8 character codes supported by HTML5:
Character codes Decimal Hexadecimal
C0 Controls and Basic Latin 0-127 0000-007F
C1 Controls and Latin-1 Supplement 128-255 0080-00FF
Latin Extended-A 256-383 0100-017F
Latin Extended-B 384-591 0180-024F
Spacing Modifiers 688-767 02B0-02FF
Diacritical Marks 768-879 0300-036F
Greek and Coptic 880-1023 0370-03FF
Cyrillic Basic 1024-1279 0400-04FF
Cyrillic Supplement 1280-1327 0500-052F
General Punctuation 8192-8303 2000-206F
15
Currency Symbols 8352-8399 20A0-20CF
Letterlike Symbols 8448-8527 2100-214F
Arrows 8592-8703 2190-21FF
Mathematical Operators 8704-8959 2200-22FF
Box Drawings 9472-9599 2500-257F
Block Elements 9600-9631 2580-259F
Geometric Shapes 9632-9727 25A0-25FF
Miscellaneous Symbols 9728-9983 2600-26FF
Dingbats 9984-10175 2700-27BF
The Difference Between Unicode and UTF-8
Unicode is a character set. UTF-8 is encoding.
Unicode is a list of characters with unique decimal numbers (code points). A
= 65, B = 66, C = 67, ....
This list of decimal numbers represent the string "hello": 104 101 108 108
111
Encoding is how these numbers are translated into binary numbers to be
stored in a computer:
UTF-8 encoding will store "hello" like this (binary): 01101000 01100101
01101100 01101100 01101111
16
Encoding translates numbers into binary. Character sets translates
characters to numbers.
JavaScript Statements
In HTML, JavaScript statements are "instructions" to be
"executed" by the web browser.
JavaScript Statements
This statement tells the browser to write "Hello Dolly." inside an HTML
element with id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
JavaScript Programs
Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they
are written.
In this example x, y, and z are given values, and finally z is displayed:
Example
var x, y, z;
x = 5;
y = 6;
z = x + y;
document.getElementById("demo").innerHTML = z;
JavaScript programs (and JavaScript statements) are often called
JavaScript code.
Semicolons ;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
var a, b, c;
a = 5;
b = 6;
c = a + b;
When separated by semicolons, multiple statements on one line are
allowed:
17
a = 5; b = 6; c = a + b;
When separated by semicolons, multiple statements on one line are
allowed:
a = 5; b = 6; c = a + b;
JavaScript Code Blocks
JavaScript statements can be grouped together in code blocks, inside
curly brackets {...}.
The purpose of code blocks is to define statements to be executed
together.
One place you will find statements grouped together in blocks, is in
JavaScript functions:
Example
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello
Dolly!";
document.getElementById("demo2").innerHTML = "How are
you?";
}
JavaScript Keywords
JavaScript statements often start with a keyword to identify the
JavaScript action to be performed.
Here is a list of some of the keywords you will learn about in this
tutorial:
18
JavaScript keywords are reserved words. Reserved words cannot be
used as names for variables.
JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to
make it more readable.
JavaScript comments can also be used to prevent execution, when testing
alternative code.
Single Line Comments
Single line comments start with //.
Any text between // and the end of the line will be ignored by JavaScript
(will not be executed).
This example uses a single-line comment before each code line:
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
This example uses a single line comment at the end of each line to explain
the code:
Example
var x = 5; // Declare x, give it the value of 5
var y = x + 2; // Declare y, give it the value of x + 2
19
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
This example uses a multi-line comment (a comment block) to explain the
code:
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
Using Comments to Prevent Execution
Using comments to prevent execution of code is suitable for code testing.
Adding // in front of a code line changes the code lines from an executable
line to a comment.
This example uses // to prevent execution of one of the code lines:
Example
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
This example uses a comment block to prevent execution of multiple lines:
Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
JavaScript Variables
JavaScript variables are containers for storing data values.
In this example, x, y, and z, are variables:
20
Example
var x = 5;
var y = 6;
var z = x + y;
From the example above, you can expect:
x stores the value 5
y stores the value 6
z stores the value 11
Much Like Algebra
In this example, price1, price2, and total, are variables:
Example
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
In programming, just like in algebra, we use variables (like price1) to hold values.
In programming, just like in algebra, we use variables in expressions (total
= price1 + price2).
From the example above, you can calculate the total to be 11.
JavaScript variables are containers for storing data values.
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names
(age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers)
are:
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter
Names can also begin with $ and _ (but we will not use it in this
tutorial)
Names are case sensitive (y and Y are different variables)
Reserved words (like JavaScript keywords) cannot be used as names
JavaScript identifiers are case-sensitive.
21
The Assignment Operator
In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal
to" operator.
This is different from algebra. The following does not make sense in algebra:
x = x + 5
In JavaScript, however, it makes perfect sense: it assigns the value of x + 5
to x.
(It calculates the value of x + 5 and puts the result into x. The value of x is
incremented by 5.)
The "equal to" operator is written like == in JavaScript.
JavaScript Data Types
JavaScript variables can hold numbers like 100 and text values like "John
Doe".
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of
numbers and strings.
Strings are written inside double or single quotes. Numbers are written
without quotes.
If you put a number in quotes, it will be treated as a text string.
Example
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
Declaring (Creating) JavaScript Variables
Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the var keyword:
var carName;
After the declaration, the variable has no value. (Technically it has the value
of undefined)
To assign a value to the variable, use the equal sign:
carName = "Volvo";
22
You can also assign a value to the variable when you declare it:
var carName = "Volvo";
In the example below, we create a variable called carName and assign the
value "Volvo" to it.
Then we "output" the value inside an HTML paragraph with id="demo":
Example
<p id="demo"></p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
It's a good programming practice to declare all variables at the beginning of
a script.
One Statement, Many Variables
You can declare many variables in one statement.
Start the statement with var and separate the variables by comma:
var person = "John Doe", carName = "Volvo", price = 200;
A declaration can span multiple lines:
var person = "John Doe",
carName = "Volvo",
price = 200;
Value = undefined
In computer programs, variables are often declared without a value. The
value can be something that has to be calculated, or something that will be
provided later, like user input.
A variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of
this statement:
Example
var carName;
23
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable, it will not lose its value.
The variable carName will still have the value "Volvo" after the execution of
these statements:
Example
var carName = "Volvo";
var carName;
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using
operators like = and +:
Example
var x = 5 + 2 + 3;
You can also add strings, but strings will be concatenated:
Example
var x = "John" + " " + "Doe";
Also try this:
Example
var x = "5" + 2 + 3;
If you put a number in quotes, the rest of the numbers will be treated as
strings, and concatenated.
Now try this:
Example
var x = 2 + 3 + "5";
24
JAVASCRIPT PROGRAMMING
25
JavaScript basic [58 exercises with
solution]
[An editor is available at the bottom of the page to write and
execute the scripts.]
1. Write a JavaScript program to display the current
day and time in the following format. Go to the editor
Sample Output : Today is : Friday.
Current time is : 4 PM : 50 : 22
Click me to see the solution
2. Write a JavaScript program to print the contents of
the current window. Go to the editor
Click me to see the solution
3. Write a JavaScript program to get the current date.
Go to the editor
Expected Output :
mm-dd-yyyy, mm/dd/yyyy or dd-mm-yyyy, dd/mm/yyyy
Click me to see the solution
4. Write a JavaScript program to find the area of a
triangle where lengths of the three of its sides are 5, 6,
26
7. Go to the editor
Click me to see the solution
5. Write a JavaScript program to rotate the string
'w3resource' in right direction by periodically removing
one letter from the end of the string and attaching it to
the front. Go to the editor
Click me to see the solution
6. Write a JavaScript program to determine whether a
given year is a leap year in the Gregorian calendar. Go
to the editor
Click me to see the solution
7. Write a JavaScript program to find 1st January is
being a Sunday between 2014 and 2050. Go to the
editor
Click me to see the solution
8. 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". Go to the editor
Click me to see the solution
9. Write a JavaScript program to calculate days left
until next Christmas. Go to the editor
Click me to see the solution
10. Write a JavaScript program to calculate
multiplication and division of two numbers (input from
27
user). Go to the editor
Sample form :
Click me to see the solution
11. Write a JavaScript program to convert temperatures
to and from celsius, fahrenheit. Go to the editor
[ Formula : c/5 = (f-32)/9 [ where c = temperature in
celsius and f = temperature in fahrenheit ]
Expected Output :
60C is 140 F
45F is 7.222222222222222C
Click me to see the solution
12. Write a JavaScript program to get the website URL
(loading page). Go to the editor
Click me to see the solution
13. Write a JavaScript exercise to create a variable
using a user-defined name. Go to the editor
Click me to see the solution
14. Write a JavaScript exercise to get the extension of
a filename. Go to the editor
Click me to see the solution
15. Write a JavaScript program to get the difference
between a given number and 13, if the number is
greater than 13 return double the absolute difference.
28
Go to the editor
Click me to see the solution
16. Write a JavaScript program to compute the sum of
the two given integers. If the two values are same, then
returns triple their sum. Go to the editor
Click me to see the solution
17. Write a JavaScript program to compute the
absolute difference between a specified number and
19. Returns triple their absolute difference if the
specified number is greater than 19. Go to the editor
Click me to see the solution
18. Write a JavaScript program to check two given
numbers and return true if one of the number is 50 or if
their sum is 50. Go to the editor
Click me to see the solution
19. Write a JavaScript program to check a given integer
is within 20 of 100 or 400. Go to the editor
Click me to see the solution
20. Write a JavaScript program to check from two given
integers, if one is positive and one is negative. Go to
the editor
Click me to see the solution
21. Write a JavaScript program to create a new string
adding "Py" in front of a given string. If the given string
begins with "Py" then return the original string. Go to
the editor
Click me to see the solution
29
22. Write a JavaScript program to remove a character
at the specified position of a given string and return the
new string. Go to the editor
Click me to see the solution
23. Write a JavaScript program to create a new string
from a given string changing the position of first and
last characters. The string length must be greater than
or equal to 1. Go to the editor
Click me to see the solution
24. Write a JavaScript program to create a new string
from a given string with the first character of the given
string added at the front and back. Go to the editor
Click me to see the solution
25. Write a JavaScript program check if a given positive
number is a multiple of 3 or a multiple of 7. Go to the
editor
Click me to see the solution
26. Write a JavaScript program to create a new string
from a given string taking the last 3 characters and
added at both the front and back. The string length
must be 3 or more. Go to the editor
Click me to see the solution
27. Write a JavaScript program to check if a string
starts with 'Java' and false otherwise. Go to the editor
Click me to see the solution
28. Write a JavaScript program to check if two given
integer values are in the range 50..99 (inclusive).
30
Return true if either of them are in the said range. Go
to the editor
Click me to see the solution
29. Write a JavaScript program to check if three given
integer values are in the range 50..99 (inclusive).
Return true if one or more of them are in the said
range. Go to the editor
Click me to see the solution
30. Write a JavaScript program to check if a string
"Script" presents at 5th (index 4) position in a given
string, if "Script" presents in the string return the string
without "Script" otherwise return the original one. Go to
the editor
Click me to see the solution
31. Write a JavaScript program to find the largest of
three given integers. Go to the editor
Click me to see the solution
32. Write a JavaScript program to find a value which is
nearest to 100 from two different given integer values.
Go to the editor
Click me to see the solution
33. Write a JavaScript program to check if two numbers
are in range 40..60 or in the range 70..100 inclusive.
Go to the editor
Click me to see the solution
34. Write a JavaScript program to find the larger
number from the two given positive integers, the two
31
numbers are in the range 40..60 inclusive. Go to the
editor
Click me to see the solution
35. Write a JavaScript program to check a given string
contains 2 to 4 numbers of a specified character. Go to
the editor
Click me to see the solution
36. Write a JavaScript program to check if the last digit
of the three given positive integers is same. Go to the
editor
Click me to see the solution
37. Write a JavaScript program to create new string
with first 3 characters are in lower case. If the string
length is less than 3 convert all the characters in upper
case. Go to the editor
Click me to see the solution
38. Write a JavaScript program to check the total marks
of a student in various examinations. The student will
get A+ grade if the total marks are in the range 89..100
inclusive, if the examination is "Final-exam." the
student will get A+ grade and total marks must be
greater than or equal to 90. Return true if the student
get A+ grade or false otherwise. Go to the editor
Click me to see the solution
39. Write a JavaScript program to compute the sum of
the two given integers, If the sum is in the range 50..80
32
return 65 other wise return 80. Go to the editor
Click me to see the solution
40. Write a JavaScript program to check from two given
integers if either one is 8 or their sum or difference is 8.
Go to the editor
Click me to see the solution
41. Write a JavaScript program to check three given
numbers, if the three numbers are same return 30
otherwise return 40 and if two numbers are same return
20. Go to the editor
Click me to see the solution
42. Write a JavaScript program to check if three given
numbers (integers) are increasing in strict mode and
flag is "false", however if "true" is false the numbers will
in soft mode. Go to the editor
Note: Strict mode -> 10, 15, 31 : Soft mode -> 24, 22,
31 or 22, 22, 31
Click me to see the solution
43. Write a JavaScript program to check from three
given numbers (non negative integers) that two or all of
them have the same rightmost digit. Go to the editor
Click me to see the solution
44. Write a JavaScript program to check from three
given integers that if a number is greater than or equal
to 20 and less than one of the others. Go to the editor
Click me to see the solution
33
45. Write a JavaScript program to check two given
integer values and return true if one of the number is 15
or if their sum or difference is 15. Go to the editor
Click me to see the solution
46. Write a JavaScript program to check two given non-
negative integers and if one of the number (not both) is
multiple of 7 or 11. Go to the editor
Click me to see the solution
47. Write a JavaScript program to check if a number in
the range 40..10000 inclusive presents in two number
(in same range). Go to the editor
For example 40 presents in 400 and 4000
Click me to see the solution
48. Write a JavaScript program to reverse a given
string. Go to the editor
Click me to see the solution
49. Write a JavaScript program to replace every
character in a given string with the character following it
in the alphabet. Go to the editor
Click me to see the solution
50. Write a JavaScript program to capitalize the first
letter of each word of a given string. Go to the editor
Click me to see the solution
51. Write a JavaScript program to convert a given
number to hours and minutes. Go to the editor
Click me to see the solution
34
52. Write a JavaScript program to convert the letters of
a given string in alphabetical order. Go to the editor
Click me to see the solution
53. Write a JavaScript program to check if the
characters a and b are separated by exactly 3 places
anywhere (at least once) in a given string. Go to the
editor
Click me to see the solution
54. Write a JavaScript program to count the number of
vowels in a given string. Go to the editor
Click me to see the solution
55. Write a JavaScript program to check if a given
string contains equal number of p's and t's present. Go
to the editor
Click me to see the solution
56. Write a JavaScript program to divide two positive
numbers and return a string with properly formatted
commas. Go to the editor
Click me to see the solution
57. Write a JavaScript program to create a new string
of specified copies (positive number) of a given string.
Go to the editor
Click me to see the solution
58. Write a JavaScript program to create a new string
of 4 copies of the last 3 characters of a given original
string. The length of the given string must be 3 and
above. Go to the editorClick me to see the solution
35
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript current day and time</title>
</head>
<body></body>
</html>
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday","Monday","Tuesday","Wednesday
","Thursday","Friday","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;
if (hour===0 && prepand===' PM ')
if (minute===0 && second===0)
hour=12;
prepand=' Noon';
else
hour=12;
prepand=' PM';
if (hour===0 && prepand===' AM ')
if (minute===0 && second===0)
36
{
hour=12;
prepand=' Midnight';
else
hour=12;
prepand=' AM';
console.log("Current Time : "+hour + prepand + " : " + minute + " : " + second);
<!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>
<button onclick="print_current_page()">Print this page</button>
</body>
</html>
Copy
JavaScript Code:
37