Content
• Introduction to JavaScript
• Need of JavaScript
• Example
• JavaScript and Java
• Comments
• Variables
• Identifiers
• Operators
Introduction to JavaScript
What is JavaScript?
Object-based Structured
scripting language JavaScript
programming
Translator
Use of prototypes language
Supplement for Platform
HTML independent
Introduction to JavaScript (contd.)
First introduced in JavaScript allows to
Netscape 2.0 as LiveScript access and manipulate
to add interactive features and content of
features on web the document
Introduction to JavaScript (contd.)
HTML CSS JavaScript
• Content of web • Layout of web • Program
page page behaviour of
web page
Introduction to JavaScript (contd.)
• JavaScript can run on both
Client side
Server side
Need of JavaScript (contd.)
• Decision Making
• Submitting Forms
• Performing complex mathematical functions
• Automatic online data validation
Need of JavaScript(contd.)
Read elements
from
Perform actions documents
based on
Manipulate text
conditions
Create pop-up
Need of Perform
windows JavaScript mathematical
calculations
Retrieve the
Client side
current date
validation
and time
Example
<script>
document.write(“Example of JavaScript");
</script>
Details Script tag: Specifies JavaScript
Text/javaScript: Information to
browser about data
Document.write: Displays dynamic
content through JavaScript
How to add script to HTML Page
• <script>…</script>: used to insert JavaScript
• Any number can be placed in HTML document
How to place JavaScript
JavaScript can
be placed in Between the Between the
external files body tag of html head tag of html
(.js)
JavaScript and Java
JavaScript Java
Interpreted in source code on Complied in bytecode
browser
Integrate into HTML program for Must be compiled before
execution execution
Enhance features of HTML by Powerful language and
providing interactive web pages substitute for C and C++
Doesn’t create applets Create applets
JavaScript Comments
• Uses
To explain JavaScript code
To prevent execution for testing alternative
code
• Types
Single line Comments
Multi-line Comments
Single Line Comments
• Starts with //
• Most commonly used
• Example:
• // Single line comment
• Used at the end of line to explain the code
Multiple Line/ Block Comments
• Starts with /* and end with */
• Example:
• /*
First line of comment
Second line of comment
Third line of comment
*/
JavaScript Variables
• Name of storage location
Basics • Store data
• Equal sign (=): Assign values
Types • Local and Global variable
JavaScript Variables (Contd.)
Identifier Name must start with a letter (a to z or
A to Z), underscore( _ ), or dollar( $ )
sign
After first letter, digits (0 to 9) can be
used
Case sensitive
JavaScript Variables (Contd.)
Variable Declaration
1. var: Used in all older version of JavaScript.
var x;
x = 5;
2. let: Used in newer version of JavaScript, if value of variable
can change
let y;
y = 3;
3. const: Value must be assigned in declaration
const x = 4;
4. Undefined: No value is given
let x;
JavaScript Variables (Contd.)
• Example of variable declaration
const a = 5;
const b = 6;
let total = a + b;
JavaScript Variables(contd.)
Example var a = 11;
var _value=“abc";
<html>
<body>
<script>
var a = 11;
var b = 21;
var z=x+y;
document.write(z);
</script>
</body>
</html>
JavaScript Variables(contd.)
Local Declared inside block or function
variable
<script>
function xyz() {
var x=11; //local variable
}
</script>
JavaScript Variables(contd.)
Global Declared outside the function or declared with
variable window object
<script>
var value=50; //global variable
function a(){
alert(value);
}
function b(){
alert(value);
}
</script>
JavaScript Variables(contd.)
<p id=“example"></p>
<script>
let stdName = “abc";
document.getElementById("example").innerHT
ML = stdName;
</script>
Output: abc
JavaScript Datatypes
Datatypes
Primitive
String, Number, Boolean,
Undefined, Null
Non-primitive (Reference data type)
Object, Array and RegExp
Primitive Datatypes
Datatype Description
String Sequence of characters
Number Numeric values
Boolean Boolean value either true or
false
Undefined Undefined value
Null No value at all
Non-primitive Datatypes
Datatype Description
Object Instance to access members
Array Group of similar values
RegExp Boolean value either true or
false
JavaScript Objects
Basics Entity having properties and methods
Object-based language
Template based, directly create
objects
JavaScript Objects (Contd.)
Object literal
Ways to Instance of object directly
create objects (using new keyword)
Use of object constructor
(using new keyword)
Object literal
Syntax object={property1:value1,property2:value2.....propertyN:valueN}
<script>
std={id:11,name:"Kumar"}
Example document.write(std.id+" "+std.name);
</script>
Output: 11 Kumar
Instance of object directly
Syntax
• var objectname=new Object();
Example
<script>
var std=new Object();
std.id=21;
std.name=“abc";
document.write(std.id+" "+std.name);
</script>
Output: 21 abc
Use of object constructor
Create function with Each argument value can be assigned in
arguments current object using this keyword
This: refers to current object
<script>
function std(id,name){
this.id=id;
this.name=name; Output: 11 abc
}
s=new std(11 ,“abc");
document.write(s.id+" "+s.name);
</script>
Primitive Datatypes
String
• Object represents sequence of
characters to store and
manipulate text
Basics • Either single or double quotes
are required
• let name = “abc”;
Example
• let name = ‘abc’;
Primitive Datatypes (Contd.)
String
Ways to create
string
String literal String object
Created using double Using new keyword
quotes var strname=new String(“NITP");
let name = “abc”; New keyword: Create instance of
string
String Methods
Extracting string parts
slice(start, end) Replacing string
String length
substring(start, end) replace()
substr(start, length)
Converting to upper Extracting String
and lowercase Characters
toUpperCase(): charAt(position)
toLowerCase():
Extracting string parts
• slice(start, end)
• Example:
let str = “NIT Patna Bihar”
let result_1 = str.slice(4,9);
Output: Patna
let result_2 = str.slice(-1,-6);
Output: Bihar
• substr(start, length)
let result_3 = str.substr(4,5);
Output: Patna
Replacing string
replace()
• Replaces a specified value with another value
• Example:
let str = “abc";
let result = str.replace(“abc", “def");
Output: def
Let char = str.charAt(0);
Output: a
Converting to upper and lowercase
toUpperCase():
toLowerCase():
• toUpperCase():
• Example
let str = “Keep It Up”;
let str1 = str. toUpperCase();
Result: KEEP IT UP
• toLowerCase():
• Example
let str2 = str. toLowerCase();
Result: keep it up
String Search Methods
String indexOf() String lastIndexOf()
returns the index of the first returns the index of
occurrence the last occurrence
String startsWith() String endsWith()
returns if a string begins returns if a string ends
String Search Methods (contd.)
• String indexOf()
• Example:
let txt = ”abc def ghi def";
txt.indexOf("def");
Output: 4
• String lastIndexOf()
• Example:
• txt. lastIndexOf(def);
• Output: 12
String startsWith()
• returns true if a string begins with a specified
value
• Example:
let text = " abc def ghi def”
text.startsWith(“abc");
Output: true
let txt = "def ghi def”
txt.startsWith(“abc");
output: false
String endsWith()
• Returns true if a string ends with a specified
value
• Example:
let text = " abc def ghi def”
text.endsWith(“def");
Output: true
Non-primitive Datatypes
Array
• Special variable holds more than one value
• Need of Array
Hold more values under a single name and
Access values individually
Array (contd.)
• Array Declaration (Creating an array)
• Use const for array declaration
• Syntax
Keyword array_name= [element1, element2...];
Example: const arr = [“a”,”b”,…]
• Multiple line declaration can be possible
• Example: const arr = [
“a”,
“b”,
];
• Array declaration and then input elements
• const arr = [];
• arr[0]= “a”;
• arr[1]= “b”;
Accessing Array Elements
• By referring to index number
• Use numbers to access its element
• Index starts with 0
• Example:
const arr = *“a”, “b”, ”c”+;
let arr = arr[0];
Output: a
• Changing an array element
arr[0] = “d”;
Output: d b c
• Full array can be accessed
Accessing Array Elements (contd.)
• Full array can be accessed
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
const arr = ["ab", "cd", "ef"];
document.getElementById("demo").innerHTML = arr;
</script>
</body>
</html>
Array object
• To access its elements, arrays use numbers
• Objects use names to access its members
• Arrays: use numbered indexes
• Objects: use named indexes
• Array.isArray(): method to recognize an array
Array object
Object literal
Instance of array object
Ways to create
directly (using new
objects
keyword)
Use of array constructor
(using new keyword)
Object literal
Syntax Example
• var arrayname=[value1,val <script>
ue2.....valueN]; var std=*“ab",“cd",“ef"+;
for (i=0;i<std.length;i++){
document.write(std[i] + "<br/>");
}
</script>
Use of Array Object directly (new keyword)
Example
<script>
Syntax var i;
var emp = new Array();
• var arrayname=new Array(); emp[0] = "A";
emp[1] = “B";
emp[2] = “C";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Use of array constructor
Example
<script>
Basics var emp=new Array(“A",“B",“C");
for (i=0;i<emp.length;i++){
Passing arguments in document.write(emp[i] + "<br>");
constructor }
</script>
Array Methods
• Converting arrays to strings
join(): Converts an array to a string with
specific separator
Example: const arr = *“a”, “b”, ”c”+;
arr.join(“ - “);
Output: a - b - c
Array properties and methods (contd.)
Length push() and pop()
Push(): Adds a new element to an array
returns length of an array at the end
Pop(): Removes the last element from
an array
Example: const arr =
*“abc", “def", “ghi", “jkl"+; Example of push():const alpha = *“a", “b", “c"+;
let length = arr.length; alpha.push(“d");
Output: 4 Output: a,b,c,d
Example of pop(): const alpha = *“a", “b", “c"+;
alpha.pop();
Output: a,b
Array properties and methods (contd.)
Shift() and Unshift() concat()
shift(): Removes first array
Joins two or more arrays to
element
create new one
unshift(): Adds a new element
at the beginning
const alpha_a = *“a", “b", “c"+;
Example: const alpha = *“a", “b", “c"+;
alpha.shift(); const alpha_b = *“d", “e"+;
Output: b,c
const alpha_c =
const alpha = *“b", “c"+;
alpha.unshift(“a”); alpha_a.concat(alpha_b);
Output: a,b,c Output: a,b,c,d,e
Array properties and methods (contd.)
Splice() slice()
splice(): Adds or removes Slice out a piece of an array
new element at specified into a new array
position
Example: const alpha =
const alpha = *“a", “b", “c“, “d”+;
*“a", “b", “c"+;
alpha.splice(1, 0, “d”); const alpha_s = alpha.slice(1)
Output: a,d,b,c Output: b,c,d
alpha.splice(1, 1);
Output: a,c
Array properties and methods (contd.)
reverse() sort()
Reverses the elements in an
Sorts an array alphabetically
array
Example: const arr =
const alpha = *“a", “b", “c"+; *“b", “e", “a, “c“, “d”+;
alpha.reverse(); arr.sort();
Output: c,b,a Output: a,b,c,d,e
JavaScript Operators
• Symbol is used to perform a calculation in an expression with
two or more values
Arithmetic
operators
Special Logical
operator operators
Types
Bitwise Assignment
operator operators
Comparison String
operators operators
Operators (contd.)
• Performs arithmetic on
Arithmetic number (literals or
operators variables)
• +, -, *,/, %, ++, --,**
Assignment • Assigns value to a variable
operators • =, +=, -=, *=, /=, %=
Operators (contd.)
let x= 5
Arithmetic operators
Symbol Description Example Result
+ Addition x+5 10
- Subtraction x-3 2
* Multiplication x*5 25
/ Division x/5 1
% Modulus x%2 1
++ Increment x++ 6
-- Decrement x-- 4
** Exponentiation x**2 25
Operators (contd.)
Assignment operators
let x = 10;
let y = 5;
Symbol Example using Equivalent Result
shorthand
= a=1 a=1 -
+= x+=y x=x+y 15
-= x-=y x=x-y 5
*= x*=y x=x*y 50
/= x/=y x=x/y 2
%= x%=y x=x%y 0
Operators (contd.)
• + operator/Concatenation operator: To
String concatenate strings
operators • +=: can also be used
• Adding number and string: return string
• ==, !=, > (greater), <(less),>=,<=,
Comparison ?(ternary/conditional)
operators • Variablename = (condition)?value1:
value2
Operators (contd.)
String Operators
• Example 1
let str1 = “NIT”;
let str2 = “Patna”;
let str3 = str1+str2; or let str3 = str1+” ” +str2;
Output: NITPatna Output: NIT Patna
• Example 2
let str1 = “NIT ”;
str1 += “Patna”;
Output: NIT Patna
Operators (contd.)
Comparison Operators
Operator Description Example
== Is equal to 2==1 returns false
1==1returns true
!= Is not equal to 1!=2returns true
1==1returns false
> Is greater than 2>1 returns true
1>2 returns false
>= Is greater than or equal 1>=2returns false
to 2>=1 returns true
<= Is less than or equal to 1<=2returns true
2<=1 returns false
Operators (contd.)
Logical Operators
• Logic between
Logical operators variables and values
• &&(and), II (or), !(not)
Operators (contd.)
Logical Operators
let x = 1;
let y = 2;
Operator Name Example
&& AND x<2 && y>1,
returns true
II OR x<2 II y<2,
returns true
! NOT !(x>y),
returns true
Operators (contd.)
Bitwise Operators
Operator Name
& AND
| OR
^ Bitwise XOR
~ Bitwise NOT
<< Bitwise Left Shift
>> Bitwise Left Shift
>>> Bitwise Right Shift with Zero
Operators (contd.)
Special Operators
Operator Name
(?:) Conditional operator
, Comma operator to evaluate
multiple expressions
delete Deletes property from object
in Checks if object has given property
typeof Checks the type of object
new Creates an object