SlideShare a Scribd company logo
1 of 76
Download to read offline
JavaScript Introduction
Dr.T.Abirami
Associate Professor
Department of IT
Kongu Engineering College
Perundurai
Dr.T.Abirami/IT
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
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
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
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
The <script> Tag
• In HTML, JavaScript code is inserted
between <script> and </script> tags.
Dr.T.Abirami/IT
JavaScript Example
<script>
document.write(“Hello World!” ) ;
</script>
document.write is a JavaScript function that
writes the contents onto the web page.
In this case, it prints “Hello World!” on
screen.
Dr.T.Abirami/IT
<Html>
<body>
<script>
document.write("Hello JavaScript");
</script>
</body>
</html>
Dr.T.Abirami/IT
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
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
<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
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
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
JavaScript Programming
Dr.T.Abirami/IT
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
Single-line Comment
<script>
// It is single line comment
document.write("hello javascript");
</script>
Dr.T.Abirami/IT
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
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
Example
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
Dr.T.Abirami/IT
<html>
<body>
<h1>JavaScript Variables</h1>
<h1>
<script>
var x = 5;
var y = 2;
var z = x + y;
document.write(“ result " + " " + z)
</script>
</h1>
</body>
</html>
Dr.T.Abirami/IT
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
const
• constant values cannot be changed.
const price1 = 5;
const price2 = 6;
var total = price1 + price2;
Dr.T.Abirami/IT
<html>
<body>
<h1>JavaScript Variables</h1>
<h1>
<script>
const price1 = 5;
const price2 = 1;
var total = price1 + price2;
document.write("result " + " " + total)
</script>
</h1>
</body>
</html>
Dr.T.Abirami/IT
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
• 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
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
• 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
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
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
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
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
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
3 Methods to Take array input
from user in JavaScript
Dr.T.Abirami/IT
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
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
<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
<html>
<body>
<h1>Function example</h1>
<h1>
<script>
var x = multi(2, 3);
document.write(x);
function multi(a, b) {
return a * b;
}
</script>
</h1>
</body>
</html>
Dr.T.Abirami/IT
<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
<p id="demo"></p>
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML =
toCelsius;
</script>
Dr.T.Abirami/IT
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
<html>
<body>
<h1>Conditional statement example</h1>
<h1>
<script>
check();
function check() {
var hour = 12
if (hour < 18) {
greeting = "Good day";
document.write(greeting)
}
}
</script>
</h1>
</body>
</html>
Dr.T.Abirami/IT
Getting user input
<html>
<body>
<h1>Conditional statement example</h1>
<h1>
<script>
check();
function check()
{
var hour= window.prompt("Enter your hour: ");
alert("Your hour is " + hour);
if (hour < 18)
{
greeting = "Good day";
document.write(greeting)
}
}
</script> </h1> </body> </html> Dr.T.Abirami/IT
<html>
<body>
<h1>Conditional statement example</h1>
<h1>
<script>
check();
function check() {
var a=123
var b=89
if (a>b)
document.write(a)
else
document.write(b)
}
</script>
</h1>
</body>
</html>
Dr.T.Abirami/IT
<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
<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
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
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
Dr.T.Abirami/IT
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
Dr.T.Abirami/IT
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Dr.T.Abirami/IT
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
// ----- 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
<html>
<body>
<h1>example</h1>
<h1>
<script>
function factorial(x)
{
if (x === 0)
{
return 1;
}
return x * factorial(x-1);
}
document.write(factorial(8));
</script>
</h1>
</body>
</html>
JavaScript recursion function:
Calculate the factorial of a
number
Dr.T.Abirami/IT
// 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
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
JavaScript scope
Dr.T.Abirami/IT
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
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
<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
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
JavaScript Arrays
Dr.T.Abirami/IT
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
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
Creating an Array
Syntax:
const array_name = [item1, item2, ...];
const cars = [
"Saab",
"Volvo",
"BMW"
];
Dr.T.Abirami/IT
create an array, and then provide the
elements:
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
Dr.T.Abirami/IT
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
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
Changing an Array Element
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
Dr.T.Abirami/IT
Access the Full Array
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML =
cars;
Dr.T.Abirami/IT
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
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
Sorting an Array
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML =
fruits;
fruits.sort();
document.getElementById("demo2").innerHTML =
fruits;
</script>
Dr.T.Abirami/IT
Reversing an Array
<script>
// Create and display an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
// First sort the array
fruits.sort();
// Then reverse it:
fruits.reverse();
document.getElementById("demo2").innerHTML = fruits;
</script>
Dr.T.Abirami/IT
Numeric Sort
<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML =
points;
points.sort(function(a, b){return a - b});
document.getElementById("demo2").innerHTML =
points;
</script>
Dr.T.Abirami/IT
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
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
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

More Related Content

Similar to JavaScript_introduction_upload.pdf

JS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTINGJS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTINGArulkumar
 
JavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxJavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxrish15r890
 
gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxsandeshshahapur
 
BITM3730Week6.pptx
BITM3730Week6.pptxBITM3730Week6.pptx
BITM3730Week6.pptxMattMarino13
 
JavaScript : A trending scripting language
JavaScript : A trending scripting languageJavaScript : A trending scripting language
JavaScript : A trending scripting languageAbhayDhupar
 
BITM3730 10-17.pptx
BITM3730 10-17.pptxBITM3730 10-17.pptx
BITM3730 10-17.pptxMattMarino13
 
Java Script basics and DOM
Java Script basics and DOMJava Script basics and DOM
Java Script basics and DOMSukrit Gupta
 
Hsc IT Chap 3. Advanced javascript-1.pdf
Hsc IT Chap 3. Advanced javascript-1.pdfHsc IT Chap 3. Advanced javascript-1.pdf
Hsc IT Chap 3. Advanced javascript-1.pdfAAFREEN SHAIKH
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript TutorialDHTMLExtreme
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentationJohnLagman3
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scriptingpkaviya
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascriptambuj pathak
 
Javascript Basics by Bonny
Javascript Basics by BonnyJavascript Basics by Bonny
Javascript Basics by BonnyBonny Chacko
 

Similar to JavaScript_introduction_upload.pdf (20)

JS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTINGJS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTING
 
Welcome to React.pptx
Welcome to React.pptxWelcome to React.pptx
Welcome to React.pptx
 
Java script
Java scriptJava script
Java script
 
Java script
Java scriptJava script
Java script
 
JavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxJavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptx
 
WTA-MODULE-4.pptx
WTA-MODULE-4.pptxWTA-MODULE-4.pptx
WTA-MODULE-4.pptx
 
gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptx
 
BITM3730Week6.pptx
BITM3730Week6.pptxBITM3730Week6.pptx
BITM3730Week6.pptx
 
JavaScript : A trending scripting language
JavaScript : A trending scripting languageJavaScript : A trending scripting language
JavaScript : A trending scripting language
 
BITM3730 10-17.pptx
BITM3730 10-17.pptxBITM3730 10-17.pptx
BITM3730 10-17.pptx
 
Java Script basics and DOM
Java Script basics and DOMJava Script basics and DOM
Java Script basics and DOM
 
Hsc IT Chap 3. Advanced javascript-1.pdf
Hsc IT Chap 3. Advanced javascript-1.pdfHsc IT Chap 3. Advanced javascript-1.pdf
Hsc IT Chap 3. Advanced javascript-1.pdf
 
UNIT 3.ppt
UNIT 3.pptUNIT 3.ppt
UNIT 3.ppt
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
 
Java script
Java scriptJava script
Java script
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Javascript Basics by Bonny
Javascript Basics by BonnyJavascript Basics by Bonny
Javascript Basics by Bonny
 
Javascript
JavascriptJavascript
Javascript
 

More from Kongu Engineering College, Perundurai, Erode

More from Kongu Engineering College, Perundurai, Erode (20)

Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
 
A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...
 
SOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptxSOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptx
 
Application Layer.pptx
Application Layer.pptxApplication Layer.pptx
Application Layer.pptx
 
Connect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptxConnect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptx
 
Node_basics.pptx
Node_basics.pptxNode_basics.pptx
Node_basics.pptx
 
Navigation Bar.pptx
Navigation Bar.pptxNavigation Bar.pptx
Navigation Bar.pptx
 
Bootstarp installation.pptx
Bootstarp installation.pptxBootstarp installation.pptx
Bootstarp installation.pptx
 
nested_Object as Parameter & Recursion_Later_commamd.pptx
nested_Object as Parameter  & Recursion_Later_commamd.pptxnested_Object as Parameter  & Recursion_Later_commamd.pptx
nested_Object as Parameter & Recursion_Later_commamd.pptx
 
Chapter 3.pdf
Chapter 3.pdfChapter 3.pdf
Chapter 3.pdf
 
Introduction to Social Media and Social Networks.pdf
Introduction to Social Media and Social Networks.pdfIntroduction to Social Media and Social Networks.pdf
Introduction to Social Media and Social Networks.pdf
 
Dropdown Menu or Combo List.pdf
Dropdown Menu or Combo List.pdfDropdown Menu or Combo List.pdf
Dropdown Menu or Combo List.pdf
 
div tag.pdf
div tag.pdfdiv tag.pdf
div tag.pdf
 
Dimensions of elements.pdf
Dimensions of elements.pdfDimensions of elements.pdf
Dimensions of elements.pdf
 
CSS Positioning Elements.pdf
CSS Positioning Elements.pdfCSS Positioning Elements.pdf
CSS Positioning Elements.pdf
 
Random number generation_upload.pdf
Random number generation_upload.pdfRandom number generation_upload.pdf
Random number generation_upload.pdf
 
Computer Networks: Quality of service
Computer Networks: Quality of serviceComputer Networks: Quality of service
Computer Networks: Quality of service
 
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
 
Transport layer services
Transport layer servicesTransport layer services
Transport layer services
 
Transport layer protocols : TCP and UDP
Transport layer protocols  : TCP and UDPTransport layer protocols  : TCP and UDP
Transport layer protocols : TCP and UDP
 

Recently uploaded

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAbhinavSharma374939
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 

Recently uploaded (20)

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 

JavaScript_introduction_upload.pdf

  • 1. JavaScript Introduction Dr.T.Abirami Associate Professor Department of IT Kongu Engineering College Perundurai Dr.T.Abirami/IT
  • 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
  • 7. JavaScript Example <script> document.write(“Hello World!” ) ; </script> document.write is a JavaScript function that writes the contents onto the web page. In this case, it prints “Hello World!” on screen. 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
  • 16. Single-line Comment <script> // It is single line comment document.write("hello javascript"); </script> 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
  • 20. <html> <body> <h1>JavaScript Variables</h1> <h1> <script> var x = 5; var y = 2; var z = x + y; document.write(“ result " + " " + z) </script> </h1> </body> </html> 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
  • 23. <html> <body> <h1>JavaScript Variables</h1> <h1> <script> const price1 = 5; const price2 = 1; var total = price1 + price2; document.write("result " + " " + total) </script> </h1> </body> </html> 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
  • 37. <html> <body> <h1>Function example</h1> <h1> <script> var x = multi(2, 3); document.write(x); function multi(a, b) { return a * b; } </script> </h1> </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
  • 39. <p id="demo"></p> <script> function toCelsius(f) { return (5/9) * (f-32); } document.getElementById("demo").innerHTML = toCelsius; </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
  • 41. <html> <body> <h1>Conditional statement example</h1> <h1> <script> check(); function check() { var hour = 12 if (hour < 18) { greeting = "Good day"; document.write(greeting) } } </script> </h1> </body> </html> Dr.T.Abirami/IT
  • 42. Getting user input <html> <body> <h1>Conditional statement example</h1> <h1> <script> check(); function check() { var hour= window.prompt("Enter your hour: "); alert("Your hour is " + hour); if (hour < 18) { greeting = "Good day"; document.write(greeting) } } </script> </h1> </body> </html> Dr.T.Abirami/IT
  • 43. <html> <body> <h1>Conditional statement example</h1> <h1> <script> check(); function check() { var a=123 var b=89 if (a>b) document.write(a) else document.write(b) } </script> </h1> </body> </html> 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
  • 47. <script> for (i=1; i<=5; i++) { document.write(i + "<br/>") } </script> Dr.T.Abirami/IT
  • 48. <script> var i=11; while (i<=15) { document.write(i + "<br/>"); i++; } </script> Dr.T.Abirami/IT
  • 49. <script> var i=21; do{ document.write(i + "<br/>"); i++; }while (i<=25); </script> 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
  • 52. <html> <body> <h1>example</h1> <h1> <script> function factorial(x) { if (x === 0) { return 1; } return x * factorial(x-1); } document.write(factorial(8)); </script> </h1> </body> </html> JavaScript recursion function: Calculate the factorial of a number 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
  • 63. Creating an Array Syntax: const array_name = [item1, item2, ...]; const cars = [ "Saab", "Volvo", "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
  • 71. Sorting an Array <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; fruits.sort(); document.getElementById("demo2").innerHTML = fruits; </script> Dr.T.Abirami/IT
  • 72. Reversing an Array <script> // Create and display an array: const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; // First sort the array fruits.sort(); // Then reverse it: fruits.reverse(); document.getElementById("demo2").innerHTML = fruits; </script> Dr.T.Abirami/IT
  • 73. Numeric Sort <script> const points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo1").innerHTML = points; points.sort(function(a, b){return a - b}); document.getElementById("demo2").innerHTML = points; </script> 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