JS_BASICS_LOOP_FN_OBJECT
JS_BASICS_LOOP_FN_OBJECT
What is JavaScript?
Javascript History
The language was initially called LiveScript and was later renamed JavaScript.
There are many programmers who think that JavaScript and Java are the same. In
2
fact, JavaScript and Java are very much unrelated. Java is a very complex
programming language whereas JavaScript is only a scripting language.
Features of JavaScript
There are following features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
6. It is a case-sensitive language.
11. You can run JavaScript not only in the browser but also on
the server and any device which has a JavaScript Engine.
2. To avoid the unnecessary code It can also be used to avoid the code being
executed. Sometimes, we add the code to perform some action. But after
sometime, there may be need to disable the code. In such case, it is better to use
comments.
3
Most popular websites like Google, Facebook, Netflix, Amazon, etc make use of
JavaScript to build their websites.
On the other hand, CSS is like our clothes. It makes the web look better. It
uses CSS which stands for Cascading Style Sheets for styling purpose.
Finally, JavaScript is used to add life to a web page. Just like how kids move
around using the skateboard, the web also motions with the help of
JavaScript.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box,
confirm dialog box and prompt dialog box),
o Displaying clocks etc.
5
<html>
<head>
<script type="text/javascript">
alert("Hello World!");
</script>
</head>
<body>
</body>
</html>
Advantages of JavaScript
The merits of using JavaScript are −
Less server interaction − You can validate user input before sending the
page off to the server. This saves server traffic, which means less load on
your server.
Immediate feedback to the visitors − They don't have to wait for a page
reload to see if they have forgotten to enter something.
Increased interactivity − You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-
and-drop components and sliders to give a Rich Interface to your site
visitors.
o JavaScript is used to create beautiful web
pages and applications. It is mostly used to make your web
look alive and adds variety to the page.
6
Most popular websites like Google, Facebook, Netflix, Amazon, etc make use of
JavaScript to build their websites.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features −
Client-side JavaScript does not allow the reading or writing of files. This
has been kept for security reason.
JavaScript cannot be used for networking applications because there is no
such support available.
JavaScript doesn't have any multithreading or multiprocessor capabilities.
HTML files are stored with .htm or .html extension, while DHTML
files are stored with .dhtm extension.
JavaScript provides different data types to hold different types of values. There
are two types of data types in JavaScript.
JavaScript is a dynamic type language, means you don't need to specify type of
the variable because it is dynamically used by JavaScript engine. You need to
use var here to specify the data type. It can hold any type of values such as
numbers, strings etc. For example:
There are five types of primitive data types in JavaScript. They are as follows:
JavaScript Example
Compiler ; https://www.javatpoint.com/oprweb/test.jsp?filename=hellojs
1. <h2>Welcome to JavaScript</h2>
2. <script>
3. document.write("Hello JavaScript by JavaScript");
4. </script>
JAVASCRIPT OPERATORS
JavaScript operators are symbols that are used to perform operations on operands.
For example:
10
1. var sum=10+20;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:
Operator Description
(?:) Conditional Operator returns value based on the condition. It is
like if-else.
, Comma Operator allows multiple expressions to be evaluated as
single statement.
delete Delete Operator deletes a property from the object.
in In Operator checks if object has the given property
instanceof checks if the object is an instance of given type
new creates an instance (object)
typeof checks the type of object.
void it discards the expression's return value.
yield checks what is returned in a generator by the generator's iterator.
JavaScript If-else
13
The JavaScript if-else statement is used to execute the code whether condition is
true or false. There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
1. if(expression){
2. //content to be evaluated
3. }
Flowchart of JavaScript If statement
1. <script>
2. var a=20;
3. if(a>10){
4. document.write("value of a is greater than 10");
5. }
6. </script>
Test it Now
14
It evaluates the content whether condition is true of false. The syntax of JavaScript
if-else statement is given below.
1. if(expression){
2. //content to be evaluated if condition is true
3. }
4. else{
5. //content to be evaluated if condition is false
6. }
Flowchart of JavaScript If...else statement
Let’s see the example of if-else statement in JavaScript to find out the even or odd
number.
1. <script>
2. var a=20;
15
3. if(a%2==0){
4. document.write("a is even number");
5. }
6. else{
7. document.write("a is odd number");
8. }
9. </script>
Test it Now
Output of the above example
a is even number
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
1. if(expression1){
2. //content to be evaluated if expression1 is true
3. }
4. else if(expression2){
5. //content to be evaluated if expression2 is true
6. }
7. else if(expression3){
8. //content to be evaluated if expression3 is true
9. }
10.else{
11.//content to be evaluated if no expression is true
12.}
1. <script>
2. var a=20;
3. if(a==10){
4. document.write("a is equal to 10");
5. }
6. else if(a==15){
7. document.write("a is equal to 15");
8. }
9. else if(a==20){
10.document.write("a is equal to 20");
16
11.}
12.else{
13.document.write("a is not equal to 10, 15 or 20");
14.}
15.</script>
Output of the above example
a is equal to 20
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in previous page.
But it is convenient thanif..else..if because it can be used with numbers, characters
etc.
1. switch(expression){
2. case value1:
3. code to be executed;
4. break;
5. case value2:
6. code to be executed;
7. break;
8. ......
9.
10.default:
11. code to be executed if above values are not matched;
12.}
1. <script>
2. var grade='B';
3. var result;
4. switch(grade){
5. case 'A':
6. result="A Grade";
7. break;
8. case 'B':
17
9. result="B Grade";
10.break;
11.case 'C':
12.result="C Grade";
13.break;
14.default:
15.result="No Grade";
16.}
17.document.write(result);
18.</script>
Test it Now
Output of the above example
B Grade
The switch statement is fall-through i.e. all the cases will be evaluated if you
don't use break statement.
1. <script>
2. var grade='B';
3. var result;
4. switch(grade){
5. case 'A':
6. result+=" A Grade";
7. case 'B':
8. result+=" B Grade";
9. case 'C':
10.result+=" C Grade";
11.default:
12.result+=" No Grade";
13.}
14.document.write(result);
15.</script>
Test it Now
Output of the above example
B Grade B Grade C Grade No Grade
JavaScript Loops
18
The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It makes the code compact. It is mostly used in array.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
The JavaScript for loop iterates the elements for the fixed number of times. It
should be used if number of iteration is known. The syntax of for loop is given
below.
1. <script>
2. for (i=1; i<=5; i++)
3. {
4. document.write(i + "<br/>")
5. }
6. </script>
Test it Now
Output:
1
2
3
4
5
19
The JavaScript while loop iterates the elements for the infinite number of times. It
should be used if number of iteration is not known. The syntax of while loop is
given below.
1. while (condition)
2. {
3. code to be executed
4. }
1. <script>
2. var i=11;
3. while (i<=15)
4. {
5. document.write(i + "<br/>");
6. i++;
7. }
8. </script>
Test it Now
Output:
11
12
13
14
15
3) JavaScript do while loop
The JavaScript do while loop iterates the elements for the infinite number of
times like while loop. But, code is executed at least once whether condition is true
or false. The syntax of do while loop is given below.
1. do{
2. code to be executed
3. }while (condition);
1. <script>
2. var i=21;
3. do{
4. document.write(i + "<br/>");
5. i++;
6. }while (i<=25);
7. </script>
Test it Now
Output:
21
22
23
24
25
4) JavaScript for in loop
The JavaScript for in loop is used to iterate the properties of an object. We will
discuss about it later.
JavaScript Functions
3. }
Let’s see the simple example of function in JavaScript that does not has arguments.
1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>
Test it Now
Output of the above example
Function Arguments
We can call function by passing arguments. Let’s see the example of function that
has one argument.
1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>
Output of the above example
Function with Return Value
We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.
1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
22
6. <script>
7. document.write(getInfo());
8. </script>
Test it Now
Output of the above example
hello javatpoint! How r u?
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method).
For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1. object={property1:value1,property2:value2.....propertyN:valueN}
1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
23
4. </script>
Test it Now
Output of the above example
102 Shyam Kumar 40000
1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>
Test it Now
Output of the above example
101 Ravi 50000
Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
24
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10.</script>
Test it Now
Output of the above example
103 Vimal Jaiswal 30000
We can define method in JavaScript object. But before defining method, we need
to add property in the function with same name as method.
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10.}
11.}
12.e=new emp(103,"Sonoo Jaiswal",30000);
13.document.write(e.id+" "+e.name+" "+e.salary);
14.e.changeSalary(45000);
15.document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16.</script>
Test it Now
Output of the above example
103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000
JavaScript Array
25
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1. 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.
1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>
Test it Now
1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10.}
11.</script>
Test it Now
Output of the above example
Arun
Varun
John
1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>
Test it Now
Output of the above example
Jai
Vijay
Smith
27
JavaScript Array
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1. 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.
1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>
Test it Now
1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10.}
11.</script>
Test it Now
Output of the above example
Arun
Varun
John
1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>
29
Test it Now
Output of the above example
Jai
Vijay
Smith
The JavaScript date object can be used to get year, month and day. You can
display a timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods
to get and set day, month, year, hour, minute and seconds.
Constructor
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
Method Description
getFullYear() returns the year in 4 digit e.g. 2015. It is a new method and
suggested than getYear() which is now deprecated.
getMonth() returns the month in 2 digit from 1 to 31.
30
Let's see the simple example to print date object. It prints date and time both.
Output:
Current Date and Time: Thu Oct 08 2015 09:29:13 GMT+0530 (India Standard
Time)
Output:
31
Let's see the simple example to display digital clock using JavaScript date object.
Output:
Current Time:
The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.
Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.
Output:
Output:
The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.
Output:
33
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.
Output:
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.
Output:
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.
6. </script>
Test it Now
Output:
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.
Output:
The JavaScript number object enables you to represent a numeric value. It may
be integer or floating-point. JavaScript number object follows IEEE standard to
represent the floating-point numbers.
By the help of Number() constructor, you can create number object in JavaScript.
For example:
Output:
Constant Description
MIN_VALUE returns the largest minimum value.
MAX_VALUE returns the largest maximum value.
POSITIVE_INFINITY returns positive infinity, overflow value.
NEGATIVE_INFINITY returns negative infinity, overflow value.
NaN represents "Not a Number" value.
Methods Description
toExponential(x) displays exponential value.
toFixed(x) limits the number of digits after decimal value.
toPrecision(x) formats the number with given number of digits.
toString() converts number into string.
valueOf() coverts other type of value into number.
The Browser Object Model (BOM) is used to interact with the browser.
36
The default object of browser is window means you can call all the functions of
window by specifying window or directly. For example:
1. window.alert("hello javatpoint");
is same as:
1. alert("hello javatpoint");
You can use a lot of properties (other objects) defined underneath the window
object like document, history, screen, navigator, location, innerHeight, innerWidth,
Visit the next page to learn about window object fully with example.
Window Object
1. Window Object
2. Properties of Window Object
3. Methods of Window Object
4. Example of Window Object
Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc.
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.
1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>
It displays the confirm dialog box. It has message with ok and cancel buttons.
38
1. <script type="text/javascript">
2. function msg(){
3. var v= confirm("Are u sure?");
4. if(v==true){
5. alert("ok");
6. }
7. else{
8. alert("cancel");
9. }
10.
11.}
12.</script>
13.
14.<input type="button" value="delete record" onclick="msg()"/>
It displays prompt dialog box for input. It has message and textfield.
1. <script type="text/javascript">
2. function msg(){
3. var v= prompt("Who are you?");
4. alert("I am "+v);
5.
6. }
7. </script>
8.
9. <input type="button" value="click" onclick="msg()"/>
1. <script type="text/javascript">
2. function msg(){
3. open("http://www.javatpoint.com");
39
4. }
5. </script>
6. <input type="button" value="javatpoint" onclick="msg()"/>
1. <script type="text/javascript">
2. function msg(){
3. setTimeout(
4. function(){
5. alert("Welcome to Javatpoint after 2 seconds")
6. },2000);
7.
8. }
9. </script>
10.
11.<input type="button" value="click" onclick="msg()"/>
Click
1. Document Object
2. Properties of document object
3. Methods of document object
4. Example of document object
window.document
Is same as
document
According to W3C - "The W3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts to dynamically access
and update the content, structure, and style of a document."
Let's see the properties of document object that can be accessed and modified by
the document
41
object.
Method Description
write("string") writes the given string on the doucment.
writeln("string") writes the given string on the doucment with
newline character at the end.
getElementById() returns the element having the given id value.
getElementsByName() returns all the elements having the given name
value.
42
In this example, we are going to get the value of input text by user. Here, we are
usingdocument.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with welcome
message.
1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;
4. alert("Welcome: "+name);
5. }
6. </script>
7.
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10.<input type="button" onclick="printvalue()" value="print name"/>
11.</form>
HTML or DOM events are widely used in JavaScript code. JavaScript code is
executed with HTML/DOM events. So before learning JavaScript, let’s have some
idea about events.
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.