JAVA Script
JAVA Script
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
Client-side validation,
Dynamic drop-down menus,
Displaying date and time,
Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and prompt dialog
box),
Displaying clocks etc.
JavaScript Example
1. <script>
2. document.write("Hello JavaScript by JavaScript");
3. </script>
Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
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
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> document.getElementById("demo").innerHTML = 5 + 6;
<html> </script></body>
<body> </html>
<h1>My First Web Page</h1> Output: My First Web Page
<p>My First Paragraph</p> My First Paragraph.
<p id="demo"></p> 11
<script>
Using document.write():
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html> <script>
<html> document.write(5 + 6);
<body> </script>
<h1>My First Web Page</h1> </body>
<p>My first paragraph.</p> </html>
Output: My First Web Page
My first paragraph.
Never call document.write after the document has finished loading. It will overwrite the whole document.
11
Using window.alert():
You can use an alert box to display data:
Example
<!DOCTYPE html> window.alert(5 + 6);
<html> </script>
<body> </body>
<h1>My First Web Page</h1> </html>
<p>My first paragraph.</p>
<script>
JavaScript Statements
JavaScript statements are composed of:Values, Operators, Expressions, Keywords, and Comments
Semicolons ;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
<html> a = 1;
<body> b = 2;
<h2>JavaScript Statements</h2> c = a + b;
<p>JavaScript statements are separated by document.getElementById("demo1").innerHTML = c;
semicolons.</p> </script>
<p id="demo1"></p> </body>
<script> </html>
var a, b, c;
Output:
JavaScript Statements
JavaScript statements are separated by semicolons.
3
JavaScript Keywords:
JavaScript statements often start with a keyword to identify the JavaScript action to be performed.
Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging function
do ... while Executes a block of statements, and repeats the block, while a condition is true
For Marks a block of statements to be executed, as long as a condition is true
function Declares a function
if ... else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different cases
try ... catch Implements error handling to a block of statements
Var Declares a variable
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:
<html> </script>
<body> </body>
<h2>JavaScript Numbers</h2> </html>
<p>Number can be written with or without Output:
decimals.</p> JavaScript Numbers
<p id="demo"></p> Number can be written with or without decimals.
<script> 10.5
document.getElementById("demo").innerHTML = 10.50;
"John Doe"
'John Doe'
<html> document.getElementById("demo").innerHTML = 'John
<body> Doe';
<h2>JavaScript Strings</h2> </script>
<p>Strings can be written with double or single </body>
quotes.</p> </html>
<p id="demo"></p>
<script>
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.
<html> var x;
<body> x = 6;
<h2>JavaScript Variables</h2> document.getElementById("demo").innerHTML = x;
<p>In this example, x is defined as a variable. </script>
Then, x is assigned the value of 6:</p> </body>
<p id="demo"></p> </html>
<script>
JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
<html> <script>
<body> document.getElementById("demo").innerHTML = (5 + 6)
<h2>JavaScript Operators</h2> * 10;
<p>JavaScript uses arithmetic operators to compute </script>
values (just like algebra).</p> </body>
<p id="demo"></p> </html>
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:
<html> <script>
<body> document.getElementById("demo").innerHTML = 5 *
<h2>JavaScript Expressions</h2> 10;
<p>Expressions compute to values.</p> </script>
<p id="demo"></p> </body></html>
JavaScript Keywords:
JavaScript keywords are used to identify actions to be performed.The var keyword tells the browser to create variables:
<html> y = x * 10;
<body> document.getElementById("demo").innerHTML = y;
<h2>The var Keyword Creates Variables</h2> </script>
<p id="demo"></p>
<script> </body>
var x, y; </html>
x = 5 + 6;
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.
Example
<p id="demo"></p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
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;
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
++ Increment
-- Decrement
JavaScript Functions:
<html> return p1 * p2;
<body> }
<h2>JavaScript Functions</h2> document.getElementById("demo").innerHTML =
<p>This example calls a function which performs a myFunction(4, 3);
calculation, and returns the result:</p> </script>
<p id="demo"></p> </body>
<script> </html>
function myFunction(p1, p2) {
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
Function Return
When JavaScript reaches a return statement, the function will stop executing.If the function was invoked from a
statement, JavaScript will "return" to execute the code after the invoking statement.Functions often compute a return
value. The return value is "returned" back to the "caller"
<html> document.getElementById("demo").innerHTML = x;
<body>
<h2>JavaScript Functions</h2> function myFunction(a, b) {
<p>This example calls a function which performs a return a * b;
calculation and returns the result:</p> }
<p id="demo"></p> </script>
<script> </body>
var x = myFunction(4, 3); </html>
Window Object
1. Window Object
2. Properties of Window Object
3. Methods of Window Object
4. Example of Window Object
The window object represents a window in browser. An object of window is created automatically by the browser.
Window is the object of browser, it is not the object of javascript. The javascript objects are string, array, date etc.
Note: if html document contains frame or iframe, browser creates additional window objects for each frame.
Methods of window object
The important methods of window object are as follows:
Method Description
alert() displays the alert box containing message with ok button.
confirm() displays the confirm dialog box containing message with ok and cancel button.
prompt() displays a dialog box to get input from the user.
open() opens the new window.
close() closes the current window.
setTimeout() performs action after specified time like calling function, evaluating expressions etc.
Example of alert() in javascript
It displays alert dialog box. It has message and ok button.
1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>
Javascript - innerHTML
1. javascript innerHTML
2. Example of innerHTML property
The innerHTML property can be used to write the dynamic html on the html document.It is used mostly in the web
pages to generate the dynamic html such as registration form, comment form, links etc.
Javascript - innerText
1. javascript innerText
2. Example of innerText property
The innerText property can be used to write the dynamic text on the html document. Here, text will not be interpreted
as html text but a normal text.It is used mostly in the web pages to generate the dynamic content such as writing the
validation message, password strength etc.
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using string literal is given below:
1. var stringname="string value";
1. <script>
2. var str="This is string literal";
3. document.write(str);
4. </script>
Output:
This is string literal
Output:
hello javascript string
JavaScript String Methods
Let's see the list of JavaScript string methods with examples.
Methods Description
charAt() It provides the char value present at the specified index.
charCodeAt() It provides the Unicode value of a character present at the specified index.
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string.
It provides the position of a char value present in the given string by searching a character from
lastIndexOf()
the last position.
It searches a specified regular expression in a given string and returns its position if a match
search()
occurs.
It searches a specified regular expression in a given string and returns that regular expression if a
match()
match occurs.
replace() It replaces a given string with the specified replacement.
It is used to fetch the part of the given string on the basis of the specified starting position and
substr()
length.
substring() It is used to fetch the part of the given string on the basis of the specified index.
slice() It is used to fetch the part of the given string. It allows us to assign positive as well negative index.
toLowerCase() It converts the given string into lowercase letter.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current locale.
toUpperCase() It converts the given string into uppercase letter.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current locale.
toString() It provides a string representing the particular object.
valueOf() It provides the primitive value of string object.
1) JavaScript String charAt(index) Method
The JavaScript String charAt() method returns the character at the given index.
1. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>
Output:
v
2) JavaScript String concat(str) Method
The JavaScript String concat(str) method concatenates or joins two strings.
1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>
Output:
javascript concat example
3) JavaScript String indexOf(str) Method
The JavaScript String indexOf(str) method returns the index position of the given string.
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("from");
4. document.write(n);
5. </script>
Output:
11
4) JavaScript String lastIndexOf(str) Method
The JavaScript String lastIndexOf(str) method returns the last index position of the given string.
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.lastIndexOf("java");
4. document.write(n);
5. </script>
Output:
16
Output:
javascript tolowercase example
Output:
JAVASCRIPT TOUPPERCASE EXAMPLE
Output:
cde
Output:
javascript trim
Constructor
You can use 4 variant of Date constructor to create date object.
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
JavaScript Date Methods
Let's see the list of JavaScript date methods with their description.
Methods Description
It returns the integer value between 1 and 31 that represents the day for the specified date on the
getDate()
basis of local time.
It returns the integer value between 0 and 6 that represents the day of the week on the basis of local
getDay()
time.
getFullYears() It returns the integer value that represents the year on the basis of local time.
getHours() It returns the integer value between 0 and 23 that represents the hours on the basis of local time.
It returns the integer value between 0 and 999 that represents the milliseconds on the basis of local
getMilliseconds()
time.
getMinutes() It returns the integer value between 0 and 59 that represents the minutes on the basis of local time.
getMonth() It returns the integer value between 0 and 11 that represents the month on the basis of local time.
getSeconds() It returns the integer value between 0 and 60 that represents the seconds on the basis of local time.
setDate() It sets the day value for the specified date on the basis of local time.
setDay() It sets the particular day of the week on the basis of local time.
setFullYears() It sets the year value for the specified date on the basis of local time.
setHours() It sets the hour value for the specified date on the basis of local time.
setMilliseconds() It sets the millisecond value for the specified date on the basis of local time.
setMinutes() It sets the minute value for the specified date on the basis of local time.
setMonth() It sets the month value for the specified date on the basis of local time.
setSeconds() It sets the second value for the specified date on the basis of local time.
toString() It returns the date in the form of string.
JavaScript Date Example
Let's see the simple example to print date object. It prints date and time both.
1. Current Date and Time: <span id="txt"></span>
2. <script>
3. var today=new Date();
4. document.getElementById('txt').innerHTML=today;
5. </script>
Output:
Current Date and Time: Tue Oct 23 2018 01:36:29 GMT+0530 (India Standard Time)
Let's see another code to print date/month/year.
1. <script>
2. var date=new Date();
3. var day=date.getDate();
4. var month=date.getMonth()+1;
5. var year=date.getFullYear();
6. document.write("<br>Date is: "+day+"/"+month+"/"+year);
7. </script>
Output:
Date is: 23/10/2018
Output:
Current Time: 1:36:29
JavaScript Math
The JavaScript math object provides several constants and methods to perform mathematical operation. Unlike date
object, it doesn't have constructors.
JavaScript Math Methods
Let's see the list of JavaScript Math methods with description.
Methods Description
abs() It returns the absolute value of the given number.
acos() It returns the arccosine of the given number in radians.
asin() It returns the arcsine of the given number in radians.
atan() It returns the arc-tangent of the given number in radians.
cbrt() It returns the cube root of the given number.
ceil() It returns a smallest integer value, greater than or equal to the given number.
cos() It returns the cosine of the given number.
cosh() It returns the hyperbolic cosine of the given number.
exp() It returns the exponential form of the given number.
floor() It returns largest integer value, lower than or equal to the given number.
hypot() It returns square root of sum of the squares of given numbers.
log() It returns natural logarithm of a number.
max() It returns maximum value of the given numbers.
min() It returns minimum value of the given numbers.
pow() It returns value of base to the power of exponent.
random() It returns random number between 0 (inclusive) and 1 (exclusive).
round() It returns closest integer value of the given number.
sign() It returns the sign of the given number
sin() It returns the sine of the given number.
sinh() It returns the hyperbolic sine of the given number.
sqrt() It returns the square root of the given number
tan() It returns the tangent of the given number.
tanh() It returns the hyperbolic tangent of the given number.
trunc() It returns an integer part of the given number.
Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.
1. Square Root of 17 is: <span id="p1"></span>
2. <script>
3. document.getElementById('p1').innerHTML=Math.sqrt(17);
4. </script>
Output:
Square Root of 17 is: 4.123105625617661
Math.random()
The JavaScript math.random() method returns the random number between 0 to 1.
1. Random Number is: <span id="p2"></span>
2. <script>
3. document.getElementById('p2').innerHTML=Math.random();
4. </script>
Output:
Random Number is: 0.4886444692425461
Math.pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.
1. 3 to the power of 4 is: <span id="p3"></span>
2. <script>
3. document.getElementById('p3').innerHTML=Math.pow(3,4);
4. </script>
Output:
3 to the power of 4 is: 81
Math.floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given number. For example 3 for 3.7, 5 for 5.9
etc.
1. Floor of 4.6 is: <span id="p4"></span>
2. <script>
3. document.getElementById('p4').innerHTML=Math.floor(4.6);
4. </script>
Output:
Floor of 4.6 is: 4
Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given number. For example 4 for 3.7, 6 for 5.9 etc.
1. Ceil of 4.6 is: <span id="p5"></span>
2. <script>
3. document.getElementById('p5').innerHTML=Math.ceil(4.6);
4. </script>
Output:
Ceil of 4.6 is: 5
Math.round(n)
The JavaScript math.round(n) method returns the rounded integer nearest for the given number. If fractional part is
equal or greater than 0.5, it goes to upper value 1 otherwise lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.
1. Round of 4.3 is: <span id="p6"></span><br>
2. Round of 4.7 is: <span id="p7"></span>
3. <script>
4. document.getElementById('p6').innerHTML=Math.round(4.3);
5. document.getElementById('p7').innerHTML=Math.round(4.7);
6. </script>
Output:
Round of 4.3 is: 4
Round of 4.7 is: 5
Math.abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given number. For example 4 for -4, 6.6 for -6.6
etc.
1. Absolute value of -4 is: <span id="p8"></span>
2. <script>
3. document.getElementById('p8').innerHTML=Math.abs(-4);
4. </script>
Output:
Absolute value of -4 is: 4
Output:
102 102.7 130000 16
<script> </body>
function displayDate() { </html>
<html> } else {
<body onload="checkCookies()"> text = "Cookies are not enabled.";
}
<p id="demo"></p> document.getElementById("demo").innerHTML =
text;
<script> }
function checkCookies() { </script>
var text = "";
if (navigator.cookieEnabled == true) { </body>
text = "Cookies are enabled."; </html>
The onchange Event
The onchange event is often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the
content of an input field.
Example
<html>
<head> Enter your name: <input type="text" id="fname"
<script> onchange="myFunction()">
function myFunction() { <p>When you leave the input field, a function is
var x = document.getElementById("fname"); triggered which transforms the input text to upper
x.value = x.value.toUpperCase(); case.</p>
}
</script> </body>
</head> </html>
<body>
<div onmousedown="mDown(this)"
onmouseup="mUp(this)"
style="background-
color:#D94A38;width:90px;height:20px;padding:40px;"
>
Click Me</div>
<script>
function mDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
obj.innerHTML = "Release Me";
}
function mUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>
</body>
</html>