SlideShare a Scribd company logo
G.ShreeDevi M.E (CSE)
Erode
JAVASCRIPT BASICS
VARIABLES External js file
SYNTAX &STATEMENTS
IF STATEMENT,
WHILE & DO LOOP,
SWITCH CASE,FOR
BREAK AND CONTINUe
OVERVIEW
FUNCTION
PAGE PRINTING STRING & ARRAY
ERROR HANDLING
OVERVIEW
PRT 01
A program is a list of "instructions" to be "executed" by a computer.
JavaScript is used to create client-side dynamic pages.
JavaScript is an object-based scripting language which is lightweight and cross-platform.JavaScript is not a compiled
language, but it is a translated language.
The JavaScript Translator (embedded in the browser) is responsible for translating the JavaScript code for the web
browser.
The programming instructions are called statements.
JavaScript - Syntax
JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script> HTML tags in a web page.
Place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should
keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as a script.
A simple syntax of your JavaScript will appear as follows.
<script ...> JavaScript code </script>
• The script tag takes two important attributes −
• Language − This attribute specifies what scripting language you are using. Typically, its value will
be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the
use of this attribute.
• Type − This attribute is what is now recommended to indicate the scripting language in use and its
value should be set to "text/javascript".
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>
JavaScript in <body> and <head> Sections
• You can put your JavaScript code in <head> and <body> section altogether as follows −
<html>
<head>
<script type = "text/javascript">
function sayHello()
{ alert("Hello World") }
</script>
</head>
<body>
<script type = "text/javascript">
document.write("Hello World“)
</script>
<input type = "button" onclick = "sayHello()“ value = "Say Hello" />
</body>
</html>
STATEMENTS
JavaScript Statements
JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments.
The statements are executed, one by one, in the same order as they a
re written.
Semicolons separate JavaScript statements.
JavaScript White Space
JavaScript ignores multiple spaces. You can add white space to your script to
make it more readable.
The following lines are equivalent:
var person = “ANJU";
var person=“ANJU";
VARIABLES
EXAMPLES
var v1, v2, v3; // Declare 3 variables
v1= 5; // Assign the value 5 to v1
v2= 6; // Assign the value 6 to v2
v3 = a + b; // Assign the sum of v1and v2 to v3
a = 5; b = 6; c = a + b;
var sname= "Anju";
var sname="Anju";
Declaring or Creating JavaScript Variables
Creating a variable in JavaScript is called "declaring" a variable.
Declare a JavaScript variable with the var keyword:
var Studname;
To assign a value to the variable, use the equal sign:
studname = "Anju";
We can assign a valu to the variable when you declare it:
var Studname = “Anju”;
Operators,Expression,Keywords,Comments
JavaScript Keywor
ds
JavaScript keywords are used to identify
actions to be performed.
JavaScript Comme
nts
Code after double slashes // or between /* and */ is tre
ated as a comment.
Comments are ignored, and will not be executed:
Operators
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Expression
An expression is a combination of values, variables, and ope
rators, which computes to a value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50
Operator Description Example
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 20%10 = 0
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9
Arithmetic Operators
Operators Description
== Compares the equality of two
operands without considering
type.
=== Compares equality of two
operands with type.
!= Compares inequality of two
operands.
> Checks whether left side value is
greater than right side value. If
yes then returns true otherwise
false.
< Checks whether left operand is
less than right operand. If yes
then returns true otherwise
false.
>= Checks whether left operand is
greater than or equal to right
operand. If yes then returns true
otherwise false.
<= Checks whether left operand is
less than or equal to right
operand. If yes then returns true
otherwise false.
Comparison Operators
Operator Description
&& && is known as AND operator.
It checks whether two operands
are non-zero (0, false,
undefined, null or "" are
considered as zero), if yes then
returns 1 otherwise 0.
|| || is known as OR operator. It
checks whether any one of the
two operands is non-zero (0,
false, undefined, null or "" is
considered as zero).
! ! is known as NOT operator. It
reverses the boolean result of
the operand (or condition)
Logical Operators
Assignment operators Description
= Assigns right operand value to
left operand.
+= Sums up left and right operand
values and assign the result to
the left operand.
-= Subtract right operand value
from left operand value and
assign the result to the left
operand.
*= Multiply left and right operand
values and assign the result to
the left operand.
/= Divide left operand value by
right operand value and assign
the result to the left operand.
%= Get the modulus of left operand
Assignment Operators
Ternary Operator
JavaScript includes special operator called ternary operator :? that assigns a value to a variable based on some
condition. This is like short form of if-else condition.
Syntax:
<condition> ? <value1> :<value2>;
Example: Ternary operator
var a = 10, b = 5;
var c = a > b? a : b; // value of c would be 10
var d = a > b? b : a; // value of d would be 5
JAVASCRIPT IN EXTERNAL FILE
• The script tag provides a mechanism to allow you to
store JavaScript in an external file and then include it
into your HTML files.
<html>
<head>
<script type = "text/javascript" src = "filename.js" >
</script>
</head>
<body> ....... </body>
</html>
• the following content is saved in filename.js file and then you
can use sayHello function in your HTML file after including the
filename.js file.
function sayHello()
{ alert("Hello World"); }
CONDITIONAL STATEMENTS
For loop
if..else
statement.
switch
statement
The while Loop The do...while Loop
•To use conditional statements that allow your program to make correct
decisions and perform right actions.
• While writing a program, you may encounter a situation where you
need to perform an action over and over again. In such situations, you
would need to write loop statements to reduce the number of lines.
if...else Statement
.
• JavaScript supports conditional statements which
are used to perform different actions based on
different conditions. Here we will explain the
if..else statement. JavaScript supports the
following forms of if..else statement −
• if statement
• if...else statement
• if...else if... statement
Syntax
The syntax for a basic if statement is as follows −
if (expression)
{ Statement(s) to be executed if expression is true }
Syntax
if (expression)
{ Statement(s) to be executed if expression is true }
else
{ Statement(s) to be executed if expression is false }
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1)
{ Statement(s) to be executed if expression 1 is true }
else if (expression 2)
{ Statement(s) to be executed if expression 2 is true }
else if (expression 3)
{ Statement(s) to be executed if expression 3 is true }
else
{ Statement(s) to be executed if no expression is true }
JavaScript - Switch Case
Syntax
The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the
value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing
matches, a default condition will be used.
switch (expression)
{ case condition 1:
statement(s)
break;
case condition 2:
statement(s)
break;
... case condition n:
statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case
JavaScript - While Loops
The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the
loop terminates.
Syntax
The syntax of while loop in JavaScript is as follows −
while (expression)
{
Statement(s) to be executed if expression is true
}
<html>
<body>
<script type = "text/javascript">
var count = 0;
document.write("Starting Loop ");
while (count < 10)
{
document.write("Current Count : " + count + "<br />");
count++;
} document.write("Loop stopped!");
</script>
</body>
</html>
The do...while Loop
The do...while loop is similar to the while loop except that the condition check happens at the end of the
loop
PART 0
Syntax
The syntax for do-while loop in JavaScript is as follows −
do
{ Statement(s) to be executed; }
while (expression);
<html>
<body>
<script type = "text/javascript">
var count = 0;
document.write("Starting Loop" + "<br />");
do
{
document.write("Current Count : " + count + "<br />");
count++;
} while (count < 5);
document.write ("Loop stopped!");
</script>
</body>
</html>
JavaScript for loop
if you want to run the same code over and over again, each time with a different value.
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
<html>
<body>
<script type = "text/javascript">
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++)
{ document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
</script>
</body>
</html>
JavaScript - Loop Control
JavaScript provides break and continue statements. These statements are used to
immediately come out of any loop or to start the next iteration of any loop respectively.
.
The break statementStatement
The break statement, which was briefly introduced with the switch
statement, is used to exit a loop early, breaking out of the enclosing curly
braces.
<html>
<body>
<script type = "text/javascript">
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{ if (x == 5)
break;
}
x = x + 1;
document.write( x + "<br />"); }
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>
The continue Statement
When a continue statement is encountered, the program
flow moves to the loop check expression immediately and
if the condition remains true, then it starts the next
iteration, otherwise the control comes out of the loop.
<html>
<body>
<script type = "text/javascript">
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10)
{ x = x + 1;
if (x == 5)
{
continue; // skip rest of the loop body }
document.write( x + "<br />"); }
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>
JAVASCRIPT - FUNCTIONS
Calling a Function
EXAMPLE
The most common way to define a function in JavaScript is by using the function keyword, followed by a unique
function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
<script type = "text/javascript">
function functionname(parameter-list)
{ statements }
</script>
<script type ="text/javascript">
function sayHello()
{alert("Hello there"); }
</script>
<html> <head>
<script type = "text/javascript">
function sayHello()
{ document.write ("Hello there!"); }
</script> </head>
<body>
<p>Click the following button to call the function</p>
<form> <input type = "button" onclick = "sayHello()" value = "Say Hello"> </form>
<p>Use different text in write method and then try...</p>
</body>
</html>
The return Statement
This is required to return a value from a function. This statement should be the last statement in a function.
<html>
<head>
<script type = "text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{ var result;
result = concatenate(‘snehal', ‘smruti');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form>
</body>
</html>
JAVASCRIPT - PAGE PRINTING
The JavaScript print function window.print() prints the current web page when executed
PART 05
<html>
<head>
<script type="text/javascript">
</script>
</head>
<body>
<form>
<input type="button" value="Print" onclick="window.print()" />
</form>
</body>
<html>
JAVASCRIPT - THE STRINGS
OBJECT
The String parameter is a series of characters that has been properly encode
syntax to create a String object −
var val = new String(string);
Syntax
String Methods
Methods Explanation
length Returns the number of characters in a string
indexOf() Returns the index of the first time the specified
character occurs, or -1 if it never occurs, so
with that index you can determine if the string
contains the specified character.
lastIndexOf() Same as indexOf, only it starts from the right
and moves left.
match() Behaves similar to indexOf and lastIndexOf,
but the match method returns the specified
characters, or "null", instead of a numeric
value.
substr() Returns the characters you specified: (14,7)
returns 7 characters, from the 14th character.
substring() Returns the characters you specified: (7,14)
returns all characters between the 7th and the
14th.
toLowerCase() Converts a string to lower case
toUpperCase() Converts a string to upper case
<html>
<body>
<script type="text/javascript">
var str=“welcome!"
document.write("<p>" + str + "</p>")
document.write("str.length")
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
var str=("Hello JavaScripters!")
document.write(str.toLowerCase())
document.write("<br>")
document.write(str.toUpperCase())
</script>
</body>
</html>
It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data
JAVASCRIPT - THE ARRAYS
OBJECT
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
By array literal
By creating instance of Array directly (using new keyword)
By using an Array constructor (using new keyword)
Syntax Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
var array_name = [item1, item2, ...]; 
var fruits = new Array( "apple", "orange", "mango" );
JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();  
JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we don't have to provide value
explicitly.
The example of creating object by array constructor is given below.
<script>  
var emp=new Array("Jai","Vijay","Smith");  
for (i=0;i<emp.length;i++){  
document.write(emp[i] + "<br>");  
} 
 </SCRIPT>
JavaScript - Errors & Exceptions Handling
Runtime Errors
Runtime errors, also called exceptions, occur during execution
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional programming languages and at interpret time in JavaScript.
Runtime Errors
Runtime errors, also called exceptions, occur during execution
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a
mistake in the logic that drives your script and you do not get the result you expected.
JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions.
The try...catch...finally block syntax −
<script type = "text/javascript">
try
{ // Code to run [break;] }
catch ( e )
{ // Code to run if an exception occurs [break;] }
[ finally { // Code that is always executed regardless of // an exception occurring }]
</script>
<html>
<head>
<script type = "text/javascript">
function disp()
{ var a = 100;
alert("Value of variable a is : " + a );
} </script>
</head>
<body>
<p>Click the following to see the result:</p>
<form> <input type = "button" value = "Click Me" onclick = “disp();" />
</form>
</body>
</html>
Thank You
Ad

More Related Content

What's hot (20)

Javascript 101
Javascript 101Javascript 101
Javascript 101
Shlomi Komemi
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Andres Baravalle
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Bui Kiet
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
CSS Basics
CSS BasicsCSS Basics
CSS Basics
WordPress Memphis
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
cascading style sheet ppt
cascading style sheet pptcascading style sheet ppt
cascading style sheet ppt
abhilashagupta
 
CSS for Beginners
CSS for BeginnersCSS for Beginners
CSS for Beginners
Amit Kumar Singh
 
Js ppt
Js pptJs ppt
Js ppt
Rakhi Thota
 
Html
HtmlHtml
Html
irshadahamed
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
sentayehu
 
jQuery
jQueryjQuery
jQuery
Dileep Mishra
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
WebStackAcademy
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
Dom
DomDom
Dom
Rakshita Upadhyay
 
Php
PhpPhp
Php
Shyam Khant
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
Hassan Dar
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
Fahim Abdullah
 

Similar to Javascript basics (20)

javascriptbasicsPresentationsforDevelopers
javascriptbasicsPresentationsforDevelopersjavascriptbasicsPresentationsforDevelopers
javascriptbasicsPresentationsforDevelopers
Ganesh Bhosale
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
DivyaKS12
 
JAVASCRIPT - LinkedIn
JAVASCRIPT - LinkedInJAVASCRIPT - LinkedIn
JAVASCRIPT - LinkedIn
Gino Louie Peña, ITIL®,MOS®
 
Basics of Javascript
Basics of Javascript Basics of Javascript
Basics of Javascript
poojanov04
 
Java scripts
Java scriptsJava scripts
Java scripts
Capgemini India
 
Unit 2.5
Unit 2.5Unit 2.5
Unit 2.5
Abhishek Kesharwani
 
Unit 2.5
Unit 2.5Unit 2.5
Unit 2.5
Abhishek Kesharwani
 
Introduction to javascript.ppt
Introduction to javascript.pptIntroduction to javascript.ppt
Introduction to javascript.ppt
BArulmozhi
 
Ch3- Java Script.pdf
Ch3- Java Script.pdfCh3- Java Script.pdf
Ch3- Java Script.pdf
HASENSEID
 
Unit 2.4
Unit 2.4Unit 2.4
Unit 2.4
Abhishek Kesharwani
 
Janakiram web
Janakiram webJanakiram web
Janakiram web
MARELLA CHINABABU
 
Javascript tutorial basic for starter
Javascript tutorial basic for starterJavascript tutorial basic for starter
Javascript tutorial basic for starter
Marcello Harford
 
JavaScript Notes 🔥.pdfssssssssssssssssssssssssssssssssssssssssss
JavaScript Notes 🔥.pdfssssssssssssssssssssssssssssssssssssssssssJavaScript Notes 🔥.pdfssssssssssssssssssssssssssssssssssssssssss
JavaScript Notes 🔥.pdfssssssssssssssssssssssssssssssssssssssssss
youssefsoulali2
 
any things about myself and that css tble
any things about myself and that css tbleany things about myself and that css tble
any things about myself and that css tble
sahimhdsm12
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
ch samaram
 
Unit 2.4
Unit 2.4Unit 2.4
Unit 2.4
Abhishek Kesharwani
 
JavaScripttttttttttttttttttttttttttttttttttttttt.ppt
JavaScripttttttttttttttttttttttttttttttttttttttt.pptJavaScripttttttttttttttttttttttttttttttttttttttt.ppt
JavaScripttttttttttttttttttttttttttttttttttttttt.ppt
ankitasaha010207
 
Java script.pptx v
Java script.pptx                                     vJava script.pptx                                     v
Java script.pptx v
22x026
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
adelaticleanu
 
Cordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptCordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to Javascript
Binu Paul
 
javascriptbasicsPresentationsforDevelopers
javascriptbasicsPresentationsforDevelopersjavascriptbasicsPresentationsforDevelopers
javascriptbasicsPresentationsforDevelopers
Ganesh Bhosale
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
DivyaKS12
 
Basics of Javascript
Basics of Javascript Basics of Javascript
Basics of Javascript
poojanov04
 
Introduction to javascript.ppt
Introduction to javascript.pptIntroduction to javascript.ppt
Introduction to javascript.ppt
BArulmozhi
 
Ch3- Java Script.pdf
Ch3- Java Script.pdfCh3- Java Script.pdf
Ch3- Java Script.pdf
HASENSEID
 
Javascript tutorial basic for starter
Javascript tutorial basic for starterJavascript tutorial basic for starter
Javascript tutorial basic for starter
Marcello Harford
 
JavaScript Notes 🔥.pdfssssssssssssssssssssssssssssssssssssssssss
JavaScript Notes 🔥.pdfssssssssssssssssssssssssssssssssssssssssssJavaScript Notes 🔥.pdfssssssssssssssssssssssssssssssssssssssssss
JavaScript Notes 🔥.pdfssssssssssssssssssssssssssssssssssssssssss
youssefsoulali2
 
any things about myself and that css tble
any things about myself and that css tbleany things about myself and that css tble
any things about myself and that css tble
sahimhdsm12
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
ch samaram
 
JavaScripttttttttttttttttttttttttttttttttttttttt.ppt
JavaScripttttttttttttttttttttttttttttttttttttttt.pptJavaScripttttttttttttttttttttttttttttttttttttttt.ppt
JavaScripttttttttttttttttttttttttttttttttttttttt.ppt
ankitasaha010207
 
Java script.pptx v
Java script.pptx                                     vJava script.pptx                                     v
Java script.pptx v
22x026
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
adelaticleanu
 
Cordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptCordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to Javascript
Binu Paul
 
Ad

Recently uploaded (20)

APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
Ad

Javascript basics

  • 2. VARIABLES External js file SYNTAX &STATEMENTS IF STATEMENT, WHILE & DO LOOP, SWITCH CASE,FOR BREAK AND CONTINUe OVERVIEW FUNCTION PAGE PRINTING STRING & ARRAY ERROR HANDLING
  • 4. A program is a list of "instructions" to be "executed" by a computer. JavaScript is used to create client-side dynamic pages. JavaScript is an object-based scripting language which is lightweight and cross-platform.JavaScript is not a compiled language, but it is a translated language. The JavaScript Translator (embedded in the browser) is responsible for translating the JavaScript code for the web browser. The programming instructions are called statements.
  • 5. JavaScript - Syntax JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script> HTML tags in a web page. Place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags. The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear as follows. <script ...> JavaScript code </script>
  • 6. • The script tag takes two important attributes − • Language − This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute. • Type − This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript". <script language = "javascript" type = "text/javascript"> JavaScript code </script>
  • 7. JavaScript in <body> and <head> Sections • You can put your JavaScript code in <head> and <body> section altogether as follows − <html> <head> <script type = "text/javascript"> function sayHello() { alert("Hello World") } </script> </head> <body> <script type = "text/javascript"> document.write("Hello World“) </script> <input type = "button" onclick = "sayHello()“ value = "Say Hello" /> </body> </html>
  • 8. STATEMENTS JavaScript Statements JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments. The statements are executed, one by one, in the same order as they a re written. Semicolons separate JavaScript statements. JavaScript White Space JavaScript ignores multiple spaces. You can add white space to your script to make it more readable. The following lines are equivalent: var person = “ANJU"; var person=“ANJU";
  • 9. VARIABLES EXAMPLES var v1, v2, v3; // Declare 3 variables v1= 5; // Assign the value 5 to v1 v2= 6; // Assign the value 6 to v2 v3 = a + b; // Assign the sum of v1and v2 to v3 a = 5; b = 6; c = a + b; var sname= "Anju"; var sname="Anju"; Declaring or Creating JavaScript Variables Creating a variable in JavaScript is called "declaring" a variable. Declare a JavaScript variable with the var keyword: var Studname; To assign a value to the variable, use the equal sign: studname = "Anju"; We can assign a valu to the variable when you declare it: var Studname = “Anju”;
  • 10. Operators,Expression,Keywords,Comments JavaScript Keywor ds JavaScript keywords are used to identify actions to be performed. JavaScript Comme nts Code after double slashes // or between /* and */ is tre ated as a comment. Comments are ignored, and will not be executed: Operators Arithmetic Operators Comparison Operators Logical (or Relational) Operators Assignment Operators Conditional (or ternary) Operators Expression An expression is a combination of values, variables, and ope rators, which computes to a value. The computation is called an evaluation. For example, 5 * 10 evaluates to 50
  • 11. Operator Description Example + Addition 10+20 = 30 - Subtraction 20-10 = 10 * Multiplication 10*20 = 200 / Division 20/10 = 2 % Modulus (Remainder) 20%10 = 0 ++ Increment var a=10; a++; Now a = 11 -- Decrement var a=10; a--; Now a = 9 Arithmetic Operators
  • 12. Operators Description == Compares the equality of two operands without considering type. === Compares equality of two operands with type. != Compares inequality of two operands. > Checks whether left side value is greater than right side value. If yes then returns true otherwise false. < Checks whether left operand is less than right operand. If yes then returns true otherwise false. >= Checks whether left operand is greater than or equal to right operand. If yes then returns true otherwise false. <= Checks whether left operand is less than or equal to right operand. If yes then returns true otherwise false. Comparison Operators
  • 13. Operator Description && && is known as AND operator. It checks whether two operands are non-zero (0, false, undefined, null or "" are considered as zero), if yes then returns 1 otherwise 0. || || is known as OR operator. It checks whether any one of the two operands is non-zero (0, false, undefined, null or "" is considered as zero). ! ! is known as NOT operator. It reverses the boolean result of the operand (or condition) Logical Operators
  • 14. Assignment operators Description = Assigns right operand value to left operand. += Sums up left and right operand values and assign the result to the left operand. -= Subtract right operand value from left operand value and assign the result to the left operand. *= Multiply left and right operand values and assign the result to the left operand. /= Divide left operand value by right operand value and assign the result to the left operand. %= Get the modulus of left operand Assignment Operators
  • 15. Ternary Operator JavaScript includes special operator called ternary operator :? that assigns a value to a variable based on some condition. This is like short form of if-else condition. Syntax: <condition> ? <value1> :<value2>; Example: Ternary operator var a = 10, b = 5; var c = a > b? a : b; // value of c would be 10 var d = a > b? b : a; // value of d would be 5
  • 16. JAVASCRIPT IN EXTERNAL FILE • The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it into your HTML files. <html> <head> <script type = "text/javascript" src = "filename.js" > </script> </head> <body> ....... </body> </html> • the following content is saved in filename.js file and then you can use sayHello function in your HTML file after including the filename.js file. function sayHello() { alert("Hello World"); }
  • 17. CONDITIONAL STATEMENTS For loop if..else statement. switch statement The while Loop The do...while Loop •To use conditional statements that allow your program to make correct decisions and perform right actions. • While writing a program, you may encounter a situation where you need to perform an action over and over again. In such situations, you would need to write loop statements to reduce the number of lines.
  • 18. if...else Statement . • JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain the if..else statement. JavaScript supports the following forms of if..else statement − • if statement • if...else statement • if...else if... statement Syntax The syntax for a basic if statement is as follows − if (expression) { Statement(s) to be executed if expression is true } Syntax if (expression) { Statement(s) to be executed if expression is true } else { Statement(s) to be executed if expression is false } Syntax The syntax of an if-else-if statement is as follows − if (expression 1) { Statement(s) to be executed if expression 1 is true } else if (expression 2) { Statement(s) to be executed if expression 2 is true } else if (expression 3) { Statement(s) to be executed if expression 3 is true } else { Statement(s) to be executed if no expression is true }
  • 19. JavaScript - Switch Case Syntax The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used. switch (expression) { case condition 1: statement(s) break; case condition 2: statement(s) break; ... case condition n: statement(s) break; default: statement(s) } The break statements indicate the end of a particular case
  • 20. JavaScript - While Loops The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates. Syntax The syntax of while loop in JavaScript is as follows − while (expression) { Statement(s) to be executed if expression is true } <html> <body> <script type = "text/javascript"> var count = 0; document.write("Starting Loop "); while (count < 10) { document.write("Current Count : " + count + "<br />"); count++; } document.write("Loop stopped!"); </script> </body> </html>
  • 21. The do...while Loop The do...while loop is similar to the while loop except that the condition check happens at the end of the loop PART 0 Syntax The syntax for do-while loop in JavaScript is as follows − do { Statement(s) to be executed; } while (expression); <html> <body> <script type = "text/javascript"> var count = 0; document.write("Starting Loop" + "<br />"); do { document.write("Current Count : " + count + "<br />"); count++; } while (count < 5); document.write ("Loop stopped!"); </script> </body> </html>
  • 22. JavaScript for loop if you want to run the same code over and over again, each time with a different value. Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (every time) after the code block has been executed. <html> <body> <script type = "text/javascript"> var count; document.write("Starting Loop" + "<br />"); for(count = 0; count < 10; count++) { document.write("Current Count : " + count ); document.write("<br />"); } document.write("Loop stopped!"); </script> </body> </html>
  • 23. JavaScript - Loop Control JavaScript provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively. . The break statementStatement The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces. <html> <body> <script type = "text/javascript"> var x = 1; document.write("Entering the loop<br /> "); while (x < 20) { if (x == 5) break; } x = x + 1; document.write( x + "<br />"); } document.write("Exiting the loop!<br /> "); </script> </body> </html> The continue Statement When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop. <html> <body> <script type = "text/javascript"> var x = 1; document.write("Entering the loop<br /> "); while (x < 10) { x = x + 1; if (x == 5) { continue; // skip rest of the loop body } document.write( x + "<br />"); } document.write("Exiting the loop!<br /> "); </script> </body> </html>
  • 24. JAVASCRIPT - FUNCTIONS Calling a Function EXAMPLE The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. Syntax <script type = "text/javascript"> function functionname(parameter-list) { statements } </script> <script type ="text/javascript"> function sayHello() {alert("Hello there"); } </script> <html> <head> <script type = "text/javascript"> function sayHello() { document.write ("Hello there!"); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick = "sayHello()" value = "Say Hello"> </form> <p>Use different text in write method and then try...</p> </body> </html>
  • 25. The return Statement This is required to return a value from a function. This statement should be the last statement in a function. <html> <head> <script type = "text/javascript"> function concatenate(first, last) { var full; full = first + last; return full; } function secondFunction() { var result; result = concatenate(‘snehal', ‘smruti'); document.write (result ); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick = "secondFunction()" value = "Call Function"> </form> </body> </html>
  • 26. JAVASCRIPT - PAGE PRINTING The JavaScript print function window.print() prints the current web page when executed PART 05 <html> <head> <script type="text/javascript"> </script> </head> <body> <form> <input type="button" value="Print" onclick="window.print()" /> </form> </body> <html>
  • 27. JAVASCRIPT - THE STRINGS OBJECT The String parameter is a series of characters that has been properly encode syntax to create a String object − var val = new String(string); Syntax String Methods Methods Explanation length Returns the number of characters in a string indexOf() Returns the index of the first time the specified character occurs, or -1 if it never occurs, so with that index you can determine if the string contains the specified character. lastIndexOf() Same as indexOf, only it starts from the right and moves left. match() Behaves similar to indexOf and lastIndexOf, but the match method returns the specified characters, or "null", instead of a numeric value. substr() Returns the characters you specified: (14,7) returns 7 characters, from the 14th character. substring() Returns the characters you specified: (7,14) returns all characters between the 7th and the 14th. toLowerCase() Converts a string to lower case toUpperCase() Converts a string to upper case
  • 28. <html> <body> <script type="text/javascript"> var str=“welcome!" document.write("<p>" + str + "</p>") document.write("str.length") </script> </body> </html> <html> <body> <script type="text/javascript"> var str=("Hello JavaScripters!") document.write(str.toLowerCase()) document.write("<br>") document.write(str.toUpperCase()) </script> </body> </html>
  • 29. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data JAVASCRIPT - THE ARRAYS OBJECT JavaScript array is an object that represents a collection of similar type of elements. There are 3 ways to construct array in JavaScript By array literal By creating instance of Array directly (using new keyword) By using an Array constructor (using new keyword) Syntax Creating an Array Using an array literal is the easiest way to create a JavaScript Array. var array_name = [item1, item2, ...];  var fruits = new Array( "apple", "orange", "mango" ); JavaScript Array directly (new keyword) The syntax of creating array directly is given below: var arrayname=new Array();   JavaScript array constructor (new keyword) Here, you need to create instance of array by passing arguments in constructor so that we don't have to provide value explicitly. The example of creating object by array constructor is given below. <script>   var emp=new Array("Jai","Vijay","Smith");   for (i=0;i<emp.length;i++){   document.write(emp[i] + "<br>");   }   </SCRIPT>
  • 30. JavaScript - Errors & Exceptions Handling Runtime Errors Runtime errors, also called exceptions, occur during execution There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors. Syntax Errors Syntax errors, also called parsing errors, occur at compile time in traditional programming languages and at interpret time in JavaScript. Runtime Errors Runtime errors, also called exceptions, occur during execution Logical Errors Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions. The try...catch...finally block syntax − <script type = "text/javascript"> try { // Code to run [break;] } catch ( e ) { // Code to run if an exception occurs [break;] } [ finally { // Code that is always executed regardless of // an exception occurring }] </script>
  • 31. <html> <head> <script type = "text/javascript"> function disp() { var a = 100; alert("Value of variable a is : " + a ); } </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type = "button" value = "Click Me" onclick = “disp();" /> </form> </body> </html>
  翻译: