2. JavaScript Introduction
• JavaScript is the programming language of the Web.
• JavaScript (js) is a light-weight object-oriented
programming language
• which is used by several websites for scripting the
webpages.
• It enables dynamic interactivity on websites when applied
to an HTML document.
• It was introduced in the year 1995 for adding programs to
the webpages in the Netscape Navigator browser.
• It adopted by all other graphical web browsers.
• With JavaScript, users can build modern web applications
to interact directly without reloading the page every time.
• The traditional website uses js to provide several forms of
interactivity and simplicity.
Dr.T.Abirami/IT
3. Features of JavaScript
• All popular web browsers support JavaScript as they provide built-
in execution environments.
• JavaScript follows the syntax and structure of the C programming
language. Thus, it is a structured programming language.
• JavaScript is a weakly typed language, where certain types are
implicitly cast (depending on the operation).
• JavaScript is an object-oriented programming language that uses
prototypes rather than using classes for inheritance.
• It is a light-weighted and interpreted language.
• It is a case-sensitive language.
• JavaScript is supportable in several operating systems including,
Windows, macOS, etc.
• It provides good control to the users over the web browsers.
Dr.T.Abirami/IT
4. 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.
Dr.T.Abirami/IT
5. Why Study JavaScript?
• to create web applications
• to javaScript offers lots of flexibility
• to provide users with the most relevant graphical
user interface
• used in mobile app development, desktop app
development, and game development.
• you can find tons of frameworks and libraries already
developed, which can be used directly in web
development. That reduces the development time
and enhances the graphical user interface.
• HTML to define the content of web pages
• CSS to specify the layout of web pages
• JavaScript to program the behavior of web pages
Dr.T.Abirami/IT
6. The <script> Tag
• In HTML, JavaScript code is inserted
between <script> and </script> tags.
Dr.T.Abirami/IT
9. JavaScript Output - 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().
Dr.T.Abirami/IT
10. innerHTML - Definition and Usage
• The innerHTML property sets or returns the
HTML content (inner HTML) of an element.
• The innerHTML is a property of
the Element that allows you to get or set the
HTML markup contained within the element.
• The getElementById() method is one of the
most common methods in the HTML DOM.
• It is used to read or edit an HTML element.
Syntax: document.getElementById(elementID).innerHTML
Dr.T.Abirami/IT
11. <html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "My First
JavaScript";
</script>
</body>
</html>
Dr.T.Abirami/IT
12. 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.
Dr.T.Abirami/IT
13. 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.
Dr.T.Abirami/IT
15. Types of JavaScript Comments
• It is ignored by the JavaScript engine i.e.
embedded in the browser.
There are two types of comments in JavaScript.
• Single-line Comment
• Multi-line Comment
Dr.T.Abirami/IT
17. Multi line Comment
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline
comment");
</script>
Dr.T.Abirami/IT
18. Variable
• variable is simply a name of storage location.
4 Ways to Declare a JavaScript Variable:
• Using var
• Using let
• Using const
• Using nothing
Dr.T.Abirami/IT
19. Example
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
Dr.T.Abirami/IT
21. Getting user input
<html>
<body>
<h1>Conditional statement example</h1>
<h1>
<script>
var a = parseInt(prompt("Enter your a : "));
var b = parseInt(prompt("Enter your b : "));
var c = a+b;
document.write(c);
</script>
</h1>
</body>
</html> The prompt() method displays a dialog box that
prompts the user for input.
The prompt() method returns the input value if the
user clicks "OK", otherwise it returns null.
Dr.T.Abirami/IT
22. const
• constant values cannot be changed.
const price1 = 5;
const price2 = 6;
var total = price1 + price2;
Dr.T.Abirami/IT
24. let
• value of the variable can change, use let.
<html>
<body>
<h1>JavaScript Variables</h1>
<h1>
<script>
let price1 = 5;
let price2 = 66;
let total = price1 + price2;
document.write("result " + " " + total)
</script>
</h1>
</body>
</html>
Dr.T.Abirami/IT
25. • let doesn't allow to redeclare Variables
1. A variable declared with var can be redeclared
again. For example,
var a = 5;
var a = 3;
• A variable declared with let cannot be redeclared
within the same block or same scope. For
example,
let a = 5;
let a = 3; // error
Dr.T.Abirami/IT
26. Data Types
• JavaScript will treat the number as a string
• Numbers can be written with, or without decimals
• Extra large or extra small numbers can be written
with scientific (exponential) notation
let length = 16; // Number
let lastName = "Johnson"; // String
let x = {firstName:"John", lastName:"Doe"};
// Object
Dr.T.Abirami/IT
27. • let x1 = 34.00; // Written with decimals
let x2 = 34; // Written without decimals
• let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
Dr.T.Abirami/IT
28. Data Types
• JavaScript has dynamic types.
• This means that the same variable can be
used to hold different data types
• let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
Dr.T.Abirami/IT
29. Booleans
• Booleans can only have two values: true or false.
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
Dr.T.Abirami/IT
30. Functions
• A JavaScript function is a block of code designed to
perform a particular task.
• A JavaScript function is executed when "something"
invokes it (calls it).
• function is defined with the function keyword,
followed by a name, followed by parentheses ().
function name(parameter1, parameter2, parameter3)
{
// code to be executed
}
Dr.T.Abirami/IT
31. 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)
Dr.T.Abirami/IT
32. 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":
Dr.T.Abirami/IT
33. 3 Methods to Take array input
from user in JavaScript
Dr.T.Abirami/IT
34. 3 Methods to Take array input from
user in JavaScript
• Prompt() to Take array input from user in
JavaScript
• Take array input from user in JavaScript
getElementById()
• getElementsByName() to take array input from
user in JavaScript
Dr.T.Abirami/IT
35. Prompt()
var myinputarr = [];
var size = 5; // Array size
for(var a=0; a<size; a++)
{
myinputarr[a] = prompt('Enter array
Element ‘ + a);
}
document.write(myinputarr);
Dr.T.Abirami/IT
36. <html>
<body>
<script>
add();
function add()
{
var myinputarr = [];
var size = parseInt(prompt("enter value")); // Array size
for(var a=0; a<size; a++)
{
myinputarr[a] = prompt('Enter array Element ' + a);
}
document.write(myinputarr);
}
</script>
</body>
</html>
Dr.T.Abirami/IT
38. <p id="demo"></p>
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
Dr.T.Abirami/IT
40. Conditional Statements
• To perform different actions for different
decisions.
• Use if to specify a block of code to be executed, if
a specified condition is true
• Use else to specify a block of code to be
executed, if the same condition is false
• Use else if to specify a new condition to test, if
the first condition is false
• Use switch to specify many alternative blocks of
code to be executed
Dr.T.Abirami/IT
44. <script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
Dr.T.Abirami/IT
45. <script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Dr.T.Abirami/IT
46. Loops
• 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.
There are four types of loops in JavaScript.
• for loop
• while loop
• do-while loop
• for-in loop
Dr.T.Abirami/IT
50. Difference between Recursion and
Iteration
• A program is called recursive when an entity
calls itself.
• A program is call iterative when there is a loop
(or repetition).
Dr.T.Abirami/IT
51. // ----- Recursion -----
// method to find factorial of given number
int factorialUsingRecursion(int n)
{
if (n == 0)
return 1;
// recursion call
return n * factorialUsingRecursion(n - 1);
}
// ----- Iteration -----
// Method to find the factorial of a given number
int factorialUsingIteration(int n)
{
int res = 1, i;
// using iteration
for (i = 2; i <= n; i++)
res *= i;
return res;
} Dr.T.Abirami/IT
53. // program to find the factorial of a number
function factorial(x) {
// if number is 0
if (x == 0) {
return 1;
}
// if number is positive
else {
return x * factorial(x - 1);
}
}
// take input from the user
const num = prompt('Enter a positive number: ');
// calling factorial() if num is positive
if (num >= 0) {
const result = factorial(num);
console.log(`The factorial of ${num} is ${result}`);
}
else {
console.log('Enter a positive number.');
}
Dr.T.Abirami/IT
54. Variable Explanation Example
String
This is a sequence of text known as a
string. To signify that the value is a
string, enclose it in single quote marks.
let myVariable = 'Bob';
Number
This is a number. Numbers don't have
quotes around them.
let myVariable = 10;
Boolean
This is a True/False value. The
words true and false are special
keywords that don't need quote
marks.
let myVariable = true;
Array
This is a structure that allows you to
store multiple values in a single
reference.
let myVariable =
[1,'Bob','Steve',10];
Refer to each member of the
array like this:
myVariable[0], myVariable[1], etc.
Object
This can be anything. Everything in
JavaScript is an object and can be
stored in a variable. Keep this in mind
as you learn.
let myVariable =
document.querySelector('h1');
All of the above examples too.
Dr.T.Abirami/IT
56. JavaScript scope
• Scope determines the accessibility (visibility) of
variables.
• Scope refers to the availability of variables and
functions in certain parts of the code.
In JavaScript, a variable has two types of scope:
• Global Scope
• Local Scope
Dr.T.Abirami/IT
57. Global Scope
• A variable declared at the top of a program or
outside of a function is considered a global scope
variable.
• // program to print a text
let a = "hello";
function greet ()
{
console.log(a);
}
greet(); // hello
It means the variable a can
be used anywhere in the
program.
Dr.T.Abirami/IT
58. <html>
<body>
<h1>example</h1>
<h1>
<script>
function greet() {
a = "hello"
document.write(a);
}
greet();
</script>
</h1>
</body>
</html>
In JavaScript, a variable can also be used
without declaring it. If a variable is used
without declaring it, that variable
automatically becomes a global variable.
Dr.T.Abirami/IT
59. Local Scope
• Variables declared within a JavaScript function,
become LOCAL to the function.
• // code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
// code here can NOT use carName
Dr.T.Abirami/IT
61. Array
• An array is a special variable, which can hold more than one
value
• An array can hold many values under a single name, and
you can access the values by referring to an index number.
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
Dr.T.Abirami/IT
62. Why Use Arrays?
• If you have a list of items (a list of car names,
for example), storing the cars in single
variables
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
Dr.T.Abirami/IT
64. create an array, and then provide the
elements:
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
Dr.T.Abirami/IT
65. Using the JavaScript Keyword new
const cars = new Array("Saab", "Volvo", "BMW");
<p id="demo"></p>
<script>
const cars = new Array("Saab", "Volvo", "BMW");
document.getElementById("demo").innerHTML = cars;
</script>
Dr.T.Abirami/IT
66. Accessing Array Elements
• You access an array element by referring to
the index number:
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
Dr.T.Abirami/IT
67. Changing an Array Element
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
Dr.T.Abirami/IT
68. Access the Full Array
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML =
cars;
Dr.T.Abirami/IT
69. The length Property
• The length property of an array returns the length of
an array (the number of array elements).
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML =
fruits.length;
</script>
Dr.T.Abirami/IT
70. Looping Array Elements
const fruits =
["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;
let text = "<ul>";
for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
Dr.T.Abirami/IT
74. The Compare Function
• The compare function should return a negative, zero,
or positive value, depending on the arguments:
function(a, b){return a - b}
• When the sort() function compares two values, it sends
the values to the compare function, and sorts the
values according to the returned (negative, zero,
positive) value.
• If the result is negative a is sorted before b.
• If the result is positive b is sorted before a.
• If the result is 0 no changes are done with the sort
order of the two values.
Dr.T.Abirami/IT
75. Example:
• The compare function compares all the values
in the array, two values at a time (a, b).
• When comparing 40 and 100,
the sort() method calls the compare
function(40, 100).
• The function calculates 40 - 100 (a - b), and
since the result is negative (-60), the sort
function will sort 40 as a value lower than 100.
Dr.T.Abirami/IT
76. function bubbleSort(array) {
var done = false;
while (!done) {
done = true;
for (var i = 1; i < array.length; i += 1) {
if (array[i - 1] > array[i]) {
done = false;
var tmp = array[i - 1];
array[i - 1] = array[i];
array[i] = tmp;
}
}
}
return array;
}
var numbers = [12, 10, 15, 11, 14, 13, 16];
bubbleSort(numbers);
console.log(numbers);
Dr.T.Abirami/IT