SlideShare a Scribd company logo
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 (20)

Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students
shafiq sangi
 
JavaScripts & jQuery
JavaScripts & jQueryJavaScripts & jQuery
JavaScripts & jQuery
Asanka Indrajith
 
2javascript web programming with JAVA script
2javascript web programming with JAVA script2javascript web programming with JAVA script
2javascript web programming with JAVA script
umardanjumamaiwada
 
Javascript
JavascriptJavascript
Javascript
20261A05H0SRIKAKULAS
 
Js mod1
Js mod1Js mod1
Js mod1
VARSHAKUMARI49
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
DHTMLExtreme
 
JavaScriptL18 [Autosaved].pptx
JavaScriptL18 [Autosaved].pptxJavaScriptL18 [Autosaved].pptx
JavaScriptL18 [Autosaved].pptx
VivekBaghel30
 
Java script
 Java script Java script
Java script
bosybosy
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)
SANTOSH RATH
 
javascript client side scripting la.pptx
javascript client side scripting la.pptxjavascript client side scripting la.pptx
javascript client side scripting la.pptx
lekhacce
 
Internet Based Programming -3-JAVASCRIPT
Internet Based Programming -3-JAVASCRIPTInternet Based Programming -3-JAVASCRIPT
Internet Based Programming -3-JAVASCRIPT
stevecom2010
 
Java script
Java scriptJava script
Java script
Sadeek Mohammed
 
wp-UNIT_III.pptx
wp-UNIT_III.pptxwp-UNIT_III.pptx
wp-UNIT_III.pptx
GANDHAMKUMAR2
 
1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications
surajshreyans
 
js.pptx
js.pptxjs.pptx
js.pptx
SuhaibKhan62
 
Java script
Java scriptJava script
Java script
Shyam Khant
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
Priya Goyal
 
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
pkaviya
 
Welcome to React.pptx
Welcome to React.pptxWelcome to React.pptx
Welcome to React.pptx
PraveenKumar680401
 
Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students
shafiq sangi
 
2javascript web programming with JAVA script
2javascript web programming with JAVA script2javascript web programming with JAVA script
2javascript web programming with JAVA script
umardanjumamaiwada
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
DHTMLExtreme
 
JavaScriptL18 [Autosaved].pptx
JavaScriptL18 [Autosaved].pptxJavaScriptL18 [Autosaved].pptx
JavaScriptL18 [Autosaved].pptx
VivekBaghel30
 
Java script
 Java script Java script
Java script
bosybosy
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)
SANTOSH RATH
 
javascript client side scripting la.pptx
javascript client side scripting la.pptxjavascript client side scripting la.pptx
javascript client side scripting la.pptx
lekhacce
 
Internet Based Programming -3-JAVASCRIPT
Internet Based Programming -3-JAVASCRIPTInternet Based Programming -3-JAVASCRIPT
Internet Based Programming -3-JAVASCRIPT
stevecom2010
 
1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications
surajshreyans
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
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
pkaviya
 

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

Introduction to Generative AI refers to a subset of artificial intelligence
Introduction to Generative AI refers to a subset of artificial intelligenceIntroduction to Generative AI refers to a subset of artificial intelligence
Introduction to Generative AI refers to a subset of artificial intelligence
Kongu Engineering College, Perundurai, Erode
 
Introduction to Microsoft Power BI is a business analytics service
Introduction to Microsoft Power BI is a business analytics serviceIntroduction to Microsoft Power BI is a business analytics service
Introduction to Microsoft Power BI is a business analytics service
Kongu Engineering College, Perundurai, Erode
 
Connect to NoSQL Database (MongoDB) using Node JS & Connect Node.js with NoSQ...
Connect to NoSQL Database (MongoDB) using Node JS & Connect Node.js with NoSQ...Connect to NoSQL Database (MongoDB) using Node JS & Connect Node.js with NoSQ...
Connect to NoSQL Database (MongoDB) using Node JS & Connect Node.js with NoSQ...
Kongu Engineering College, Perundurai, Erode
 
concept of server-side JavaScript / JS Framework: NODEJS
concept of server-side JavaScript / JS Framework: NODEJSconcept of server-side JavaScript / JS Framework: NODEJS
concept of server-side JavaScript / JS Framework: NODEJS
Kongu Engineering College, Perundurai, Erode
 
Node.js web-based Example :Run a local server in order to start using node.js...
Node.js web-based Example :Run a local server in order to start using node.js...Node.js web-based Example :Run a local server in order to start using node.js...
Node.js web-based Example :Run a local server in order to start using node.js...
Kongu Engineering College, Perundurai, Erode
 
Concepts of Satellite Communication and types and its applications
Concepts of Satellite Communication  and types and its applicationsConcepts of Satellite Communication  and types and its applications
Concepts of Satellite Communication and types and its applications
Kongu Engineering College, Perundurai, Erode
 
Concepts of Mobile Communication Wireless LANs, Bluetooth , HiperLAN
Concepts of Mobile Communication Wireless LANs, Bluetooth , HiperLANConcepts of Mobile Communication Wireless LANs, Bluetooth , HiperLAN
Concepts of Mobile Communication Wireless LANs, Bluetooth , HiperLAN
Kongu Engineering College, Perundurai, Erode
 
Web Technology Introduction framework.pptx
Web Technology Introduction framework.pptxWeb Technology Introduction framework.pptx
Web Technology Introduction framework.pptx
Kongu Engineering College, Perundurai, Erode
 
Computer Network - Unicast Routing Distance vector Link state vector
Computer Network - Unicast Routing Distance vector Link state vectorComputer Network - Unicast Routing Distance vector Link state vector
Computer Network - Unicast Routing Distance vector Link state vector
Kongu Engineering College, Perundurai, Erode
 
Android SQLite database oriented application development
Android SQLite database oriented application developmentAndroid SQLite database oriented application development
Android SQLite database oriented application development
Kongu Engineering College, Perundurai, Erode
 
Android Application Development Programming
Android Application Development ProgrammingAndroid Application Development Programming
Android Application Development Programming
Kongu Engineering College, Perundurai, Erode
 
Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
Kongu Engineering College, Perundurai, Erode
 
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...
Kongu Engineering College, Perundurai, Erode
 
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
Kongu Engineering College, Perundurai, Erode
 
Application Layer.pptx
Application Layer.pptxApplication Layer.pptx
Application Layer.pptx
Kongu Engineering College, Perundurai, Erode
 
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
Kongu Engineering College, Perundurai, Erode
 
Node_basics.pptx
Node_basics.pptxNode_basics.pptx
Node_basics.pptx
Kongu Engineering College, Perundurai, Erode
 
Navigation Bar.pptx
Navigation Bar.pptxNavigation Bar.pptx
Navigation Bar.pptx
Kongu Engineering College, Perundurai, Erode
 
Bootstarp installation.pptx
Bootstarp installation.pptxBootstarp installation.pptx
Bootstarp installation.pptx
Kongu Engineering College, Perundurai, Erode
 
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
Kongu Engineering College, Perundurai, Erode
 
Ad

Recently uploaded (20)

22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank
Guru Nanak Technical Institutions
 
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
BeHappy728244
 
What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...
cyhuutjdoazdwrnubt
 
"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai
Julio Chai
 
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
Journal of Soft Computing in Civil Engineering
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
ijccmsjournal
 
Presentación Tomografía Axial Computarizada
Presentación Tomografía Axial ComputarizadaPresentación Tomografía Axial Computarizada
Presentación Tomografía Axial Computarizada
Juliana Ovalle Jiménez
 
Environmental Engineering Wastewater.pptx
Environmental Engineering Wastewater.pptxEnvironmental Engineering Wastewater.pptx
Environmental Engineering Wastewater.pptx
SheerazAhmed77
 
Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)
kevig
 
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Mohamed905031
 
Structural Health and Factors affecting.pptx
Structural Health and Factors affecting.pptxStructural Health and Factors affecting.pptx
Structural Health and Factors affecting.pptx
gunjalsachin
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
Class-Symbols for vessels ships shipyards.pdf
Class-Symbols for vessels ships shipyards.pdfClass-Symbols for vessels ships shipyards.pdf
Class-Symbols for vessels ships shipyards.pdf
takisvlastos
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
introduction to Digital Signature basics
introduction to Digital Signature basicsintroduction to Digital Signature basics
introduction to Digital Signature basics
DhavalPatel171802
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
Forecasting Road Accidents Using Deep Learning Approach: Policies to Improve ...
Forecasting Road Accidents Using Deep Learning Approach: Policies to Improve ...Forecasting Road Accidents Using Deep Learning Approach: Policies to Improve ...
Forecasting Road Accidents Using Deep Learning Approach: Policies to Improve ...
Journal of Soft Computing in Civil Engineering
 
Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)
elelijjournal653
 
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
Direct Current circuitsDirect Current circuitsDirect Current circuitsDirect C...
BeHappy728244
 
What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...What is dbms architecture, components of dbms architecture and types of dbms ...
What is dbms architecture, components of dbms architecture and types of dbms ...
cyhuutjdoazdwrnubt
 
"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai"The Enigmas of the Riemann Hypothesis" by Julio Chai
"The Enigmas of the Riemann Hypothesis" by Julio Chai
Julio Chai
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...
ijccmsjournal
 
Presentación Tomografía Axial Computarizada
Presentación Tomografía Axial ComputarizadaPresentación Tomografía Axial Computarizada
Presentación Tomografía Axial Computarizada
Juliana Ovalle Jiménez
 
Environmental Engineering Wastewater.pptx
Environmental Engineering Wastewater.pptxEnvironmental Engineering Wastewater.pptx
Environmental Engineering Wastewater.pptx
SheerazAhmed77
 
Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)Call For Papers - International Journal on Natural Language Computing (IJNLC)
Call For Papers - International Journal on Natural Language Computing (IJNLC)
kevig
 
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Mohamed905031
 
Structural Health and Factors affecting.pptx
Structural Health and Factors affecting.pptxStructural Health and Factors affecting.pptx
Structural Health and Factors affecting.pptx
gunjalsachin
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
Class-Symbols for vessels ships shipyards.pdf
Class-Symbols for vessels ships shipyards.pdfClass-Symbols for vessels ships shipyards.pdf
Class-Symbols for vessels ships shipyards.pdf
takisvlastos
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
introduction to Digital Signature basics
introduction to Digital Signature basicsintroduction to Digital Signature basics
introduction to Digital Signature basics
DhavalPatel171802
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)Electrical and Electronics Engineering: An International Journal (ELELIJ)
Electrical and Electronics Engineering: An International Journal (ELELIJ)
elelijjournal653
 
Ad

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