SlideShare uma empresa Scribd logo
1 de 63
 JS is a dynamic programming language.
 It is a scripting language (lightweight
programming language) which is designed
to add interactivity to HTML pages.
Developed by
Brendan Eich,
while he was
working for
Netscape
Communications
Corporation.
 Developed under the name Mocha
 Officially called LiveScript when it first shipped in
beta releases of Netscape Navigator 2.0 in September
1995
 But renamed JavaScript when it was deployed in the
Netscape browser version 2.0B3 .
 JavaScript was standardized under ECMA
International for consideration as an industry
standard, and subsequent work resulted in the
version named ECMAScript (European Computer
Manufacturers Association Script)
CONTINUE…
 Interpreted language.
 Easy debugging and testing.
 Embedded within HTML.
 Minimal syntax , easy to learn.
 Platform independent.
 Procedural capabilities.
 Less server interaction.
 Immediate feedback to the visitors.
 Using the <script> tag .
Syntax
<script >
//JS code
</script>
 language : Specify scripting
language you are using.
 src : To access an external script.
 1) <head> section
<html>
<head>
<script >
....//JS
code
</script>
</head>
</html>
 2) <body> section
<html>
<head> .......</head>
<body>
<script >
....//JS code
</script>
</body>
</html>
<html>
<head>
<title> JavaScript Page</title>
</head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
</script>
</body>
</html>
 3) External script
 Used for multiple pages.
 Script will be written as external independent file.
 Have .js extension.
 Referred using “src” attribute.
Example :
<head>
<script src = “myfile.js”>
</script>
</head>
 A variable is a named element in a
program that stores information.
 The following restrictions apply to
variable names:
 Names can contain letters, digits,
underscores, and dollar signs.
 Names must begin with a letter.
 Names can also begin with $ and _ .
 Names are case sensitive.
Syntax
var <variable name> = value ;
Example : var FirstName = “Shah”;
 When you declare a variable within a function, the
variable can only be accessed within that function.
 If you declare a variable outside a function, all the
functions on your page can access it.
 The lifetime of these variables starts when they
are declared, and ends when the page is closed.
 Primitive data types
 Number: integer , floating-point, NaN numbers.
 Boolean: true or false.
 String: a sequence of alphanumeric characters
enclosed in “ ” or ‘ ’.
 Null: the only value is "null" – to represent nothing.
 Complex data types
 Object: a named collection of data.
 Array: a sequence of values (an array is actually a
predefined object.
 Represented by the Array object.
 Index of array runs from 0 to N-1.
 Can store values of different types.
 Syntax
var arrayName = new Array(Array_length);
var arrayName = new Array();
 Dense Array
Each element assigned with a specific value.
arrayName = new Array(value0, value1, value2…);
 Operators are used to handle variables.
 Combination of an operand and operator is referred to as
expression.
 Types of Operator
Arithmetic , Logical , Comparison, String , Conditional.
 Special Operators
 New : Create an instance of object type.
 Delete : Deletes property of an object or an element at an
array index.
 Void : It does not return a value. It is used in JS to return a
URL with no value.
 Logical AND ( && )
OP1 && OP2
 Logical OR ( | | )
OP1 || OP2
 Logical NOT ( ! )
!( OP1 )
 The typeof operator to find the data type of a
JavaScript variable.
Eg :
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof NaN // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns object
 String operator
 These are those operators which are used to perform
operation on string.
 JS only support string concatenation operator ‘+’.
Example : “ ab ” + “ cd ”
 Conditional operator (Ternary operator)
 Condition ? Value1 : Value2 ;
 Consist of 3 Operand – a condition to be evaluated
and two alternative values to be returned based on
the outcome of expression.
 If true , return value1
 If false, return value2
 In JavaScript we have the following
conditional statements:
1) IF
2) IF – ELSE
3) ELSE – IF
4) SWITCH
 Use the if statement to specify a block of
JavaScript code to be executed if a
condition is true.
 Syntax
if (condition) {
block of code to be executed if the
condition is true
}
 Note that if is in lowercase letters.
Uppercase letters (If or IF) will generate a
JavaScript error.
 Example: Make a "Good day" greeting if the
hour is less than 18:00 .
if (hour < 18)
{
greeting = "Good day";
}
 Output
Good day
 Use the else statement to specify a block of
code to be executed if the condition is false.
 Syntax
if (condition) {
block of code to be executed if the condition
is true
}
else {
block of code to be executed if the condition
is false
}
 Example : If the hour is less than 18, create "Good
day" greeting, otherwise "Good evening“.
if (hour < 18)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
 Use the else if statement to specify a new condition if the
first condition is false.
 Syntax
if (condition1) {
block of code to be executed if condition1 is true }
else if (condition2) {
block of code to be executed if the condition1 is false and
condition2 is true }
else{
block of code to be executed if the condition1 is false and
condition2 is false }
Example : If time is less than 10:00, create a "Good
morning" greeting, if not, but time is less than
20:00, create a "Good day" greeting, otherwise a
"Good evening“.
if (time < 10) {
greeting = "Good morning";
}
else if (time < 20) {
greeting = "Good day";
}
else {
greeting = "Good evening";
}
 Use the switch statement to select one of many
blocks of code to be executed.
 Syntax
switch(expression) {
case value1 : code block
break;
case value2 : code block
break;
default : default code block
}
 Example : weekday number to calculate weekday name:
switch (day) {
case 0 : "Sunday“; break;
case 1 : "Monday"; break;
case 2 : "Tuesday"; break;
case 3 : "Wednesday"; break;
case 4 "Thursday"; break;
case 5 : "Friday"; break;
case 6 : "Saturday"; break;
}
JavaScript supports different kinds of loops:
1) for - loops through a block of code a number of
times.
2) while - loops through a block of code while a
specified condition is true.
Syntax
for (exp1; condition; exp2)
{
code block to be executed
}
Example
for (i = 0; i < 5; i++)
{
text += i ;
}
 The for each...in statement iterates a
specified variable over all values of object's
properties. For each distinct property, a
specified statement is executed.
 for each (variable in object)
{ statement }
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt += person[x] + " ";
}
Syntax
while (condition) {
code block to be executed
}
Example
while (i < 10) {
text += i;
i++;
}
 A JavaScript function is a block of code designed to
perform a particular task.
 It often returns a value.
 A JavaScript function is executed when "something"
invokes it (calls it).
 May take zero or more parameters.
 Built-in Functions
1) eval() : evaluates an expression or statement.
eval("3 + 4"); // Returns 7 (Number)
eval("alert('Hello')");// Calls the function alert('Hello')
2)parseInt() : Converts string literals to integers
Parses up to any character that is not part of a valid
integer
parseInt("3 chances") // returns 3
parseInt(" 5 alive") // returns 5
parseInt("How are you") // returns NaN
3)parseFloat() : Finds a floating point value at the
beginning of a string.
parseFloat("3e-1 xyz") // returns 0.3
parseFloat("13.5 abc") // returns 13.5
 var x = 16 + "Volvo";
 var x = 16 + 4 + "Volvo";
 var x = "Volvo" + 16 + 4;
 <script language="javascript">
var a = "334";
var b = 3;
var c = parseInt(a)+b;
var d = a+b;
document.write("parseInt(a)+b = “ c);
document.write(" a+b = “ d);
</script>
 Syntax
function function_name(para1, para2,….)
{
code to be executed
}
 A JavaScript function is defined with
the function keyword, followed by a name, followed by
parentheses ().
 Function names can contain letters, digits,
underscores, and dollar signs (same rules as variables).
 The code to be executed, by the function, is placed
inside curly brackets { } .
 Function arguments are the real values received
by the function when it is invoked.
 Inside the function, the arguments are used as
local variables.
 Example
function myFunction(p1, p2)
{
return p1 * p2;
// returns product of p1 and p2
}
Example : Calculate the product of two numbers, and
return the result.
var x = myFunction(4, 3); // Function is called, return
value will end up in x
function myFunction(a, b)
{
return a * b; // Function returns the product of a and b
}
The result in x will be:
12
 JavaScript can "display" data in different ways:
1. Writing into an alert box,
using window.alert().
2. Writing into the HTML output
using document.write().
3. Writing into an HTML element,
using innerHTML.
4. Writing into the browser console,
using console.log().
You can use an alert box to display
data.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
For testing purposes, it is convenient to
use document. write()
Example
<!DOCTYPE html>
<html>
<body><h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Used to access an HTML element
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById(id);
</script>
</body>
</html>
In your browser, you can use
the console.log() method to display
data.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>
 JavaScript has three kind of popup
boxes:
1) Alert box,
2) Confirm box,
3) Prompt box.
 An alert box is often used if you want to make sure
information comes through to the user.
 When an alert box pops up, the user will have to
click "OK" to proceed.
 Syntax
window.alert("sometext");
 The window.alert() method can be written without
the window prefix.
 Example
alert("I am an alert box!");
 A confirm box is often used if you want the
user to verify or accept something.
 When a confirm box pops up, the user will
have to click either "OK" or "Cancel" to
proceed.
 If the user clicks "OK", the box returns true. If
the user clicks "Cancel", the box returns false.
 Syntax
window.confirm("some text");
The window.confirm() method can be written without the
window prefix.
Example
var r = confirm("Press a button");
if (r == true)
{
x = "You pressed OK!";
}
else
{
x = "You pressed Cancel!";
}
 A prompt box is often used if you want the
user to input a value before entering a page.
 When a prompt box pops up, the user will
have to click either "OK" or "Cancel" to
proceed after entering an input value.
 If the user clicks "OK" the box returns the
input value. If the user clicks "Cancel" the box
returns null.
 Syntax
window.prompt("sometext","defaultText");
The window.prompt() method can be written
without the window prefix.
Example
var person = prompt("Please enter your
name", “Steve");
if (person != null)
{
document.getElementById(id) = "Hello " + person
+ "! How are you ?";
}
Javascript

Mais conteúdo relacionado

Mais procurados

Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
Princess Sam
 

Mais procurados (20)

Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Xml processing in scala
Xml processing in scalaXml processing in scala
Xml processing in scala
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
JavaScript Basics and Trends
JavaScript Basics and TrendsJavaScript Basics and Trends
JavaScript Basics and Trends
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Functions & closures
Functions & closuresFunctions & closures
Functions & closures
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional Way
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 

Semelhante a Javascript

Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
ch samaram
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 

Semelhante a Javascript (20)

csc ppt 15.pptx
csc ppt 15.pptxcsc ppt 15.pptx
csc ppt 15.pptx
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
 
Vb script final pari
Vb script final pariVb script final pari
Vb script final pari
 
VB Script
VB ScriptVB Script
VB Script
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
php&mysql with Ethical Hacking
php&mysql with Ethical Hackingphp&mysql with Ethical Hacking
php&mysql with Ethical Hacking
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Vbscript
VbscriptVbscript
Vbscript
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 
PHP Reviewer
PHP ReviewerPHP Reviewer
PHP Reviewer
 
Vb script tutorial
Vb script tutorialVb script tutorial
Vb script tutorial
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 

Javascript

  • 1.
  • 2.
  • 3.  JS is a dynamic programming language.  It is a scripting language (lightweight programming language) which is designed to add interactivity to HTML pages.
  • 4. Developed by Brendan Eich, while he was working for Netscape Communications Corporation.
  • 5.  Developed under the name Mocha  Officially called LiveScript when it first shipped in beta releases of Netscape Navigator 2.0 in September 1995  But renamed JavaScript when it was deployed in the Netscape browser version 2.0B3 .  JavaScript was standardized under ECMA International for consideration as an industry standard, and subsequent work resulted in the version named ECMAScript (European Computer Manufacturers Association Script) CONTINUE…
  • 6.  Interpreted language.  Easy debugging and testing.  Embedded within HTML.  Minimal syntax , easy to learn.  Platform independent.  Procedural capabilities.  Less server interaction.  Immediate feedback to the visitors.
  • 7.  Using the <script> tag . Syntax <script > //JS code </script>
  • 8.  language : Specify scripting language you are using.  src : To access an external script.
  • 9.  1) <head> section <html> <head> <script > ....//JS code </script> </head> </html>
  • 10.  2) <body> section <html> <head> .......</head> <body> <script > ....//JS code </script> </body> </html>
  • 11. <html> <head> <title> JavaScript Page</title> </head> <body> <h1>First JavaScript Page</h1> <script type="text/javascript"> document.write("<hr>"); document.write("Hello World Wide Web"); document.write("<hr>"); </script> </body> </html>
  • 12.
  • 13.  3) External script  Used for multiple pages.  Script will be written as external independent file.  Have .js extension.  Referred using “src” attribute. Example : <head> <script src = “myfile.js”> </script> </head>
  • 14.  A variable is a named element in a program that stores information.  The following restrictions apply to variable names:  Names can contain letters, digits, underscores, and dollar signs.  Names must begin with a letter.  Names can also begin with $ and _ .  Names are case sensitive.
  • 15. Syntax var <variable name> = value ; Example : var FirstName = “Shah”;  When you declare a variable within a function, the variable can only be accessed within that function.  If you declare a variable outside a function, all the functions on your page can access it.  The lifetime of these variables starts when they are declared, and ends when the page is closed.
  • 16.  Primitive data types  Number: integer , floating-point, NaN numbers.  Boolean: true or false.  String: a sequence of alphanumeric characters enclosed in “ ” or ‘ ’.  Null: the only value is "null" – to represent nothing.  Complex data types  Object: a named collection of data.  Array: a sequence of values (an array is actually a predefined object.
  • 17.  Represented by the Array object.  Index of array runs from 0 to N-1.  Can store values of different types.  Syntax var arrayName = new Array(Array_length); var arrayName = new Array();  Dense Array Each element assigned with a specific value. arrayName = new Array(value0, value1, value2…);
  • 18.
  • 19.
  • 20.  Operators are used to handle variables.  Combination of an operand and operator is referred to as expression.  Types of Operator Arithmetic , Logical , Comparison, String , Conditional.  Special Operators  New : Create an instance of object type.  Delete : Deletes property of an object or an element at an array index.  Void : It does not return a value. It is used in JS to return a URL with no value.
  • 21.
  • 22.  Logical AND ( && ) OP1 && OP2  Logical OR ( | | ) OP1 || OP2  Logical NOT ( ! ) !( OP1 )
  • 23.
  • 24.  The typeof operator to find the data type of a JavaScript variable. Eg : typeof "John" // Returns string typeof 3.14 // Returns number typeof NaN // Returns number typeof false // Returns boolean typeof [1,2,3,4] // Returns object
  • 25.  String operator  These are those operators which are used to perform operation on string.  JS only support string concatenation operator ‘+’. Example : “ ab ” + “ cd ”  Conditional operator (Ternary operator)  Condition ? Value1 : Value2 ;  Consist of 3 Operand – a condition to be evaluated and two alternative values to be returned based on the outcome of expression.  If true , return value1  If false, return value2
  • 26.  In JavaScript we have the following conditional statements: 1) IF 2) IF – ELSE 3) ELSE – IF 4) SWITCH
  • 27.  Use the if statement to specify a block of JavaScript code to be executed if a condition is true.  Syntax if (condition) { block of code to be executed if the condition is true }  Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
  • 28.  Example: Make a "Good day" greeting if the hour is less than 18:00 . if (hour < 18) { greeting = "Good day"; }  Output Good day
  • 29.  Use the else statement to specify a block of code to be executed if the condition is false.  Syntax if (condition) { block of code to be executed if the condition is true } else { block of code to be executed if the condition is false }
  • 30.  Example : If the hour is less than 18, create "Good day" greeting, otherwise "Good evening“. if (hour < 18) { greeting = "Good day"; } else { greeting = "Good evening"; }
  • 31.  Use the else if statement to specify a new condition if the first condition is false.  Syntax if (condition1) { block of code to be executed if condition1 is true } else if (condition2) { block of code to be executed if the condition1 is false and condition2 is true } else{ block of code to be executed if the condition1 is false and condition2 is false }
  • 32. Example : If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a "Good day" greeting, otherwise a "Good evening“. if (time < 10) { greeting = "Good morning"; } else if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; }
  • 33.  Use the switch statement to select one of many blocks of code to be executed.  Syntax switch(expression) { case value1 : code block break; case value2 : code block break; default : default code block }
  • 34.  Example : weekday number to calculate weekday name: switch (day) { case 0 : "Sunday“; break; case 1 : "Monday"; break; case 2 : "Tuesday"; break; case 3 : "Wednesday"; break; case 4 "Thursday"; break; case 5 : "Friday"; break; case 6 : "Saturday"; break; }
  • 35. JavaScript supports different kinds of loops: 1) for - loops through a block of code a number of times. 2) while - loops through a block of code while a specified condition is true.
  • 36. Syntax for (exp1; condition; exp2) { code block to be executed } Example for (i = 0; i < 5; i++) { text += i ; }
  • 37.  The for each...in statement iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
  • 38.  for each (variable in object) { statement }
  • 39. <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var txt = ""; var person = {fname:"John", lname:"Doe", age:25}; var x; for (x in person) { txt += person[x] + " "; }
  • 40. Syntax while (condition) { code block to be executed } Example while (i < 10) { text += i; i++; }
  • 41.  A JavaScript function is a block of code designed to perform a particular task.  It often returns a value.  A JavaScript function is executed when "something" invokes it (calls it).  May take zero or more parameters.  Built-in Functions 1) eval() : evaluates an expression or statement. eval("3 + 4"); // Returns 7 (Number) eval("alert('Hello')");// Calls the function alert('Hello')
  • 42. 2)parseInt() : Converts string literals to integers Parses up to any character that is not part of a valid integer parseInt("3 chances") // returns 3 parseInt(" 5 alive") // returns 5 parseInt("How are you") // returns NaN 3)parseFloat() : Finds a floating point value at the beginning of a string. parseFloat("3e-1 xyz") // returns 0.3 parseFloat("13.5 abc") // returns 13.5
  • 43.  var x = 16 + "Volvo";  var x = 16 + 4 + "Volvo";  var x = "Volvo" + 16 + 4;
  • 44.  <script language="javascript"> var a = "334"; var b = 3; var c = parseInt(a)+b; var d = a+b; document.write("parseInt(a)+b = “ c); document.write(" a+b = “ d); </script>
  • 45.  Syntax function function_name(para1, para2,….) { code to be executed }  A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().  Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).  The code to be executed, by the function, is placed inside curly brackets { } .
  • 46.  Function arguments are the real values received by the function when it is invoked.  Inside the function, the arguments are used as local variables.  Example function myFunction(p1, p2) { return p1 * p2; // returns product of p1 and p2 }
  • 47. Example : Calculate the product of two numbers, and return the result. var x = myFunction(4, 3); // Function is called, return value will end up in x function myFunction(a, b) { return a * b; // Function returns the product of a and b } The result in x will be: 12
  • 48.  JavaScript can "display" data in different ways: 1. Writing into an alert box, using window.alert(). 2. Writing into the HTML output using document.write(). 3. Writing into an HTML element, using innerHTML. 4. Writing into the browser console, using console.log().
  • 49. You can use an alert box to display data.
  • 50. Example <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> window.alert(5 + 6); </script> </body> </html>
  • 51. For testing purposes, it is convenient to use document. write()
  • 52. Example <!DOCTYPE html> <html> <body><h1>My First Web Page</h1> <p>My first paragraph.</p> <script> document.write(5 + 6); </script> </body> </html>
  • 53. Used to access an HTML element
  • 54. Example <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My First Paragraph</p> <p id="demo"></p> <script> document.getElementById(id); </script> </body> </html>
  • 55. In your browser, you can use the console.log() method to display data.
  • 56. Example <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> console.log(5 + 6); </script> </body> </html>
  • 57.  JavaScript has three kind of popup boxes: 1) Alert box, 2) Confirm box, 3) Prompt box.
  • 58.  An alert box is often used if you want to make sure information comes through to the user.  When an alert box pops up, the user will have to click "OK" to proceed.  Syntax window.alert("sometext");  The window.alert() method can be written without the window prefix.  Example alert("I am an alert box!");
  • 59.  A confirm box is often used if you want the user to verify or accept something.  When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.  If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.  Syntax window.confirm("some text");
  • 60. The window.confirm() method can be written without the window prefix. Example var r = confirm("Press a button"); if (r == true) { x = "You pressed OK!"; } else { x = "You pressed Cancel!"; }
  • 61.  A prompt box is often used if you want the user to input a value before entering a page.  When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.  If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.  Syntax window.prompt("sometext","defaultText");
  • 62. The window.prompt() method can be written without the window prefix. Example var person = prompt("Please enter your name", “Steve"); if (person != null) { document.getElementById(id) = "Hello " + person + "! How are you ?"; }