Unit 3 : BUILD INTERACTIVE USER
INTERFACE OF WEB APPLICATION
Printing to Console
[Link]("Welcome");
- Displays output in the browser console.
- Helpful for debugging and testing.
[Link]() - Clears the console
[Link]() -Displays tabular data as a table
[Link]() - Starts a timer (can track how long
an operation takes)
[Link]() - Outputs an error message to the
console
Declaring Variables
fullName = "DEPSTAR CHARUSAT";
age = 24;
price = 99.99;
radius = 14;
a = null;
y = undefined;
isFollow = false;
[Link](isFollow);
- JavaScript is dynamically typed.
- Variables can hold different types over time.
Variable Naming Rules
var name,
var fullname,
var FULLNAME,
var _fullname,
var $fullname;
- Use camelCase for readability.
- Variable names are case-sensitive.
- Can include letters, digits, $, and _.
var vs let vs const
var age = 24;
var age = 54; // Re-declared and update can be possible
let age1 = 24;
let age1 = 86; // ❌ Error: Cannot re-declare but can update
const b; // ❌ Error: Must be initialized
Const PI=3.14;
- var: Re-declared & updated ✅
- let: Updated ✅, Re-declared ❌
- const: Neither updated ❌ nor re-declared ❌
Undefined & Null
let a;
[Link](a); // undefined
- undefined: Variable declared but not assigned.
- null: Intentionally empty or unknown.
Primitive Data Types (7 Types)
- Number
- String
- Boolean
- Undefined
- Null
- Symbol
- BigInt
typeof variable_name;
e.g. typeof firstName;
Use for identify the used data type
Non Primitive Data Types
Non primitive data types:
Objects(array, functions)
// it is collection of value
Objects will be like key-pair
E.g.
const student = {
fullName : "Rahul Kumar",
age:20,
sgpa:8.0,
isPass:true
}
To access above object data
We can use [Link], obj["key"]
E.g. student["age"] = student["age"]
+ 1;
[Link](student["age"]);
Practice Question
• Create a const object called a “product” to
store information shown in the picture.
Comments in JavaScript
// This is a single-line comment
/* This is a
multi-line comment */
JavaScript Output
JavaScript can "display" data in different ways:
• Writing into an HTML element,
using innerHTML or innerText.
• Writing into the HTML output
using [Link]().
• Writing into an alert box, using [Link]().
• Writing into the browser console, using [Link]().
Arithmetic Operators
let a = 10, b = 5;
[Link](a + b); // 15
[Link](a - b); // 5
[Link](a * b); // 50
[Link](a / b); // 2
Modulus Operator
let a = 10, b = 3;
[Link](a % b); // 1
Exponential Operator
let a = 2;
[Link](a ** 3); // 8
Increment & Decrement
let a = 5;
a++;
[Link](a); // 6
b = 5;
--b;
[Link](b); // 4
Assignment Operators
Assignment Operator(=, +=, -=,*=, %=, **=)
let a = 10;
a += 5;
[Link](a); // 15
a *= 2;
[Link](a); // 30
Comparison Operators
Comparison Operators(==, !=, Equal to &
type(strict) ===, Not equal to & type !==,
>,>=,<,<=)
[Link](5 == '5'); // true
[Link](5 === '5'); // false
[Link](10 != 5); // true
[Link](10 > 5); // true
Logical Operators
let a = 5, b = 10;
[Link](a > 0 && b > 0); // true
[Link](a > 0 || b < 0); // true
[Link](!(a > 0)); // false
JavaScript Loops
The For Loop
The for statement creates a loop with 3 optional expressions:
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
Expression 1 is executed (one time) before the execution of the
code block.
Expression 2 defines the condition for executing the code block.
Expression 3 is executed (every time) after the code block has
been executed.
JavaScript Loops
<p id="demo"></p>
<script>
let text = "";
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
[Link]("demo").innerHTML = text;
</script>
JavaScript Loops
The For In Loop
The JavaScript for in statement loops through the
properties of an Object:
const person = {fname:"John", lname:"Doe", age:25};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
}
JavaScript Loops
The While Loop
The while loop loops through a block of code as long as
a specified condition is true.
Syntax
while (condition) {
// code block to be executed
}
JavaScript Loops
The Do While Loop
The do while loop is a variant of the while loop.
This loop will execute the code block once, before
checking if the condition is true, then it will repeat the
loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
Conditional Statements
In JavaScript we have the following conditional
statements:
• Use if to specify a block of code to be executed, if a
specified condition is true
• Use else to specify a block of code to be executed, if
the same condition is false
• Use else if to specify a new condition to test, if the
first condition is false
• Use switch to specify many alternative blocks of code
to be executed
Ternary Operator
let age = 20;
let status = (age >= 18) ? 'Adult' : 'Minor';
[Link](status);
JavaScript Popup Boxes
• Alert 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
• [Link]("sometext");
JavaScript Popup Boxes
• Confirm 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
• [Link]("sometext");
JavaScript Popup Boxes
• Prompt Box
• 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
• [Link]("sometext","defaultText");
Practice
• Q-1. Get user to input a number using
prompt(“Enter a number:”). Check if the
number is a multiple of 5 or not.
Practice
Q-2. Write a code which can give grades to
students according to their scores:
90-100,A
70-89,B
60-69,C
50-59,D
0-49,F
What is an Array?
• Collection of items stored in a single variable
• let arr = [1, 2, 3, 4];
• let fruits = ["apple", "banana", "mango"];
• [Link](fruits[0]); // apple
String: Immutable
• let str = "hello";
• str[0] = "H";
• [Link](str); // 'hello' (unchanged)
Array: Mutable
• let arr = [1, 2, 3];
• arr[0] = 10;
• [Link](arr); // [10, 2, 3]
Loop over Array (for loop)
• let students = ["Hitesh", "Vijay", "Ashish"];
• for (let i = 0; i < [Link]; i++) {
• [Link](students[i]);
• }
JavaScript Loops
The For Of Loop
The JavaScript for of statement loops through the values
of an iterable object.
It lets you loop over iterable data structures such as
Arrays, Strings, Maps, NodeLists, and more:
Syntax
for (variable of iterable) {
// code block to be executed
}
Array Methods
push() Method
• add(original) to end(single or multiple items
can be added),
• let arr = [1, 2];
• [Link](3);
• [Link](arr); // [1, 2, 3]
pop() Method
• delete from the end and return the deleted
value,
• let arr = [1, 2, 3];
• let x = [Link]();
• [Link](x); // 3
• [Link](arr); // [1, 2]
toString() Method
• convert array to string, no change to original
• let arr = [1, 2, 3];
• [Link]([Link]()); // '1,2,3’
• some methods change array, some make new
array
concat() Method
• Joins multiple arrays and returns the result
• let a = [1, 2];
• let b = [3, 4];
• let c = [Link](b);
• [Link](c); // [1, 2, 3, 4]
unshift() Method
• add to start(like push)
• let arr = [2, 3];
• [Link](1);
• [Link](arr); // [1, 2, 3]
shift() Method
• delete from start & return
• let arr = [1, 2, 3];
• [Link]();
• [Link](arr); // [2, 3]
slice() Method
• returns a piece of the array
• slice(startindx,endindx), not change to original
• let arr = [0, 1, 2, 3];
• let newArr = [Link](1, 3);
• [Link](newArr); // [1, 2]
splice() Method
• Change original array(add, remove, replace)
• splice(startidx,delCount,newEl1..)
• let arr = [1, 2, 3, 4];
• [Link](1, 2, 20, 30);
• [Link](arr); // [1, 20, 30, 4]
Practice Example
• Create an array to store companies-
>"Bloomberg","microsoft","Uber","Google","I
BM","Netflix"
• [Link] the first company from the array
• [Link] uber &Add ola in its place
• [Link] amazon at the end
Practice Example
• let companies = ["Bloomberg", "microsoft",
"Uber", "Google", "IBM", "Netflix"];
• [Link]();
• [Link](1, 1, "Ola");
• [Link]("Amazon");
• [Link](companies);
Create a String
• let str = "Hello, World!";
• [Link](str);
String Length & Indices
• let str = "JavaScript";
• [Link]([Link]); // 10
• [Link](str[0]); // J
String Methods in JS
• let str = "hello";
• [Link]([Link]()); // HELLO
• [Link]([Link]()); // hello
trim Method
• let str = " hello world ";
• [Link]([Link]()); // 'hello world'
Immutable Strings
• let str = "hello";
• str[0] = "H";
• [Link](str); // 'hello' (unchanged)
• this method never change to original string
• let str ="Depstar";
• str=[Link]();// it can change original
• in JS strings are immutable(no change)
slice Method
• let str = "JavaScript";
• [Link]([Link](0, 4)); // 'Java'
concat Method
• let str1 = "Hello";
• let str2 = "World";
• [Link]([Link](" ", str2));
• // 'Hello World'
replace Method
• let str = "I like cats";
• [Link]([Link]("cats", "dogs"));
• // 'I like dogs'
charAt Method
• let str = "JavaScript";
• [Link]([Link](4));
• // 'S'
Practice
Type Conversions
• Converting Strings to Numbers
• Converting Numbers to Strings
• Converting Dates to Numbers
• Converting Numbers to Dates
• Converting Booleans to Numbers
• Converting Numbers to Booleans
Converting Strings to Numbers
• The global method Number() converts a variable (or
a value) into a number.
• A numeric string (like "3.14") converts to a number
(like 3.14).
• An empty string (like "") converts to 0.
• A non numeric string (like "John") converts
to NaN (Not a Number).
Converting Numbers to Strings
• The global method String() can convert numbers to
strings.
• It can be used on any type of numbers, literals,
variables, or expressions.
• let x = 123;
• [Link]("demo").innerHTML =
String(x) + "<br>" + String(123) + "<br>" +
String(100 + 23);
Output :
123
123
123
Converting Dates to Numbers
• The global method Number() can be used to convert
dates to numbers.
• d = new Date();
Number(d) // returns 1404568027739
• The date method getTime() does the same.
• d = new Date();
[Link]() // returns 1404568027739
Converting Dates to Strings
• The global method String() can convert dates to
strings.
• String(Date()) // returns "Thu Jul 17 2014
[Link] GMT+0200 (W. Europe Daylight Time)“
• The Date method toString() does the same.
• Date().toString()
Converting Dates to Strings
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since
January 1, 1970)
Converting Booleans to Numbers
• The global method Number() can also convert
booleans to numbers.
• Number(false) // returns 0
Number(true) // returns 1
Converting Booleans to Strings
• The global method String() can convert
booleans to strings.
• String(false) // returns "false"
String(true) // returns "true“
• The Boolean method toString() does the same.
• [Link]() // returns "false"
[Link]() // returns "true"
Automatic Type Conversion
• When JavaScript tries to operate on a "wrong"
data type, it will try to convert the value to a
"right" type.
• The result is not always what you expect.
• "5" + 2 // returns "52“ (because 2 is
converted to "2“)
• "5" - 2 // returns 3 (because "5" is converted
to 5)
• "5" * "2" // returns 10 (because "5" and "2"
are converted to 5 and 2)
JavaScript Math Object
• The JavaScript Math object allows you to
perform mathematical tasks.
• The Math object is static.
• All methods and properties can be used
without creating a Math object first.
JavaScript Math Object
• The JavaScript Math object allows you to
perform mathematical tasks.
• The Math object is static.
• All methods and properties can be used
without creating a Math object first.
• The syntax for any Math property is :
[Link].
• JavaScript provides 8 mathematical constants
that can be accessed as Math properties:
JavaScript Math Object
• [Link](x) Returns x rounded to its nearest
integer
• [Link](x) Returns x rounded up to its nearest
integer
• [Link](x) Returns x rounded down to its
nearest integer
• [Link](x) Returns the integer part of x (new
in ES6)
• [Link](x) returns if x is negative, null or positive.
JavaScript Math Object
• [Link](x, y) returns the value of x to the power of
y.
• [Link](x) returns the square root of x
• [Link](x) returns the absolute (positive) value of x
• [Link]() and [Link]() can be used to find the
lowest or highest value in a list of arguments.
• [Link]() returns a random number between 0
(inclusive), and 1 (exclusive)
• [Link](x) returns the natural logarithm of x
JavaScript Math Object
• Math.E // returns Euler's number
• [Link] // returns PI
• Math.SQRT2 // returns the square root of 2
• Math.SQRT1_2 // returns the square root of 1/2
• Math.LN2 // returns the natural logarithm of 2
• Math.LN10 // returns the natural logarithm of 10
• Math.LOG2E // returns base 2 logarithm of E
• Math.LOG10E // returns base 10 logarithm of E
JavaScript Functions
• A JavaScript function is a block of code designed to
perform a particular task.
• A JavaScript function is executed when "something"
invokes it (calls it).
• Function names can contain letters, digits, underscores,
and dollar signs (same rules as variables).
• Ex:
• function myFunction(p1, p2)
{
return p1 * p2;
}
JavaScript Functions
• Functions can be used the same way as you use
variables, in all types of formulas, assignments, and
calculations.
• Ex: let x = toCelsius(77);
let text = "The temperature is " + x + "
Celsius";
JavaScript Functions
• JavaScript function definitions do not specify data
types for parameters.
• JavaScript functions do not perform type checking on
the passed arguments.
• JavaScript functions do not check the number of
arguments received.
• If a function is called with missing arguments (less
than declared), the missing values are set to
undefined.
Functions as Variables
const greet = function () { [Link]("Hi
there!"); };
greet();
JavaScript Arrow Function
• Arrow functions allow us to write shorter function
syntax:
• let hello = "";
• hello = (val) => "Hello " + val;
• [Link]("demo").innerHTML =
hello("Universe!");
Practice
Practice: countVowels
function countVowels(str){
let count =0;
for(const char of str){
if(char === "a" ||
char ==="e"||
char==="i"||
char==="o“||
char==="u")
count++;
}
}
Practice: countVowels (arrow)
const countVow = (str) =>{
let count =0;
for(const char of str){
if(char === "a" ||
char ==="e"||
char==="i"||
char==="o"||char==="u")
{
count++;
}
}
}
forEach Loop
forEach Loop Arrays
[Link](callBackFunction)
CallbackFunction : Here, it is a function to
execute for each element in the array
A callback is a function pass as an argument to
another function
Callback Example
let arr1 = ["Pune","Ahmedabad", "Mumbai"];
[Link]((val)=>{
[Link]([Link]());
})
let arr1 = ["Pune","Ahmedabad", "Mumbai"];
[Link]((val,indx,arr)=>{
[Link]([Link](),arr);
})
Higher‑Order Functions
• Take another function as argument OR
• Return a function
Examples: forEach, map, filter, reduce
Practice: Square with forEach
let nums = [2, 3, 4];
[Link]((n) => {[Link](n);});
let nums=[2, 3, 4];
let calcSquare=(num)=>{[Link](num**2);}
[Link](calcSquare);
Array Method: map()
Map - Creates a new array with the results of
some operation.
let newArr = [Link]((val)=>{return val*2;})
let arr = [1, 2, 3];
let doubled = [Link]((v) => v * 2);
[Link](doubled); // [2, 4, 6]
Practice: Square using map
let nums = [4, 5, 6];
let squares = [Link]((v) => v ** 2);
[Link](squares);
Array Method: filter()
Create a new array of elements that give true for
a condition/filter.
Eg: All even elements
let arr = [1, 2, 3, 4];
let evenArr = [Link]((val)=>{
return val%2 ===0});
[Link](evenArr); // [2, 4]
Array Method: reduce()
Performs some operations & reduces the array to a signle value. It
returns that single value.
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = [Link](
(accumulator, currentValue) => accumulator + currentValue,
initialValue,
);
[Link](sumWithInitial);
Expected output: 10
const array1 = [1, 2, 3, 4];
const sum = [Link]((acc, cur) => acc + cur, 0);
Practice: Largest with reduce
let nums = [10, 7, 25, 3];
let largest = [Link]((max, cur) => (cur >
max ? cur : max));
[Link](largest); // 25
Practice
Practice: Marks > 90
let marks = [97, 64, 32, 49, 99, 96, 86];
let toppers = [Link]((val) => val > 90);
[Link](toppers);
Practice: Sum & Factorial up to n
let n = promp("enter a number:")
let arr =[];
for(let i=1;i<=n;i++){
arr[i-1]=i;
}
[Link](arr);
let sum = [Link]((res,curr)=>{
return res+curr;
});
[Link](sum);
let fact = [Link]((res,curr)=>{
return res*curr;
});