0% found this document useful (0 votes)
59 views76 pages

Introduction to JavaScript Basics

The document provides an overview of JavaScript, detailing its history, usage, and fundamental concepts such as data types, variable declarations, and object manipulation. It covers essential JavaScript features including comments, string methods, and array operations, along with examples demonstrating their application. The content is structured over several days, progressively introducing more complex topics related to front-end development with JavaScript.

Uploaded by

abhiram5276
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views76 pages

Introduction to JavaScript Basics

The document provides an overview of JavaScript, detailing its history, usage, and fundamental concepts such as data types, variable declarations, and object manipulation. It covers essential JavaScript features including comments, string methods, and array operations, along with examples demonstrating their application. The content is structured over several days, progressively introducing more complex topics related to front-end development with JavaScript.

Uploaded by

abhiram5276
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Front End Technologies

Javascript - Day 1

Agenda
▪ Javascript
HTML -> Markup Language which is the building block of any website
CSS -> Style sheets which is used to style any website.

Javascript

In order to add interactions to any website we will be using Javascript.

97% of all the websites use javascript.

1990's Internet was bit popular.

1993 -> Mosaic -> GUI(Graphical User Interface)


WWW became very popular because of Mosaic.

Drawback-

Mosaic could handle only static web pages.

1994 started Netscape Corp and stated new project called Netscape Navigator.

Netscape Navigator is a browser which should have Dynamic capabilities.

Brendan Eich -> He was given the task to create a PL which would add dynamic
Capabilies to the browser.

Brendan Eich Developed Livescript.

Livescript is integrated with the browser. It would add the dynamic capabilities to
the browser.

1995 they released Browser Navigator beta version which included a PL called
Livescript

Dec 1995 They changed the name live script to Javascript.


Java was very popular during 1990's. Java + Script = Javascript.

Is there any similarities between Java and Javascript?


No.
Java and Javascript are no where related. But Both Java and Javascript are object
Oriented.

97% of all the web pages uses Javascript.

Previously Javascript was used only at the client side. Now we can use Javascript
on both Client side and Server side.

What is Javascript ? Where is it Used?


Javascript is a text based , Object Oriented Programming Language can be used
both on server side as well as client side which allows us to make webpage
interactive

1) Used for building simple and complex web applications


Example: Google Maps
2) We can use Mobile Apps Using Javascript. (React Native)
3) Game Development ([Link], [Link])
4) Creating Webservers ([Link])

What softwares are needed to start learning Javascript?


Browser.

All JS files must be saved with .js Extension.

How to add JS to a html page.


Front End Technologies
Javascript - Day 2

Agenda
▪ Javascript
[Link]("Hello World"); // Prints the data normally on to the console
[Link]("Debugging in progress"); //Prints the text in blue color
[Link]("This is a warning..."); // Prints the message in Yellow color
[Link]("This is an error"); //Prints the message in red color
[Link]("This is just an Information") ; //Exactly same as that of log

Javascript Comments

There are two types of comments


1) single line comments

Syntax: //
Example:

//[Link]("This is just an Information") ;

Keyboard Shortcut for single line comments


shift + /

2) Block Level Comments

Syntax

/* Your Content */
Example

/*[Link]("Hello World"); // Prints the data normally on to the console


[Link]("Debugging in progress"); //Prints the text in blue color
[Link]("This is a warning..."); // Prints the message in Yellow color*/

Keyboard shortcut

Shift + Alt + A

Variable Declaration Statement.


Whenever we need to declare a variable we need not mention the data type in JS

Whenever we need strict rules to be followed in Javascript then we should use


strict keyword as shown below
syntax:

'use strict';

In order to create variables in Javascript we can use let, var or const.

When we declare a variable using const then it would act like a constant. Once the
value is assigned , then we cant modify that value.

Data types:

10 , 10.5432131, "Sachin"
yes/no (true/false) "C"

number -> In order to handle all the numeric values we can use number datatype.
By default All the numbers are floating points in Javascript.

string -> In order to handle series of characters string datatype is used.


Anything which is enclosed with in double quotes We consider it to be strings.

Example: var str = "Hello";

boolean -> Yes/No of type of data falls under boolean category. In order to handle
yes/no (true/false) type of data we can use boolean

Example:
isCompleted = true;

undefined -> When the variable is declared but it is not defined then the datatype
will be undefined.

Example:
var firstName;
[Link](firstName);
In the above example firstName variable is declared but it is not assigned any
value. So its undefined.

null -> Represents nothing. But null is also a datatype.

All the above datatypes are primitive datatypes.

Primitive datatypes are such datatypes which doesnt have any methods associated
with it.

All the primitives are immutable.

Javascript is weakly typed Programming language. Ie We can assign any type of


data to any variables.

To know what type of data is present in any variable we can use typeof operator.

syntax:

typeof <variable_name>;

Example:

var firstName = "Sachin";

[Link](typeof firstName) // string

var age = 32;


[Link](typeof age) // number

Alternative syntax for typeof Operator


[Link](typeof(age)) // number
Front End Technologies
Javascript - Day 3

Agenda
▪ Data Types
// Primitive Datatypes
number
string
boolean
null
undefined

Object type.

An Object is combination of Properties and Behaviours

Ex:

name
age
gender
qualification
height

walk
run
cry
dance
swim
play

var name = "Sachin";


var age = 27;
var height = 5.11;
var gender = male;
var qualfication = "BE"

->In Javascript We need not have a class to create Objects


-> Object in JS is collection of key, value pairs
-> All the keys inside JS Object must me unique
In order to create an Object in JS We need to follow the below syntax

Syntax:
var object_name = {
key1: <value>,
key2: <value>,
.
.
.
.
.
keyN: <value>,

var person = {
name: "Sucheendra", age: 27, height: 5.11, gender: "Male", qualification: "BE",
}

For all the objects the memory will be allocated in the Heap Memory

Javascript Objects can be created in two ways.

1)
var person = {
name: "Sucheendra", age: 27, height: 5.11, gender: "Male", qualification: "BE",
}

2)

Using Object Constructor.

Example:

var person = new Object();


[Link] = "Sucheendra",
[Link] = 27,
[Link] = "Male"

In order to access or insert the properties inside an object we have 2 approaches

1)

[Link] = "Sucheendra"

2)

person['name'] = "Sucheendra"

We can use any of the above approaches.

Accessing JS Objects
==================

In order to access the JS Objects we can use dot(.) operator or we can use it as
shown below

[Link]([Link]) //Sucheendra
[Link](person['age']) //27

We can follow any of the above approaches to access the Object.

->

We can also add functions inside a JS Object. As shown below

var person = {
name: "Sucheendra",
age: 27,
height: 5.11,
gender: "Male",
qualification: "BE",
dance: function() {
[Link]("Sucheendra is Dancing....!!!")
}
}

[Link]() //Sucheendra is Dancing....!!!

!!!!!Important !!!!!!

From the JSON/JS Object just retrieve only the keys...

Syntax:
[Link](object_name)

Example:

var person = {
name: "Sucheendra",
age: 27,
height: 5.11,
gender: "Male",
qualification: "BE",
dance: function() {
[Link]("Sucheendra is Dancing....!!!")
}
}

var keys = [Link](person);


[Link](keys)

Output:

['name', 'age', 'height', 'gender', 'qualification', 'dance'];

!!!!!Important !!!!!!
From the JSON/JS Object just retrieve only the values...

var values = [Link](person);


[Link](values)

output:

['Sucheendra', 27, 5.11, 'Male', 'BE', dance()]

!!!
When ever we are trying to copy an object always the references gets copied. Not
entire object. In otherwords, Objects are Mutable in JS.
Front End Technologies
Javascript - Day 4

Agenda
▪ Data Types
NaN -> Not a Number

Whenever we try to divide a number by a string or any datatype it results in Nan


example:
100/"s" //NaN

Derive banana without hardcoding character n.

[Link]('ba'+(100/"s")+'a'); //banana

strings.

Collection of characters enclosed with in quotes (single/double) is considered to be


string in JS.

Example

var str = "Sachin"; // Valid

var str2= sachin // Invalid

String concatenation.

Combining one or more strings together is called as concatenation.

Inorder to concat 2 strings we should take the help of + operator.


Example:
var firstName = 'sachin';
var secondName = "Ramesh";
[Link](firstName + " " +secondName);

How to find the length of a given string?


To find the length of a given string we use the length property
Example:

var firstName = "Sachin";


[Link]([Link]) //6
Escape Characters..

Whenever we are enclosing the string within single quote and the string also
contains the single quote then there will be an issue. To resolve that issue we use
escape characters.

Example:
var str = 'it's my computer';
[Link](str); //error

To fix the above error we must include the escape characters as shown below

var str = 'it\'s my computer';


[Link](str); // it's my computer

var str = "This character \\ is a backslash";


[Link](str); //This character \ is a backslash

var str = "it's my \"brothers\" computer";


[Link](str); // it's my "brothers" computer.

How to compare the strings???

Whenever we need to compare any strings we use the syntax as shown below..
We will be using (==) operator as shown below
Example:
var str1 = "Hello";
var str2 = "Hellow";
[Link](str1 == str2);

We can compare strings with strict comparision as shown below

var str1 = "Hello";


//[Link](typeof str1);
var str2 = new String("Hello")
//[Link](typeof str2);
[Link](str1 === str2); false

The above code will return false. Because we are using strict comparision. When
we use strict comparision it will not only check the data. rather it will also check
the type of data. So in our case the type of str1 is string and type of str2 is object.
since both of them are not same it return false.

Important string methods.

1) charAt()
Whenever from a string if we need to extract a specific character we use charAt().
charAt() accpts a index as a parameter.

Example
var str = "HELLO WORLD";

[Link]([Link](4));

Can we access the string like this??


var str = "Hello World";
[Link](str[0]); // H

If the above code is true then is my below code also true???


str[0] = "P"; //TypeError: Cannot assign to read only property '0' of string 'Hello
World'

2) toLowerCase()
All the characters of the string will be converted to lowercases
Example:
var str = "HELLO WORLD";
[Link]([Link]()); //hello world

3) toUpperCase()
All the characters of the string will be converted to uppercases.
var str = "hello world";
[Link]([Link]()); // HELLO WORLD
!!!important
4) slice()
Whenever we want to extract a substring from a string we can use slice()

slice(begin_index);
slice(2) It always starts from index 2
Example:

var str = "Hello World";


[Link]([Link](2)); //It starts extraction from the index2 till the end of the
string

Example-2:

var str = "Hello World"


[Link]([Link](-2)); //It starts extaction from index -2 till the end and it
ignores the value present at the index -2

Example-3:
slice(beginIndex, endIndex);
slice(2, 8);

If we use the above syntax then the extraction starts from the beginIndex and goes
till the endIndex and ignores the character present at the endIndex.

var str = "Hello World";


[Link]([Link](2, 8));

Output: llo Wo

5)substring()
Its almost similar to slice(). The difference between substring and slice() is
substring doesnt support -ve indexes.

Exmple:
var str = "Hello World";
[Link]([Link](-4)); //Hello World

var str = "Hello World";


[Link]([Link](2)); //llo World

6) replace()

When we want to replace a particular string with new string then we use replace
method().

Example:
var str = "Hello World";
[Link]([Link]("Hello", "Hi")); //Hi World

In case we have Multiple occurances of the same string, the replace method would
replace only the first occurance of the string with the new string..

Example:

var str = "Hello Hello World";


[Link]([Link]("Hello", "Hi")); //Hi Hello World

To replace all the occurances with the new string we can't use replace() rather we
should use replaceAll().

Example:

var str = "Hello Hello World";


[Link]([Link]("Hello", "Hi")); //Hi Hi World.

7) trim()

Inorder to remove the whitespaces from the string we use the trim()
Example:
var str = " Hello World ";
[Link]([Link]()+" Hello"); //Hello World Hello

trim() will remove only the whitespaces before and after the string and it wont
remove the whitespaces present between the strings.

8)concat()
It is used to concat two strings.
Example

var str1 = "HELLO";


var str2 = "World";

[Link]([Link](str2)); //HELLOWorld
Front End Technologies
Javascript - Day 5

Agenda
▪ Arrays
substring() vs substr()

substr(3)

substr() is used to extract string from another string.


syntax:
substr(index) -> start at the specified index and move till the end of the string and
extract the string.
Example:
var str = "Hello World";
[Link]([Link](3)); //lo World

Syntax2:
[Link](index, length);

Example2:
[Link]([Link](3, 4));
The above code will start at the index3 and extract the length number of characters.
In our case it will extract 4 characters.

So Output will be lo W

Arrays.
=========

Arrays are a kind of data structure where we can store multiple data. There is no
restriction about the data we are storing.

How to declare an array??


Syntax:

var array_name = [];


or
let array_name = [];
or
const array_name = [];

Example
var arr = [1,2,3,4,5];
[Link](arr) // [1,2,3,4,5]

2nd Approach of declaring arrays

var arr2 = new Array(1,2,3,4,5);


[Link](arr2) // [1,2,3,4,5]

In JS all the arrays declared are dynamic in nature. Ie as we keep on adding data ,
the size of the array keeps on growing.

Example:

var arr = [1, "Sachin", true, {}, 'c', [10, "Ramu", false],7777,"dakdah",true];
[Link]('First Way ',arr); // [1, 'Sachin', true, {…}, 'c', Array(3), 7777,
'dakdah', true]

How can i access the data present in an array?

Arrays can be accessed as shown below.

var arr = [1, "Sachin", true, {}, 'c', [10, "Ramu", false],7777,"dakdah",true];
[Link](arr[5]) //[10, "Ramu", false]

How to get the size of an array?


We can use the length property on the array.
Example
var arr = [1, "Sachin", true, {}, 'c', [10, "Ramu", false],7777,"dakdah",true];
[Link]('First Way ',[Link]); //9
Array Methods..
===============

1) push()
When we need to push any data to an array we use push method.. push() always
appends the data to the end of the array.
Example:

var arr = [];


[Link](10);
[Link]("Sachin");
[Link](true);
[Link](null);
[Link](arr); // [10, "Sachin", true, null]

2) pop()
Whenever we need to remove an element from the array we use pop(). pop()
removes the element which is present at the last index of an array.

Example:

var arr = [10,"Sachin",true,null, 15.7655343421];


[Link]();
[Link](arr); // [10,"Sachin",true,null];

3) unshift()
When we need to push the data to the beginning of the array we use the unshift().
Example:
var arr = [10,"Sachin",true,null, 15.7655343421];
[Link]("Virat");
[Link](arr); // ["Virat",10,"Sachin",true,null, 15.7655343421];

4) shift();

To remove an element from the beginning of an array we can use shift().

Example:
var arr = ["Virat",10,"Sachin",true,null, 15.7655343421];
[Link]();
[Link](arr);

5) indexOf()

This method is used to get the index of a specific element present in an array. If the
element is present inside the array then its index will be returned. If the element is
not available inside the array then the indexOf() will return -1/

Example:
var arr = ["Virat",10,"Sachin", true, null, 15.7655343421];
[Link]([Link]("dahdlhakdlhkahldahldhladhla")) //-1

6) join()

Whenever we need to join all the elements inside the array join() should be used.
join() will join all the elements of an array and return it in the string format.
Example;
var arr = ["Virat",10,"Sachin", true, null, 15.7655343421];
[Link]([Link]());

join() by default will seperate the strings using comma. But if we want to change it
then we need to pass the character to join() as shown below.

[Link]([Link]('-')); //Virat-10-Sachin-true--15.7655343421

7) includes()
includes() checks whether the data passed to it is present inside the array or not. If
its present then it returns true else it returns false.
var arr = ["Virat",10,"Sachin", true, null, 15.7655343421];
[Link]([Link]('Sachin Ramesh... ')); //false

8) reverse()
In order to reverse an array we use reverse()
Example:
var arr = ["Virat",10,"Sachin", true, null, 15.7655343421];
[Link](arr);
[Link]([Link]());

9) slice()
var arr = ["Virat",10,"Sachin", true, null, 15.7655343421];

It works exactly the way slice() works in case of string.


Example
var arr = ["Virat",10,"Sachin", true, null, 15.7655343421,98,false];
[Link]([Link](2, 6)); // "Sachin", true, null, 15.7655343421,98
Starts at 2nd index and goes till 6th index. But ignores the 6th index data.

If we use the slice() it will not alter the original array. Rather it extracts the data
based on the indexes we pass.

slice(start,end);

extraction starts at the start index and ends at the end-1 index;

10) splice()
splice(start,length);
extraction starts at the start index extracts the length number of elements from the
array. In case of splice() it also alters the original array.

Example:

var arr = [1,2,3,4,5,6,7,8];


[Link]("Original Before Splicing ",arr);
var splicedArr = [Link](2, 4);
[Link]("Spliced Arr",splicedArr);
[Link]("Original Array After Splicing ",arr);

//Original Before Splicing (8) [1, 2, 3, 4, 5, 6, 7, 8]


Spliced Arr (4) [3, 4, 5, 6]
Original Array After Splicing (4) [1, 2, 7, 8]

In order to remove an element at a particular index then we must do it this way.

var arr = [1,2,3,4,5,6,7, 8];


[Link]([Link](7), 1);
[Link](arr); // [1,2,3,4,5,6,8]
Front End Technologies
Javascript - Day 6

Agenda
▪ Arrays
Array Destructuring and Object Destructuring.

In JS Version 6 or ECMA Script(Javascript) -> es6

The destructuring assignment syntax is a JS Expression that makes it possible to


unpack values from array in to distinct variables.

Example:

var arr = [10, 20, 30, 40];

// OLD APPROACH
// var num1 = arr[0];
// var num2 = arr[1];
// var num3 = arr[2];
// var num4 = arr[3];

Destructuring Syntax

var [num1, num2, num3, num4] = arr;


Output:
num1 = 10
num2 = 20
num3 = 30
num4 = 40

Using rest params..

While destructuring an array we can unpack and assign the remaining part of the
elements to another variable using the rest parameter.

Example:

var arr = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var [num1, num2, ...rest] = arr;

[Link](num1 + " " + num2); //10 20


[Link](rest)// [30, 40, 50, 60, 70, 80, 90];
Object Destructuring...
While destructuring an Object we can unpack and assign the key/value pairs to
variables

Example:

var student = {
firstName: "Sucheendra",
lastName: "Sachin"
}

// var fName = [Link];


// var lName = [Link];

// [Link](fName + " " + lName);

var {firstName, lastName} = student;


[Link](firstName+ " "+lastName);

Conditionals

1) if-else
2) switch
3) ternary

if-else
syntax:

if(some_condition) {
// conditions belonging to true
} else {
//conditions belonging to true
}

Example:
var firstName = "Sachin";

if([Link]("Virat")){
[Link]("First Name is ",firstName);
} else {
[Link]("First Name is Something else");
}

2) Switch

syntax
switch(condn) {
case:
//some statements
break;
}

Example:

var firstName = "Sourav";

switch(firstName) {
case "Sachin":
[Link]("My name is Sachin");
break;
case "Virat":
[Link]("My name is Virat");
break;
default:
[Link]("My name is something else");
break;
}

Ternary operator
Syntax:

condition ? //true statements : //false statements

Example:

var firstName = "Sourav";

[Link]("Sachin") ? [Link]("My name is sachin") :


[Link]("My name is some thing else");
Front End Technologies
Javascript - Day 7

Agenda
▪ Loops
loops

for loop
while loop
do while loop
for in loop
for of loop

loops are used to complete repeatative tasks easily. Instead of manually repeating
the tasks we must take advantage of loops.

for loop

Syntax:

for(initialize; condition check; increment/decrement) {


//Statements
}

Example:

for(var i = 0; i < 10; i++) {


[Link]("Number "+i);
}

Output:

Number 0
Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9
While

Syntax:

while(condition) {
//Execute statements if true
}
while should be read as "AS LONG AS"

Example:

var counter = 0;

while(counter < 10) {


[Link]("Counter value is "+counter);
counter++;
}

Output:

Counter value is 0
.
.
.
.
.
.
.

Counter value is 9

do while loop

syntax:

do {
//Execute the statements
} while(condition)

Example:

var counter = 0;

do {
[Link]("COUNTER VALUE IS "+counter);
counter++;
} while(counter < 10);

for in loop

Whenever we need to loop through the properties of an object we can use the for in
loop.

Syntax:

for(var variable_name in object_name) {


// Execute the statements
}

Example:

var student = {
name: "Sachin",
age: 27,
qualification: "Engineering",
location: "Bengaluru"
}

for(var data in student){


[Link](student[data]);
}

Output
Sachin
27
Engineering
Bengaluru

for of

Its used to iterate an array. Its very helpful while reading the arrays.

syntax:

for(var variable_name of array_name) {


//Statements
}

Example:

var arr = [10, 20, 30, 40, 50, 60];

for(var data of arr) {


[Link](data);
}

//Output
10
20
30
40
50
60

[Link]
Front End Technologies
Javascript - Day 8

Agenda
▪ Functions
Functions.

Functions are block of code which are destined to perform a specific task.

The advantage of using functions


-> Reusability of code. (Write once Use Multiple times.)

To create functions in JS Below is the syntax:

Always the function name should represent the particualar behavior

Functions wont get automatically invoked unless and until we invoke it.

function function_name() {

Example:

function sayHello(){
[Link]("Hello");
}

Function Parameters/Inputs

We can send any information to the functions by passing the inputs/parameters to it


as shown below.
Example

function addTwoNumbers(number1, number2){


var res = number1 + number2;
[Link](res);
}

addTwoNumbers(10, 20)
In the above example number1 and number2 are inputs/parameters

Functions Which can return the results


Example:

function giveTheSumOfTwoNumbers(number1, number2){


var res = number1 + number2;
return res;
}
[Link](giveTheSumOfTwoNumbers(20, 30));

Anonomous Functions

They are such functions which doesn't have a name.

Syntax:

var ref = function(){


//function body
}

Example:

var sayHello = function() {


[Link]("HELLO");
}

sayHello() //HELLO

Arrow Functions

function keyword is not used to create arrow function.


Syntax:

() => {
//Function Body
}
Arrow functions are added to ES6 (Ecma Script 6) //Latest version of JS.

Arrow functions are used mainly as callback functions.


Example:

var sayHello = () => {


[Link]("HELLO WORLD");
}

sayHello()

forEach()

forEach() is the method associated to JS Arrays. Which accepts another function as


a parameter.

Syntax:

array_name.forEach(function(){
...
...
})

Example:

var printEle = function(element){


[Link](element);
}
[Link](printEle)

or

[Link](function(element){
[Link](element);
})
or

[Link]((element) => {
[Link](element);
})

How to get the index using forEach()

Example

[Link]((element, index) => {


[Link](element + " " + index);
});

map()

The map() is an array related function in Javascript.

map() creates a new array with the results of calling a function for every array
element.

map() will not alter/modify the original array.

Example:

var arr = [10, 20, 30, 40, 50, 60];

var res = [Link]((element) => {


return element * 2;
})

[Link]('Original',arr) // [10, 20, 30, 40, 50, 60];


[Link]('Result',res); // [20, 40, 60, 80, 100, 120]
When should we not use map()??

1) Whenever we dont use the array it returns we shouldn't use the map(). Rather we
can use the forEach()
2) Whenever we are not returning anything from the callback function then no
need of using map().

callback() are such functions which gets called by the functions to which its
passed.

or

callback function is a function passed to another function as an argument, which is


then invoked by the enclosing function to complete some task.
Front End Technologies
Javascript - Day 9

Agenda
▪ Functions
reduce()
Its used to reduce the array to one single value.

-> Reduce method is such a method which accepts a callback function as the
parameter(first Param)
-> (second param) Initial Value.

Syntax:

reduce(callbackFn, initial_value)

Example;

'use strict';

var arr = [10, 20, 30, 40 ,50, 60];


var callback = (prev ,current ) => {
return prev + current;
}

var res = [Link](callback, 10);


[Link](res);

// Output
220

sort method

Its used to sort the array either in ascending or descending order.

Example:

var arr = ["Sachin", "Akash", "Virat", "Viru", 'Goutham'];


[Link]([Link]()); //['Akash', 'Goutham', 'Sachin', 'Virat', 'Viru']
For the below example sort() doesn't sort the array properly. So to solve this
problem we need to pass a callback function to the sort() as shown below.

//For Ascending order


var arr = [10, 2, 5, 1, 7];
var arr = [Link]((a,b) => {
return a - b;
})
[Link](arr); // [1,2,5,7,10]

//For Descending Order

var arr = [10, 2, 5, 1, 7];


var arr = [Link]((a,b) => {
return b - a;
})
[Link](arr); // [10, 7, 5, 2, 1]

filter()

filter() is used to filter the records in the arr.


filter() returns a new array of filtered records.

Example:

var arr = [10, 20, 30, 40, 50];

var res = [Link]((ele) => {


return ele > 20;
})

[Link](res); //[30,40,50]

try/catch/finally

Whenever we feel some part of code may cause problems, we must enclose the
part of code with in try. So if any problems occur try is designed in such a way that
it throws the exception object outside, which later will be caught by the catch().
By using try-catch syntax we can avoid our programs getting terminated abruptly.

Syntax:

try {
//Code

} catch(err){
//To catch the exceptions
}

finally

finally block will get executed irrespective of exceptions.


Example:

try {

//fetching
var num = 20;
firstName = "sachin"; //Exception
[Link]("NUM",num);
[Link](firstName);
} catch(err) {
[Link](err);
} finally {
//eliminate db connection here
[Link]("Finally Executed");
}

Manually throwing Errors


Example:
try {
var num = 20;
var firstName = "sachin"; //Exception
throw new Error("Product ID not found");
} catch(err) {
[Link](err);
} finally {
//eliminate db connection here
[Link]("Finally Executed");
}

Output:

Error: Product ID not found


Finally Executed,
Front End Technologies
Javascript - Day 10

Agenda
▪ DOM
DOM -> Document object model.

-> DOM is the interface between Javascript and Browser.


-> Javascript in order to communicate with the browser takes help of DOM.

Main Use of DOM

-> Allows us to make JS interact with the browser


-> We can write JS to create , Modify and delete HTML Elements.
-> We can dynamically add styles, classes and attributes to the HTML Elements
-> DOM is a very complex API (Application Programming Interface) which
contains lots of methods and properties which helps us to interact with the browser.

[Link]()
It helps us write some text directly to the HTML Document.
Example:

var num1 = 20;


var num2 = 40;
var res = num1 + num2;
[Link](res);
[Link]("The sum is "+res);

O/P

We will see "The sum is 60" on the webpage.

Various kinds of popups

1) alert popup
2) confirm popup
3) prompt popup

1) alert popup
Its used to alert the users regarding some change on the webpage.

Example:

alert("Hello"); //Opens popup and displays Hello

2) confirm popup

confirm() will return true is OK button is clicked Ie the positive response. Else it
returns false I.e Negative Response
Example::

var isConfirmed = confirm("Are you sure to continue?");


if(isConfirmed == true){
[Link]("Thank you. Your image is deleted from the database.")
} else {
[Link]("Thank you. Your image is not deleted from the database.")
}

In our above example if ok is clicked, the confirm() will return true and "Thank
you. Your image is deleted from the database." will be displayed on the webpage

If cancel is clicked then "Thank you. Your image is not deleted from the database."
will be displayed on the webpage.

3) prompt popup

It allows users to enter the data and we can use the data entered by the users to
perform some operations.

Example:

var res = prompt("Please Enter your Name?");


[Link]("RESPONSE ",res);
[Link]("Your Name is "+res);

Finding Elements on the Webpage


getElementById()
Its the method in the DOM which finds an element based on id attribute of the
element.

innerHTML

Its the property of the webelement.

Ex:

[Link]("para").innerHTML = "Hello guys. I hope you are


enjoying holidays.."
[Link]('div').innerHTML = "This is the division";
Front End Technologies
Javascript - Day 11

Agenda
▪ DOM
difference between textContent and innerHTML?

innerHTML -> If we have any HTML tags present while using innerHTML then
innerHTML property recognises the HTML Tags

Example:

[Link]('div').innerHTML = "<i>This is the division</i>"

//The output for the above syntax is "This is the division" and will be displayed in
italics

textContent -> textContent will not recognise any HTML tags. So textContent will
render the HTML Tags also as normal text.

Example:

[Link]('para').textContent = "<i>Hello Everyone. Have a good


day!!</i>";

//Output

<i>Hello Everyone. Have a good day!!</i>

getElementsByName()

Its used to find the elements on the webpage based on the name attribute.. It returns
NodeList . NodeList is nothing but an array of nodes or HTML Elements

Example:

var fName = [Link]('firstName'); //Returns the matching


element as an Array.
fName[0].focus(); //This will focus on the input element.
getElementsByTagName()
Its used to find the elements using the HTML Tag name.

Example:

var input = [Link]("input");


[Link](input);

In our above example it will search the webpage using the tag name input. If the
elements are found it will be returned in an array of type HTMLCollection.

getElementsByClassName()
Its used to find the elements using class attribute.
Example:
<p class="para"></p>

var para = [Link]('para');


[Link](para);

Styles
======

We can dynamically apply the css styling by using the style property as shown in
the below example:

<p id="para">

</p>

var num = prompt("Enter a number?");


var para = [Link]("para");

if(num < 20){


[Link] = `<p>The Number is ${num}</p>`;
[Link] = "green";
} else {
[Link] = `<p>The Number is ${num}</p>`;
[Link] = "red";
}

We can create webelements dynamically using createElement() as shown in the


below Example

var parentDiv = [Link]('div');

The above line of code will create one division.

In order to append the dynamically created division to the webpage we can take the
help of appendChild() as shown in the below example:

var body = [Link]("body");

var parentDiv = [Link]('div');


[Link](parentDiv);

var paragraph = [Link]('p');


[Link] = "I am a paragraph";

[Link](paragraph)
Front End Technologies
Javascript - Day 13

Agenda
▪ Timers
Timers

What is the difference between setTimeout() and setInterval()

When ever we need to delay the execution of a code we use timers.

setTimeout()

1)setInterval()

setTimeout() accepts 2 parameters


1) callback function
2) the time in miliseconds

Example:
let sayHello = () => {
alert("Hello!!");
};

setTimeout(sayHello, 5000);

2) setInterval()

setInterval() also accepts 2 parameters


1) callback()
2) the time in milliseconds

The main difference between the setTimeout() and setInterval() is that the
setTimeout() will execute the callback() only once. Whereas setInterval() keeps on
triggering the callback() regularly after the given interval of time (Unless you stop
it. )

Example:
let sayHello = () => {
[Link]("Hello");
}
setInterval(sayHello, 3000);

How to stop setInterval()

When we need to stop the setInterval() we should use clearInterval()

Every setInterval() will return one id. We need that id inorder to clear the interval.

clearInterval() which accepts a number as a parameter. We should be passing the


timerId which we need to clear.

Example:

let timerId = setInterval(sayHello, 3000);


[Link](timerId);

setTimeout(() => {
clearInterval(timerId);
alert("Timer Stopped!!")
},9000)

Events
=======

Event is nothing but some activity on the webpage.


Example

click event
type event

Different types of Events.


1)

onclick
<body id="body">
<button onclick="onButtonClick()">Click Here</button>
<script src="./[Link]"></script>
</body>

function onButtonClick(){
var body = [Link]("body");
var para = [Link]('p');
[Link] = "Hello Everyone. I am generated because you clicked on a
button!!"
[Link](para);
}

In our above example upon clicking on the button we will be dynamicaaly adding
the paragraphs

2) onchange

onchange event gets called upon changing of dropdown option.


Example:

<select name="" id="" onchange="onDropdownChange(event)">


<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
<option value="Four">Four</option>
<option value="Five">Five</option>
</select>

function onDropdownChange(e){
[Link]("Dropdown value changed",e);
}

event is the predefined object in jS where it contains all the information regarding
the current happening events. Example:

When we click on a button the event object will contain all the information related
to click event.
When we change the dropdown option the event object contains all the information
related to option change, .
Event Object looks like this.
{
bubbles: true,
cancelBubble: false,
cancelable: false,
composed: false,
currentTarget: null,
defaultPrevented: false,
eventPhase: 0,
isTrusted: true,
path: (5) [select, body#body, html, document, Window],
returnValue: true,
srcElement: select,
target: select,
timeStamp: 3245,
type: "change"
}

onkeydown

This event gets triggered when we type any key on the keyboard.

Example:

<input type="text" onkeydown="keyPress(event)">

function keyPress(event){
[Link]("KEY PREssed",[Link]);
//API CALL [Link]
}

onmouseover and onmouseout

These are the events related to mouse move activity.


onmouseover -> When we take the cursor on any webelement it gets triggered
onmouseout -> When we take out the cursor from any webelement it gets triggered
Example:
<div onmouseover="mouseOver(event)" onmouseout="mouseOut(event)"
class="box" id="box">

function mouseOver(event) {
[Link](event);
[Link]("box").[Link] = "red";
}

function mouseOut(event) {
[Link]("box").[Link] = "white";
}
Front End Technologies
Javascript - Day 14

Agenda
▪ Built-In Objects
Adding Events through Javascript

We can listen to events through Javascript by using addEventListener().


addEventListener() accepts 2 parameters
1) type of event (string) ex: click, change etc
2) callback function

Example:

<button id="btn">Submit</button>

[Link]("btn").addEventListener('click',(event)=>{
alert("Button Clicked!!");
})

Example2:

<select name="" id="dropdown">


<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
<option value="Four">Four</option>
<option value="Five">Five</option>
</select>

[Link]("dropdown").addEventListener('change', (event)=>{
alert("The Value is "+[Link]);
})

Important Builtin Objects


1) Math
2) Date

1) Math

-> [Link]([Link]) //3.141592653589793


2) [Link](Math.SQRT2); //It returns square root of 2 ie 1.4142135623730951

sqrt() calculates the square root of any number passed to it.


3) [Link]([Link](64)); // 8

4) [Link]() Will help us to round the number passed to it to its nearest integer
value.

Example:

var num = 4.6;


[Link]([Link](num)); //5

5) [Link]()
[Link](num) return the value of num rounded up to its nearest integer.

Ex:
var num = 4.4;
[Link]([Link](num));

6) [Link](num)
[Link](num) returns the value of num rounded down to its nearest integer.

Example:
var num = 4.9;
[Link]([Link](num));

7) [Link]()
[Link](num) will truncate the decimal and returns only the integer part of a
num

Example:
var num = 4.334802842084802;
[Link]([Link](num));

8) [Link]()
[Link](num) returns -1 if the num is negative and +1 if the num is positive. If
the num is 0 then it returns 0

Example:
var num = 0;
[Link]([Link](num)); //0

var num = 4.55;


[Link]([Link](num)); //1

var num = -4.55;


[Link]([Link](num)); //-1

9) [Link]()
[Link]() is used to generate the Random Numbers.

10) [Link]()
Returns the Max number passed as an arguement

Exmple:
[Link]([Link](10, 12, 150, 9, 65, 43)); //150

11) [Link]()
Returns the Min Number passed as an arguement

Example

[Link]([Link](10, 12, 150, 9, 65, 43));

[Link]() Generating Random Numbers between 1-6


[Link]([Link]() * 6 + 1)

6 is the number of possible results


1 is the start number
[Link] Will remove the decimal part.
Front End Technologies
Javascript - Day 15

Agenda
▪ Date()
Date()

When ever we need to know about the date we should use Date Object.
Date Object gives information regarding Day, Month, Year, Minutes, Hours,
Seconds and Time Zone .
Example:

var date = new Date();


[Link](date);
//Thu Oct 14 2021 07:38:22 GMT+0530 (India Standard Time)

Months in date starts at 0 and ends at 11.

Ie 0 represents January and 11 Represents December


Example:

[Link](new Date(2020,9,15)); //Thu Oct 15 2020 00:00:00 GMT+0530 (India


Standard Time)

If the months that we are passing exceeds the limit, it actually moves to next year.
The same rule holds good for days as well
Example:

[Link](new Date(2020,13,30));

In our above example 2020 is the year. 13 is not a valid month. (0-11) are only
valid. so 13-11= 2 so add 2 months to the exisiting month. So it will become Feb.

30 is not a valid day in feb. so 30-maxDays = 30-28 =2. Add 2 days to existing
days.
Hence the below output

Tue Mar 02 2021 00:00:00 GMT+0530 (India Standard Time).

getFullYear() -> Returns Year as 4 digit number(yyyy)


getMonth() -> Returns the month as a number(0-11)
getDate() -> Returns the day as a number(1-31)
getHours() -> Returns the Hours (0-23)
getMinutes() -> Returns the minutes as number(0-59)
getSeconds() -> Returns the seconds as number (0-59)
getMilliSeconds() -> Returns MilliSeconds (0-999)
getTime() -> Returns the time in milliseconds(epoch time) //Time in milliseconds
since jan 1st 1970.
getDay() -> Returns the weekday as a number(0-6)

epoch time or unix time is the time in milliseconds since jan 1st 1970. Or number
of seconds elapsed since Jan1st 1970.

Methods For Setting the Date()

setFullYear() -> Used to set the year


setMonth() -> Used to set the Month (0-11)
setDate() -> Used to set the Day as a num (1-31)
SetHours() -> Used to set the Hours (0-23)
setMinutes() -> Used to set the minutes(0-59)
setSeconds() -> Used to set the seconds(0-59)
setMilliseconds() -> Used to set milliseconds(0-999)
setTime() -> Set the time (epoch value)

debugger keyword.

Its helpful for debugging our code.


Front End Technologies
Javascript - Day 16

Agenda
▪ LocalStorage
LocalStorage

Its a feature available in the browser where we can store key value pairs to make
data persistant.
Max Storage supported is up to 10MB .

We can make the data persistant on the client side using localStorage.

Example:

<body id="body">
<label for="">First Name</label> <input type="text" id="firstName">
<button id="btn">Submit</button>

<br/>
<br/>

<h3>The FirstName is </h3><span id="setFname"></span>


<script src="./[Link]"></script>
</body>

var firstName = '';


[Link]('setFname').textContent = [Link]('name');

[Link]('firstName').addEventListener('keydown',(event) => {
firstName = [Link];
})

[Link]('btn').addEventListener('click',()=> {
[Link]('name',firstName);
[Link]('setFname').textContent =
[Link]('name');
})
[Link]

'use strict';

var colors = ['white', 'red', 'blue', 'green', 'yellow','violet'];


var len = [Link] - 1;

var buttonControl = [Link]('btn');


var spanControl = [Link]('.color');

[Link]('click', () => {
var index = generateRandomNumber();
[Link] = colors[index];
[Link] = colors[index];
})

function generateRandomNumber(){
return [Link]([Link]() * len);
}

[Link]

main {
min-height: 100vh;
display: grid;
place-items: center;
}

.container {
text-align: center;
}

.container h2 {
background-color: #222;
color: #fff;
padding: 10px;
border-radius: 10px;
margin-bottom: 25px;
}

.btn-hero {
text-transform: uppercase;
background: transparent;
color: #222;
font-weight: 700;
border: 2px solid #222;
cursor: pointer;
border-radius: 10px;
padding: 8px;
}

.btn-hero:hover {
color: #fff;
background: #222;
}

You might also like