Module-1
Module-1
CS380
Web Application
2
CS380
Client Side Scripting
3
CS380
Why use client-side
4
programming?
PHP already allows us to create dynamic
web pages. Why also use client-side
scripting?
client-side scripting (JavaScript) benefits:
CS380
What is Javascript?
6
CS380
Javascript vs Java
8
+ =
CS380
History of JavaScript
10
on servers.
Today – JavaScript powers web, mobile,
CS380
Linking to a JavaScript file:
11
script
<script src="filename" type="text/javascript"></script>
HTML
script tag should be placed in HTML
page's head
script code is stored in a separate .js file
JS code can be placed directly in the
HTML file's body or head (like CSS)
but this is bad style (should separate
content, presentation, and behavior
CS380
Data Types in JavaScript
12
CS380
Primitive Data Types
13
CS380
Non-Primitive (Reference)
14
Data Types
CS380
Example Usage of Different
15
Data Types
// Primitive Types
var name = "Alice"; // String
var age = 30; // Number
var bigNum = 123n; // BigInt
var isStudent = true; // Boolean
var x; // Undefined
var y = null; // Null
var id = Symbol('id');// Symbol
CS380
Example Usage of Different
16
Data Types
// Non-Primitive Types
var person = { name: "Alice", age:
30 }; // Object
var numbers = [1, 2, 3, 4]; //
Array
function sayHello() { //
Function
console.log("Hello!");
}
CS380
Var, let, const
17
CS380
var
18
var x = 10;
function test() {
var x = 20; // Function-scoped (separate from global x)
if (true) {
var x = 30; // ✅ Not block-scoped, overwrites function `x`
console.log("Inside if block:", x); // 30
}
console.log("Inside function, after if block:", x); // 30 (Value
changed due to `var`)
}
test();
console.log("Global scope:", x); // 10 (Unchanged, as function has
its own x)
CS380
let
19
let x = 10;
function test() {
let x = 20; // Function-scoped (separate from global x)
if (true) {
let x = 30; // Block-scoped (exists only inside this if block)
console.log("Inside if block:", x); // 30
}
console.log("Inside function, after if block:", x); // 20
(Unchanged, as if block had its own x)
}
test();
console.log("Global scope:", x); // 10 (Unchanged, as function has
its own x)
CS380
const
20
CS380
Arrays
21
CS380
Using Cosntructor
23
CS380
Array functions
24
CS380
Array functions
25
CS380
Functions
26
CS380
Function with Parameters
27
function add(a, b) {
var r = a + b;
console.log(r); // 8
}
CS380
Function with Parameters &
28
return type
function add(a, b) {
return a + b;
}
console.log(add(6,2)); // 8
CS380
Return multiple values
29
function getValues() {
return 10, 20, 30; // Only 30 is
returned (last value)
}
console.log(getValues()); // Output: 30
CS380
Return multiple values
30
function getCoordinates() {
return [10, 20]; // Returning multiple
values as an array
}
CS380
Functions with same names
31
function add() {
a=20; b=30;
console.log(a+b);
}
function add() {
city = "bangalore";
console.log(city);
}
add();
CS380
Function Expression
32
(Anonymous Function)
const greet = function() {
console.log("Hello!");
};
greet();
CS380
Arrow fucntions
33
CS380
34
// Regular function
function add(a, b) {
return a + b;
}
CS380
callback function
36
CS380
callback function
37
function greet(name, x) {
console.log("Hello, " + name);
x(); // Executing the callback function
}
greet("Umesh", sayGoodbye);
CS380
higher-order function
38
greet("Umesh", sayGoodbye);
CS380
HOF returning a fucntion
40
function greet(name) {
console.log("Hello, " + name);
CS380
Example
42
CS380
String Properties
45
CS380
Common String Methods
46
CS380
Changing Case
47
console.log("hello".toUpperCase()); // Output:
"HELLO"
console.log("WORLD".toLowerCase()); // Output:
"world"
CS380
Finding a Character or Word
48
CS380
Extracting Part of a String
49
CS380
Replacing Text
50
CS380
Splitting a String
51
CS380
Removing Extra Spaces
52
CS380
Repeating a String
53
CS380
Getting a Character from a
54
String
let str = "JavaScript";
console.log(str.charAt(2)); // Output: "v"
console.log(str[2]); // Output: "v"
CS380
Concatenating Strings
55
CS380
Escape Characters
56
CS380
Escape Characters
57
CS380
Example
58
console.log(str1);
console.log(str2);
CS380
console.log(str3);
Example
59
console.log(message);
CS380
Lab Pgm 2
60
CS380
Objects
61
CS380
Creating an Object
62
CS380
1. Object Literal
63
let person = {
name: “Sukesh",
age: 18,
profession: “Student",
greet: function() {
console.log("Hello, my name is
" + this.name);
}
};
CS
Accessing Object Properties
64
console.log(person.age); // Output:
18
console.log(person[" profession "]); //
Output: student
CS380
Adding and Modifying
65
Properties
person.city = "Bangalore"; // Adding new
property
person.age = 18; // Modifying existing
property
console.log(person.city); // "Bangalore"
console.log(person.age); // 18
CS380
Deleting Properties
66
delete person.profession;
console.log(person.profession); //
undefined
CS380
Using this Keyword
67
let employee = {
name: "Anil",
address: {
city: "Mumbai",
country: "India"
}
};
CS380
console.log(employee.address.city); //
2. Using new Object()
69
Syntax
Creates an empty object first, then adds
properties.
Example:
student.name = "Pari";
student.age = 8;
student.study = function() {
console.log(this.name + " is
studying.");
};
CS380
3. Using Constructor
70
Function
Define a function and use this to assign
properties.
Use new to create objects from it.
Example:
this.name = name;
this.age = age;
this.greet = function() {
console.log("Hello, " + this.name);
CS380
};
71
console.log(person1.name); // Output:
Sukesh
person2.greet(); // Output: Hello, Pari
CS380
When to use what?
72
CS380
Array of Objects
73
let students = [
console.log(students[0].name); //
Output: Sukesh
CS380
console.log(students[1].age); // Output:
2. Using Constructor
74
Function
Create multiple objects using a function.
function Student(name, age) {
this.name = name;
this.age = age;
}
let students = [
students.push(student1, student2);
console.log(students[0].name); //
Output: Sukesh
CS380
Iterating on students
77
objects
let students = [
{ name: "Sukesh", age: 10 },
{ name: "Pari", age: 8 },
{ name: "Aarav", age: 12 }
];
if (condition) {
// Code to execute if condition is true
}
CS380
Example:
79
CS380
2. if...else Statement
80
CS380
4. Ternary Operator (Shorter if-
83
else)
A shorthand for if...else statements.
Syntax:
condition ? "true statement" : "false
statement";
Example:
let x = 5;
"Negative";
CS380
5. switch Statement
84
Syntax:
switch (expression) {
case value1:
// Code for case 1
break;
case value2:
// Code for case 2
break;
default:
// Code if no cases match
CS380
}
Example:
85
let day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Invalid day");
}
CS380
Looping Statements in
86
JavaScript
Loops in JavaScript are used to execute a
block of code repeatedly based on a
condition.
1. for Loop
known.
for (initialization; condition;
increment/decrement) {
// Code to execute
}
CS380
2. while Loop
87
while (i <= 5) {
Example:
"JavaScript" };
for (let key in student) {
// Code to execute
}
Example:
console.log(color);
}
CS380
91
CS380
92
CS380
Using forEach() (More
93
Readable)
students.forEach(student => {
console.log(student.name + " is " +
student.age + " years old.");
});
CS380
Using for...of Loop
94
let students = [
{ name: "Sukesh", age: 10 },
{ name: "Pari", age: 8 },
{ name: "Aarav", age: 12 }
];
CS380
Event-driven programming
96
HTML
<button onclick="myFunction();">Click me!</button>
HTML
JavaScript functions can be set as event
handlers
when you interact with the element, the
function will execute
onclick is just one of many event HTML
attributes we'll use
but popping up an alert window is
JS
<button onclick="changeText();">Click me!</button>
<span id="output">replace me</span>
<input id="textbox" type="text" />
HTML
function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");
textbox.style.color = "red";
}
JS
CS380
Accessing elements:
10
document.getElementById
5
document.getElementById returns the
DOM object for an element with a given
id
can change the text inside most
elements by setting the innerHTML
property
can change the text in form controls by
setting the value property
CS380
Changing element style:
10
element.style
6
Property or style
Attribute
object
color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily
CS380
Preetify
10
7
function changeText() {
//grab or initialize text here
CS380
108 More Javascript Syntax
CS380
Variables
10
9
var name = expression; JS
CS380
Math object
11
2
var rand1to10 = Math.floor(Math.random() * 10 + 1);
var three = Math.floor(Math.PI);
JS
CS380
Special values: null and
11
undefined
3
var ned = null;
var benson = 9;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined
JS
CS380
Boolean type
11
6
var iLike190M = true;
var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true */ }
if (0) { /* false */ }
JS
any value can be used as a Boolean
"falsey" values: 0, 0.0, NaN, "", null, and
undefined
"truthy" values: anything else
converting a value into a Boolean
explicitly:
var boolValue = Boolean(otherValue);
CS380
var boolValue = !!(otherValue);
for loop (same as Java)
11
7
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
}
JS
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo"
JS
CS380
while loops (same as Java)
11
8
while (condition) {
statements;
} JS
do {
statements;
} while (condition);
JS
CS380
Popup boxes
11
9
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS
CS380
Arrays
12
0
var name = []; // empty array
var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS
CS380
Array methods
12
1
var a = ["Stef", "Jason"]; // Stef, Jason
a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
a.sort(); // Jason, Stef
JS
array serves as many data structures: list,
queue, stack, ...
methods: concat, join, pop, push, reverse,
shift, slice, sort, splice, toString, unshift
push and pop add / remove from back
unshift and shift add / remove from front
shift and pop return the element that is
removed
String type
12
2
var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" ")); // "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant';
JS
methods: charAt, charCodeAt,
fromCharCode, indexOf, lastIndexOf,
replace, split, substring, toLowerCase,
toUpperCase
charAt returns a one-letter String (there is
no char type)
length property (not a method as in Java)
Strings can be specified with "" or ''
More about String
12
3
escape sequences behave as in Java: \' \"
\& \n \t \\
converting between numbers and
var Strings:
count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah
ah ah!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN JS