2. What is JavaScript
JavaScript ("JS" for short) is a full-fledged dynamic programming language
that, when applied to an HTML document, can provide dynamic
interactivity on websites.
It was invented by Brendan Eich, co-founder of the Mozilla project, the
Mozilla Foundation, and the Mozilla Corporation.
We can do pretty much anything with JavaScript, such as image galleries,
fluctuating layouts, and responses to button clicks. And if get more
experienced with the language, we'll be able to create games, animated
2D and 3D graphics, full blown database-driven apps, and more!
3. Advantages of JavaScript
Saving bandwidth and strain on the web server.
Javascript is executed on the client side
Javascript is relatively fast to the end user
Javascript is executed on the client side
4. Limitations of JavaScript
Security Issues
Javascript snippets, once appended onto web pages execute on client
servers immediately and therefore can also be used to exploit the user's
system. While a certain restriction is set by modern web standards on
browsers, malicious code can still be executed complying with the
restrictions set.
Javascript rendering varies
Different layout engines may render Javascript differently resulting in
inconsistency in terms of functionality and interface. While the latest
versions of javascript and rendering have been geared towards a universal
standard, certain variations still exist.
5. Client-side JavaScript
A scripting or script language is a programming language that supports scripts, programs
written for a special run-time environment that automate the execution of tasks that could
alternatively be executed one-by-one by a human operator. Scripting languages are often
interpreted (rather than compiled).
Client-side scripting generally refers to the class of computer programs on the web that
are executed client-side, by the user's web browser, instead of server-side.
Client-side scripts do not require additional software on the server (making them popular
with authors who lack administrative access to their servers); however, they do require that
the user's web browser understands the scripting language in which they are written.
Client-side scripting is not inherently unsafe. Users, though, are encouraged to always
keep their web browsers up-to-date to avoid exposing their computer and data to new
vulnerabilities.
6. Places to put JavaScript code
1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javaScript)
7. Between the body tag
In the above example, we have displayed the dynamic content using
JavaScript. Let’s see the simple example of JavaScript that displays alert
dialog box.
<script type="text/javascript">
alert("Hello Javatpoint");
</script>
11. Comments
Single line comment
// This is a comment
Multiline comment
/* line 1
line 2
line 3 */
12. Data Types
Variable Explanation Example
String
A string of text. To signify that the variable is a
string, you should enclose it in quote marks.
var myVariable = 'Bob';
Number
A number. Numbers don't have quotes around
them.
var myVariable = 10;
Boolean
A True/False value. The words true and false are
special keywords in JS, and don't need quotes.
var myVariable = true;
Array
A structure that allows you to store multiple values
in one single reference.
var myVariable =
[1,'Bob','Steve',10];
Refer to each member of the
array like this:
myVariable[0], myVariable[1], etc.
Object
Basically, anything. Everything in JavaScript is an
object, and can be stored in a variable. Keep this
in mind as you learn.
var myVariable =
document.querySelector('h1');
All of the above examples too.
13. Operators
What is an operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and ‘+’ is called the operator. JavaScript supports the following types
of operators.
Assignment operators
Comparison operators
Arithmetic operators
Bitwise operators
Bitwise shift operators
Logical operators
Conditional (ternary) operator
15. JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
16. 1) JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by ,
(comma).
Let’s see the simple example of creating and using array in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
17. 2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array. Let’s see the example of creating array
directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
18. 3) JavaScript array constructor
(new keyword)
Here, you need to create instance of array by passing arguments in
constructor so that we don't have to provide value explicitly.
var arrayname=new Array(value1,value2.....valueN);
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
19. How to access an array
Access the Elements of an Array
You refer to an array element by referring to the index number.
cars[0] = "Opel";
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
Access the Full Array
With JavaScript, the full array can be accessed by referring to the array name:
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
20. Arrays are objects
Arrays are a special type of objects.
var person = ["John", "Doe", 46];
Objects use names to access its "members". In this example, person.firstName returns
John:
var person = {firstName:"John", lastName:"Doe", age:46};
Document.write(person.firstname);
21. Array Methods
concat()
Javascript array concat() method returns a new array comprised of this array joined with two or more
arrays.
array.concat(value1, value2, ..., valueN);
indexOf()
Javascript array indexOf() method returns the first index at which a given element can be found in the
array, or -1 if it is not present.
array.indexOf(searchElement[, fromIndex]);
LastIndexOf()
Javascript array lastIndexOf() method returns the last index at which a given element can be found in
the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.
array.lastIndexOf(searchElement[, fromIndex]);
Join()
Javascript array join() method joins all the elements of an array into a string.
array.join(separator);
sort()
Javascript array sort() method sorts elements of an array.
array.sort(function);
22. Array Methods
Push()
Javascript array pop() method insert an element at the end of an array
Array.push(value);
Pop()
Javascript array pop() method removes the last element from an array and returns that element.
Array.pop(value);
Reverse()
Javascript array reverse() mmethod reverses the element of an array. The first array element becomes
the last and the last becomes the first.
Array.Reverse();
Unshift()
Adds one or more elements to the front of an array and returns the new length of the array.
Array.Unshift(value);
Shift()
Javascript array shift()method removes the first element from an array and returns that element.
Array.Shift();
23. Array Methods
splice()
The splice() method adds/removes items to/from an array, and returns the removed item(s).
array.splice(index,howmany,item1,.....,itemX)
slice()
The slice() method returns the selected elements in an array, as a new array object.
array.slice(start,end)
index Required. specifies at what position to add/remove items
howmany Required. The number of items to be removed
item1, ..., itemX Optional. The new item(s) to be added to the array
start Optional. specifies where to start the selection (count starts from
index value 0).
end Optional. specifies where to end the selection. (count starts from 1).
24. JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
By string literal
var stringname="string value";
By string object (using new keyword)
var stringname=new String("string literal");
25. JavaScript String Methods
charAt(index)
The JavaScript String charAt() method returns the character at the given index.
document.write(str.charAt(2));
concat(str)
The JavaScript String concat(str) method concatenates or joins two strings.
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
indexOf(str)
The JavaScript String indexOf(str) method returns the index position of the given string.
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
lastIndexOf(str)
The JavaScript String lastIndexOf(str) method returns the last index position of the given string.
var s1="javascript from javatpoint indexof";
var n=s1.lastIndexOf("java");
26. JavaScript String Methods
toLowerCase()
This method returns the given string in lowercase letters.
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
toUpperCase()
This method returns the given string in Uppercase letters.
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
slice(beginIndex, count)
This method returns the parts of string from given beginIndex to count. In slice() method, beginIndex is inclusive
and count is exclusive. (beginIndex starts from 0th element of array and count starts from beginIndex)
var s2=s1.slice(2,5);
trim()
This method removes leading and trailing whitespaces from the string.
var s1=" javascript trim ";
var s2=s1.trim();
27. Javascript DOM
Document Object Model
The document object represents the whole html document.
When html document is loaded in the browser, it becomes a document
object. It is the root element that represents the html document. It has
properties and methods. By the help of document object, we can add
dynamic content to our web page.
window.document Is same as document
28. Methods Document Object
Method Description Example
document.write("string") writes the given string on the doucment. document.write(‘’hello”);
document.writeln("string")
writes the given string on the doucment with newline
character at the end.
document.write(‘’hello”);
document.getElementById() returns the element having the given id value. var a=document.getElementById(“p1”).value
document.getElementsByName()
returns all the elements having the given name
value.
var a=document.getElementsByName(“pera”).value
document.getElementsByTagName
()
returns all the elements having the given tag name. var a=document.getElementsByTagName(“p”).value
document.getElementsByClassNam
e()
returns all the elements having the given class
name.
var
a=document.getElementsByClassName(“class1”).val
ue
document.querySelector() Returns the first element that matches a specified
CSS selector(s) in the document
Var a = document.querySelector(“.classname”);
29. Methods Document Object
Example:
<body>
<p class=“class1” name=“pera”>demo1</p>
<p class=“class1” name=“pera”>demo2</p>
<p id="p1“ ></p>
<script>
var x = document.getElementsByTagName("p"); //put ClassName or Name in the place of TagName
document.getElementById("p1").innerHTML =x[0].innerHTML;
</script>
</body>
Output:
demo1
demo2
demo3
30. Methods Document Object
Method Description
document.title Sets or returns the title of the document
document.URL Returns the full URL of the HTML document
document.cookie Returns all name/value pairs of cookies in the document
document.createAttribute() Creates an attribute node
document.body Sets or returns the document's body (the <body> element)
document.form() Returns the elements value/name of form
<form id="myForm" name="myForm">
<input id="email" name="email" value="some@email.com" />
</form>
<script>
document.forms["myForm"]["email"].value
</script>
31. Adding and Deleting HTML Elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(element) Replace an HTML element
<body>
<div id="d1">
hello
</div>
<script>
var x = document.createElement('span');
x.innerHTML = "Hello!";
//document.body.appendChild(x); //append in body
document.getElementById("d1").appendChild(x); //append in particular element
</script>
</body>
32. Methods Element Object
Method Description Example
element.style.property Sets or returns the value of the style attribute of an
element
document.getElementById(“p1”).style.color=“red”;
element.tagName Returns the tag name of an element Var x=document.getElementById(“p1”).tagName
element.innerHTML Sets or returns the content of an element p.innerHtml=“hello’;
element.id Sets or returns the value of the id attribute of an
element
Var x=document.getElementsByTagName(“p”).id
element.attribute Change the attribute value of an HTML element <img src=“1.jpg”></img>
<script>document.getElementById(“img1”).src=“2.jpg”</script>
element.setAttribute(attribute,
value)
Change the attribute value of an HTML element Ex1:
document.getElementsByTagName("H1")
[0].setAttribute("class", “newclass");
Ex2:
element.setAttribute("style", "background-color: red;");
33. Methods DOM Attribute Object
Method Description Example
attr.name Returns the name of an attribute var
a=document.getElementById(“p1”).nam
e
attr.value Sets or returns the value of the
attribute
var
a=document.getElementById(“txt1”).valu
e
• innerText retrieves and sets the content of the tag as plain
text, whereas innerHTML retrieves and sets the same content
but in HTML format.
innerText Vs innerHTML
35. JavaScript Popup Boxes
It is possible to make three different kinds of popup windows
Alert Box
An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
alert("sometext");
<script>
alert("Hello World!")
</script>
36. JavaScript Popup Boxes - 2
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
confirm("sometext");
<script>
function myFunction() {
var x;
if (confirm("Press a button!") == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>
37. JavaScript Popup Boxes - 3
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after
entering an input value.
If the user clicks "OK“, the box returns the input value. If the user clicks "Cancel“, the box returns
null.
prompt("sometext","defaultText");
Hello Alice! How are you today?
<script>
function myFunction()
{
var person = prompt("Please enter your name");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
}
</script>
38. Timing Events
setTimeout() Method
setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.
setInterval() Method
Var id_of_setinterval=setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function continuously.
clearInterval() Method
The clearInterval() method stops the executions of the function specified in the setInterval() method. It ret
clearInterval(id_of_setinterval)
* There are 1000 milliseconds in one second.
39. Window History
loads the URL in the history list.
history.back() - same as clicking back in the browser
history.forward() - same as clicking forward in the browser
<head>
<script>
function goBack() {
window.history.back()
}
function goForward() {
window.history.forward()
}
</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
<input type="button" value="Forward" onclick="goForward()">
</body>
40. Navigator object
Property Description
navigator.appName returns the name
navigator.appVersion returns the version
navigator.appCodeName returns the code name
navigator.cookieEnabled returns true if cookie is enabled otherwise false
navigator.userAgent returns the user agent
navigator.language returns the language. It is supported in Netscape and Firefox only.
navigator.userLanguage returns the user language. It is supported in IE only.
navigator.plugins returns the plugins. It is supported in Netscape and Firefox only.
navigator.systemLanguage returns the system language. It is supported in IE only.
navigator.mimeTypes[] returns the array of mime type. It is supported in Netscape and Firefox only.
navigator.platform returns the platform e.g. Win32.
navigator.online returns true if browser is online otherwise false.
The JavaScript navigator object is used for browser detection. It can be used to get browser information. There are
many properties of navigator object that returns information of the browser.
41. Window Screen
Property Description
screen.width returns the width of the visitor's screen
screen.height returns the height of the visitor's screen
screen.availWidth returns the width of the visitor's screen, in pixels, minus interface
features like the Windows Taskbar.
screen.availHeight returns the height of the visitor's screen, in pixels, minus interface
features like the Windows Taskbar.
screen.colorDepth returns the number of bits used to display one color.
screen.pixelDepth returns the pixel depth of the screen.
It contains information about the user's screen.
42. HTML/DOM events for JavaScript
Events Description
onclick occurs when element is clicked.
ondblclick occurs when element is double-clicked.
onfocus occurs when an element gets focus such as button, input, textarea etc.
onblur occurs when form looses the focus from an element.
onsubmit occurs when form is submitted.
onmouseover occurs when mouse is moved over an element.
onmouseout occurs when mouse is moved out from an element (after moved over).
onmousedown occurs when mouse button is pressed over an element.
onmouseup occurs when mouse is released from an element (after mouse is pressed).
onload occurs when document, object or frameset is loaded.
onunload occurs when body or frameset is unloaded.
onscroll occurs when document is scrolled.
onresized occurs when document is resized.
onreset occurs when form is reset.
onkeydown occurs when key is being pressed.
onkeypress occurs when user presses the key.
onkeyup occurs when key is released.