0% found this document useful (0 votes)
56 views

JavaScript by shudhakar sharma

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

JavaScript by shudhakar sharma

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 36

JavaScript

=========================
-> JavaScript is light weight JIT [ just-in-time] complied and interpreted
programming Languages.
-> Interpreted allows to translate line by line of program.
-> Compiler allows to translate all lines simultaneously at the same time.
-> There are 2 types of compiling techniques:
a) JIT [ Just-in-time]
b) AOT [ Ahead-of-Time]

-> JIT is a mechanism where the programs loaded into browser and complied in
browser.

-> AOT is a mechanism where the program is complied and translated at application
level. It is
faster and improves performance of application.

-> JavaScript supports various programming approaches


a) Structural
b) Imperative
c) Dynamic
d) Object Oriented
e) Procedure oriented ect..

-> JavaScript is a language which is used


a) Client Side : HTML, React, Angular, Vue, Backbone, Knockout
b) Server Side : Node JS
c) In Databases : MongoDB
d) For Animation ect.. : Flash, action Script

Q. What is role of JavaScript Client Side ?


Ans: JavaScript is used client side to reduce burden on server.

End video no 35
-----------------------------------------------------------------------------------
-------------------------------
Integrating JavaScript into HTML page:
=================================
-> You can integrate JavaScript function into HTML page using 3 techniques
1. Inline
2. Embedded
3. External File

1. Inline Technique:
-> In allows developer to write JavaScript function directly inside element
-> It is faster but you can't reuse.
Syntax:
<button onclick="window.print()"> Print </button>

2. Embedded
-In this technique developer can keep all JavaScript function in a <script>
container.
- So that you can access and use from various location in page.
- You can embed in <head> or <body> sections.

Syntax:
<script>
faction PrintPage()
{
window.print();
}
</script>

<button onclick ="PrintPage()"> Print</button>

- JavaScript embedded MIME type is "text/javascript" or "language=JavaScript".

Syntax:
<script type ="text/JavaScript">
</script>

- JavaScript have module system which used type as "module"

Syntax:
<script type="module">
</script>

- JavaScript have different MIME type based on compilers [V8, Babel]


Syntax:
<script type ="text/babel">
</script>

- JavaScript is not a strictly typed language. Hence you have to turn ON strict
mode manually.
- Strict mode allows to reduce code in-consistency.
- You can turn ON strict mode by using the following command.
"use strict";

Syntax:
<script type="text/javascript">
<"use strict"; => Invalid : x is not define
x=10;
document.write("x=" + x): => It is valid if you remove strict
mode
</script>

- You can target JavaScript functions to Legacy Browsers by enclosing the script in
HTML comments.
Syntax:
<script type="text/javascript">
"use strict";
<!--
function name() {
--!>
</script>

External File:
===========
- JavaScript functions can be defined in separate file with extension ".js"
- So that you can reuse the function across pages.
- Using an external file will always increase the number of requests and also load
time.

Ex:
1. Go to "scr" folder
2. Add a new folder "scripts"
3. Add a new file by name "print.js"
"use strict";
function PrintPage()
{
window.print();
}

4. You have to link script file by using <script> element


<head>
<script srt="../src/script/print.js" type="text/javascript">
</script>
</head>

<body>
<button onclick="PrintPage()"> Print</button>
</body>

- You can minify the JavaScript code and use minified code for production.

Drawback of JavaScript
====================
-> It is not a strongly typed language.
-> Validating data type requires explicit functions.

var x = 10; -> x is number


x ="John"; -> x is string

- It is not a strictly typed language.


- You have to turn on strict mode manually.
- It is an OOP language.
- It supports only few features of OOP.
- Extensibility Issues.
- Code level security issues.
- No Dynamic polymorphism.

Note: The alternative for JavaScript that modern web developers use is
"TypeScript".
TypeScript is not replacement for JavaScript, It is a just an alternative.

End videos No 36
=======================
-----------------------------------------------------------------------------------
-------------------------------
Q. 1. How JavaScript refers HTML elements ?
Ans: JavaScript can refer HTML elements using DOM Hierarchy.
Syntax:
window.document.images[]
window.document.forms[].elements[]
- It is the fastest technique implemented for rendering dynamic elements.
- It is the native method for JavaScript to refer elements.
- However changing the position of element in page requires the change in index
number every time.

2. JavaScript can refer HTML elements by using a reference name.


- Every element can have a reference name.
<img name="pic">

- JavaScript can access using reference name


pic.src="../image/man.jpg";
- But you can not access any child element directly without referring to it's
parent.
- Multiple elements can have same name, then JavaScript ignore the element.

3. JavaScript can refer HTML elements by using unique "ID"


- You can access element directly from any level of hierarchy.
- JavaScript provides a document method
"document.getElementById()"

- "id" is a reference used by CSS, where it can be common for multiple elements.
- Hence ID is also having issues in manipulating element.
Syntax:
<img id="pic">
document.getElementById("pic").src="../public/image/kids.jpg";

4. JavaScript can refer HTML using CSS selectors.


- JavaScript provides a document method
document.querySelectory()

- It can use all CSS selectors like, primary, rational, structural, attribute ect..

<img>
document.querySelector("img").src="path";
<input type="button" class="btn-login">
document.querySelector(".btn-login").value="Login";

JavaScript Output & Input Techniques


======================================

- > JavaScript Output Techniques:


.alert()
.confirm()
.document.write()
.console methods
.innerHTML
.outerHTML
.interText

1. alert() method:
- Alert will display a message box with some raw text.
- It can't have formatted text.
- It will not allow user to cancel.
- User have to confirm with OK and continue.
Syntax:
alert("you message");
alert("line-1 \n line-2);
alert(expression);

2. Confirm()
- It is similar to alert() but it allows to cancel.
- It returns a Boolean result
true on OK click
false on Cancel click

Syntax:
confirm ("your message"); true = OK, false = Cancel
3.document.write()

- It renders output on new screen.


- It can render formatted content, which includes markup.
- It can render any expression result ect..

Syntax:
document.write("message | markup | expression");

Note: You can't use \n, you have define using <br>

4. innerText
- It is used to render output in any container element.
<p> <div> <span> <h2> <td> <dd> <header> ect..

- It will not allow formatted text.


- It is RC data type.

5. InnerHTML
- it is similar to innerText but it allows all formats
- You can render markup using innerHTML

Syntax:
document.querySelector("p").innerText="deleted";
document.querySelector("div").innerHTMl="<b> deleted.</b>";

6. outerHTML

- It is similar to innerHTML, but will replace the existing markup with new markup.

Syntax:
document.querySelector("p").outerHTML="<h2> Wellcom</h2>";

End videos no 37
===================================================================================
=======
7. Console methods
- Console is a developer CLI [command line interface]
- It is provided with browser developer tools. [inspect]
- Developer can log all message as output in console.
- The various contextual console method are:
console.log()
console.error()
console.warn()
console.debug()
console.info() ect..

Syntax:
console.log("string | expression");

Note: console can't take markup or complex presentation.


console methods are only for design not for production.

-----------------------------------------------------------------------------------
--------
JavaScript input Techniques
===========================
- User input can be form
a) Query String
b) Prompt()
c) From input Elements

1. Query String :

-A query string is defined in browser address bar.


- It is appended to existing URL using "?".
- Query string is usually a key and value collection.
?key=value

- you can access query string in page by using JavaScript "location.search"

Note: "location.search" return complete query string, you have to use string
methods to extract only the value.

str = location.search -> "?cotegory=mobiles"


str.indexOf("="); -> return index number of "=" [9]
str.substring(indexNumber) -> reads from specified index up to end.

2. Prompt

- JavaScript "prompt()" method provides a popup that allows input from browser
windows.
- It is an input box to input value into page.
- Prompt method returns following

Empty String [""] : OK click without value


String Value : OK click with value
null : Cancel click with or without value.

Syntax:
prompt("your message", "defualt_value_Optional");

-----------------------------------------------------------------------------------
-------
Form input Elements
=======================

- You can design a form with various input elements like


textbox
password
number
range
URL
email
radio
checkbox
dropdown ect..

- You can accept input from the element and render in UI.
- form element keep the content in the reference of "value".
End video no 38
=================================================================

JavaScript Language
===================
1. Variables
2. Data Types
3. Operators
4. Statements
5. Functions

1. Variables
---------
-> Variables are storage locations in memory, where you can store a value and use
it as a part of any expression.
Ex:
<script>
document.write("Hello" + prompt("Enter your Name") + "<br>);
document.write("Hi" + prompt("Enter your Name") + "Wel come to JavaScript");

</script>

<!-- With variable -->

<script>
username = prompt("Enter you Name")
document.write("Hello.. " + username + "<br>");
document.write("Hi " + username + " Wel come to JavaScript..");

</script>

- Variable configuration comprises of 3 phases.


a) Declaration
b) Assignment
c) Initialization

var = x; => declaring


var = 10; => assign
var x =20; => initialization

-> JavaScript allows directly assignment without declaring if it is not in strict


mode.

Syntax:
<script>
x =10;
document.write("x" +x); => valid
</script>

->If javaScript is not strict mode declaring variable is mandatory.

Syntax:
<script>
"use strict";
x =10; invalid x is not defined
document.write("x" +x); => valid
</script>
-> JavaScript variables are declared by using 3 keywords
1. var
2. let
3. const

. var :
- It define a function scope variable.
- You can declare in any block of a function and can access from any another block
inside function.
- It allows declaring, assignment and initialization.
- It allows shadowing.
- Shadowing is the process of re-declaring or re-intitializing same name
identifier within the scope.
{
var x =10;
var x = 20; => variable shadowing
}

- It allow hoisting
- It is the process of declaring and using a variable form any location. There is
no order dependency. you can use and declare later in function.

<script>
"use strict";
x =10;
document.write("x"+x);
var x; => hoisting. note: we can only declare not initialized.
</script>

let :
- It define block scope variable.
- It is accessible within the specified block and to it's inner blocks
[ this mechanism is known as closure ]

- It support declaring, assignment and initialization.


- it will not shadowing and hoisting.

const :
- It define block scope variable
- It supports only initialization.
- It not supports declaring, assignment.
- It not support shadowing and hoisting.

End Video no : 39
=================================================================
Variables Global Scope
======================
-Global scope defines the accessibility of variables across multiple functions.
- Declaring or initializing variables outside function makes as Global.
- you can configure a global variable inside function using "windwod" object of
JavaScripte.

window.varName = value;
Syntax:
<script>
var x = 10;
function f1() {
document.write("f1 x" +x + "<br>");
}
function.f2(){
document.write("f2 x=" +x);
}
f1();
f2();
</script>
---------------------------------------------------------------
Variable Naming
- Name must start with an alphabet.
- It can be alpha numeric with "_".
- You can start name with "_" . But is not recommended.
-ECMA doesn't recommended to using special chars.
-Name mac length can be upto 255.
- Never using keywords as variables.
EX:
var for;
var is: => Invalid
var while;
-Variable name must speak what it is.
- Always use camel case.
Ex:
var userName;

----------------------------------------------------------------
JavaScript Data Types
=====================
- In computer programming data type defines the data structure.
- It is about the type of behaviour of data in memory.
- JavaScript is not a strongly typed language.
- Hence there is not data type restriction for data in memory.

var x = any type of data can be stored.

- JavaScript is implicitly type language. The data type changes according to the
values type.

var x = 10; x is number.


X ="A" x is string
x = true; x is a Boolean.

- JavaScript data type in memory can be


1. Primitive types
2. Non Primitive types

=> Primitive Types:


- Primitive types are immutable types.
- You can't change structure.
- It have a fixed range for values.
- They are stored in memory stack.
- Stack uses LIFO ( last in first out).
- JavaScript Primitive Types are:
a) Number
b) String
c) Boolean
d) Null
e) Undefined
f) Bigint
g) Symbol

Number Types:
=============
- A Number for JavaScript can be any one of the following.
signed integer -5
unsigned integer 5
float point 34.32
double 233.23
decimal 3242.32 [ 29 decimal places]
exponent 2e3 [2 x 10^3] = 2000
hexa 000fx45
octa 0o578
binary 0b1010

=> Bigint is a new type for safely using large integers.


- Bigint configures large integer values with "n" as suffix.

Syntax:
var x = 9988776543; // it is not safe
var x = 9988776543n; // it is safe [Bigint]

- Every input from HTML is considered as string.


- You have to parse [convert] string into number.
- JavaScript provides the methods
a) parseInt()
b) parseFloat()

Syntax:
var age = parseInt(prompt("Enter Age"));
document.write ("you will be " + (age+1) +"next years"));

- You can verify the input type number or not by using JavaScript method "isNaN()"
- It is a Boolean method that return true if input value is not a number.

FAQ: How to verify input value number or not using regular Expression ?
Ans: By using pattern and javascript "match();

Syntax: var age = "22";


var regExp = /\d{2}/;
if(age.match(regExp))
{
+}

- You have to convert a number into string. It is possible by using


toString()
toLocalString()

Eng Vides no 40
=================================================================
JavaScript String Types
=======================:
- String is a literal with group of characters enclosed in
a) double quotes ""
b) single quotes ''
c) back ticks ``

- Single and duble quotes are used to toggle outer and inner string
Syntax:
var link = "<href='home.html'>Home</a>";
var link = '<href="home.html">Home</a>';

- Binding dynamic value to a string requires lot of concat techniques using "+"
operator.

Syntax:
"string" + dynamicValue+"string"

- E5+ version of javascript introduced a data binding expression "${}", which you
can embed in a string with backticks only
Ex:
'string${dynamicvalue} string'

- String can not print few characters, to print the non-printable character you
have to use the escape sequence character "\".
Syntax:
let path = "d:\images"; => d:images
let path = "d:\\images"; => d:\images

- JavaScript provides various methods for formatting and manipulating string.


-JavaScript string formatting includes
bold()
italics()
fontsize()
fontcolor()
sub()
sup()
strike()
toUpperCase()
toLowerCase() ect..

Syntax:
var str = "welcome";
document.write(str.bole().italics().fontsize(4).fontcolor ('green'));

Event:
onblur : specifies actions to perform when elements lost focus.
onkeyup: specifies actions to perform when a key is related[every character].

Note: You can't apply font and style on RC data element using string methods.

document.getElementById("textbox_id).value = "john".bold() // invalid.

- JavaScript provides various methods for string manipulations.

1. length [property]: It is used to return the total count of character in a


string.
syntax:

var str = "welcome";


str.length; => 7

2. charAt(); : It return the character a specified index a string. which is


start with '0'.

var str = "welcome";


str.charAt(2);

3. charCodeAt() : It return the ASCII code of the character at specifics index:

4. startWith() : It return Boolean true if string with specified char(s).

5. endsWith() : It return Boolean if string ends with specifics chars(s).

Syntax:
var str = "44556600334";
str.startsWith("4455"); true;
str.endsWith("4455"); false;
str.endsWith("88") true;

End videos no : 41
-----------------------------------------------------------------
6. indexOf() : It return the index number of character in specified string. If
character not found the it returns "-1".
It returns the first occurrence of value index.
Syntax:
var str = "welcome";
str.indexOf("e"); // return 1 ;
str.indexOf("a"); // return -1;

7. lastIndexOf() : It returns the last occurrence of index number of given value.

str.lastIndexOf("e"); // 6

8. slice() : It is used to extract chars between specified index.

9. substr() : It can extract specified number of chars from given index.

10. substring : It can extract chars between specified

FAQ: What is difference between slice(),substr()& substring()?


Ans:
Slice() : refer to start and end index. The end index value
must be greater than start index.

substr() : refers to the number of chars from specified index.

Syntax:
str.substr(startIndex, howManyChars);
str.substr(6,3); from 6 it can read 3 chars

substring() : refers to the start and end index bi-directional.


syntax:
str.substring(startIndex, endIndex);
str.substring(7,14) // 7 to 14 index
str.substring(7) // 7 to end
str.substring(7,0) // 7 to start

11. split() : It can split the string into an array by using specified delimiter.

Syntax:
var details = "john-23, david-25, sam-31";
details.split(','); // [john-23, david-25, sam-31]
index -> 0 1 2

Ex:
<script>
var contacts = "john-8242423423 , david-23424234";
var [john, david] = contacts.split(",");
document.write(john + "<br>");
document.write(david);
</script>

12. trim() : It is used to remove leading spaces from a string,


and return string without leading spaces.(space before and after].

Syntax:
var str = "welcome";
var result = str.trim(); // "welcome"
Ex:
script>
var otp = prompt("Enter OTP");
if (otp.trim() == "444") {
document.write("success");
} else {
document.write("Indalid OTP");
}
</script>

13. match() : It is used to compare your string with a regular expression and
return if string is according to given expression.

Note: In JavaScript regular expression is written in "/ /".


Syntax:
var regExp - /\ d{10}/;
var str = "9999";

End Videos no 42
=================================================================
Boolean:
=======
- Boolean are used in decision making.
- Boolean types in JavaScript can handle the keywords "true & false".
- Boolean condition in JavaScript can manage using "1 and 0".
true = 1;
false = 0;
Undefined:
==========
-It refers to a memory where value is not defined.
- You can use "undefined" keyword to verify value in memory.
Syntax:
var x;
document.write("x:" +x) // x = undefined

- You can verify value in reference using simple decision making statement.
if(x){} // x is define or not

FAQ: What is difference between undefined and not-defined ?


Ans: undefined refers that value is not defined.
not-defined refer that the memory reference is not-defined.
Syntax:
var x;
document.write('x${x} <br> y=${y}');

Null
====
- Null is a type configured for memory reference when value is not provided during
runtime.
- It is verified by using "null" keyword.

Symbol
======
- It is used to configure a hidden key for object.
- The hidden keys are ignored over iterations. But they are accessible
individually.
- Symbol is a new data type of JavaScript for developers from version ES6.
---------------------------------------------------------------
ARRAYS
---------------------------------------------------------------
- Arrays are introduced into computer programming to reduce overhead and
complexity.
- Arrays can reduce overhead by storing values in sequential order.
- Arrays reduce complexity by storing multiple values under the reference of single
name.
- Arrays can store various type of values.
- Arrays size can change dynamically.

Note: Some of the software programming technologies can't allocate different types
of memory in sequential order and can't change the size dynamically. Hence they
restrict array for similar types of values.

- JavaScript array can store various types and can change the size dynamically.
- Array refers to a type of arrangement, where elements are arranged sequentially
but can be accessed in random.
ex:
keyboard is having an arrays of keys.

Declaring Array:
- JavaScript array is declared by using var, let or const keyword.
- It used a reference name for storing values.

Syntax:
var products;
var categories;
var sales;

Assign or Initialize memory for arrays:


- Every array must be assigned or initialize with memory.
- You can initialize or assign memory by using 2 techniques.

a) []
b) array()

Syntax: Initialization of memory:

var products = [];


var products = new Array();

Syntax: Assignment of memory:

var products;
product = [];
or
product = new Array();

End Videos no 43
=================================================================
FAQ: What is difference between array "[]" and "array()" ?
Ans:
var products = "[]";
var products = new Array();

[] -> It configure a static memory, the memory allocated for


first reference will continue across multiple requests.

Array(): It configure dynamic memory, Which is newly allocated


every time when requested.

Storing value Array:


- The values are stored with reference of a property.
- Property is a string that maps to index of memory.
- You can store any types of values in array memory reference.
a) Primitive
b) Non Primitive
c) Function

- You can access array elements [values] by using the reference of property.
ex:
document.write(value[2]) => true
document.write(values["1"]) => TV

----------------------------------------------------------------
Array Properties & Method
-------------------------
1. Finding the length of an array, Which is total count of element in array.

var values = [10,20,30];


values.lenth; =>3
2. Reading values from array

toString() : It reads all element and convert inot a string

join() : It is similar to string but uses custom delimeter.

slice() : It reads elements between specified index.

map() : It is an iterator that returns all elements using a specific


presentation.

forEach() : It is similar to map() but can return index of every element in


iteratin.

find() : It returns only the first occurance element that matches


given condition.

filter() : It return all elements that match the given condition.

reduce() : It performs specific operation of values return by iterator.

Note: You can also use various statements explicitly to read value from array for,
while, for..in, for..of

Explicit Iterators for Arrays:


-----------------------------
1. for..in : It reads all properties of array.

Syntax:
for(var property in collection)
{
}

2. for..of : It reads all values of array.

Syntax:
for(var value of collection)
{
}

Note: JavaScript E5+ version interduce array unstructured.

End videos no 44
=================================================================
Dynamically Creating HTML elements:
-----------------------------------
1.HTML Elements can be created in JavaScript by using the DOM method.

document.createElement("tokenNmae") => Node Name for element


Paragraph => p
Image => img
document.createElement("img");

2. Assign a memory reference for newly created element.


var pic = document.createElement("img");
3. Configure the properties for element[You can't use attributes]

pic.src = "imgages/name.jpg";
pic.width ="400";
pic.height= "400";
pic.className = "cssClassName";

4. Add element into page. You can add any element using the DOM method
appendChild();

<figure></figure>

document.querySelector("figure").appendChild(pic);

Note: You have to configure all the functionality using specific event in page.
like-> onload, onclick, onchange ect..

Presenting Array Element in HTML Page:


--------------------------------------

1. Use any iterator for reading all elements from array.


map(), forEach(), find(), filter(), for..of, for..in

2. In every iteration create a new element using DOM method.

3. In every iteration set a properties for new element

4. In every iteration append the child element to it's parent.

Syntax:
var value= [10,20,30]; <ol></ol>

values.map(function(value){
var li = document.createElement("li");
li.innerHTML = value;
document.querySelector("ol").appendChild("li);
})

Add Element into Array:


----------------------

push() : It adds new element(s) into as last elements(s).


unshift() : It adds new element(s) into as first elements(s).
splice() : It adds new element(s) into array at specific position.

Syntax:
var menu = ["Electronics"];
menu.push("footwear"...); ["All", "Electornics", "footwear"]
menu.unshift("All"...); ["All", "Kids", "Electornics", "footwear"]
menu.splice("1,0,"kids"...); ["All","Kids", "Electornics", "footwear"];

splice(startIndex, deleteCount, Items..");

Removing Element from Array:


---------------------------
pop() : It removes and return the last element.
shift() : It removes and return the first element.
splice() : It removes and return specific element(s).

Syntax:
var categories = ["All", "Electronics" "Fashion"];
categories.pop(); => ["All", "Electronics"];
categories.shift(); => ["Electronics", "Fashion"];
categories.pop(); => ["All", "Electronics"];
categories.pop(); => ["All", "Fashion"];

Sorting Arrays Elements:


-----------------------

sort() : It arranges elements in ascending order.


reverse() : It arranges elements in reverse order.

Syntax:
categories.sort()
categories.reverse()

End Videos no 45
=================================================================

Object Type
<------------>

- Object is a key and value collection.


- The values are stored with reference of keys.
- Key is "string" type and Value can be any type.

Syntax:
var obj= {
"key":value;
"key:: function(){}
}

- If object comprises of only data then it is referred as "JSON".


- JSON is JavaScript Object Notation.

Syntax:
var product = {
"Name" : "Moble";
"Price" : 3435.43;

- You can access any value within object by using "this.KeyName".


- "this" is a keyword that refers to current object.
- You can access the values of object with reference of "ObjectName.KeyName"

document.write('Price=${product.Price}');

Note: "dot" is member invoking operator.

- JSON data is kept in separate JSON file that have the extension
".json".
- To access data from JSON file JavaScript provides a "fetch()"
promise.

- Promise is a special type of function that handles "Async" method


-"Async" is unblocking technique, without blocking other requests it can process
your request.

Syntax:
fetch("url").then(function(reponse){
return response.json();
}).then(function(data){
.. you can use data..
}).catch(function(ex){
...display exception..
}).finally(function(){
.. excutes always..
})

End Videos no : 46
=================================================================
Fetching Data from API Website:
-------------------------------
-nasa.api.gov
-fakestoreapi.com

Fakestore:
- It provides PAI for ERP application[shopping]
- It provides various method for different type of data available in there
database.

Request Method Data


-------------- ---------------------------------------
/product [{},{}] It returns all products in DB
/product/1 {} It returns specific product details by id.
/product/categories [] it returns all categories list string type
/procduct/categories/jewellery [{}.{}] It returns specific category products.

Ex:
http://fakestoreapi.com/products
http://fakestoreapi.com/products/categories

End Video No 47
================================================================
Object with Data & Functionality
--------------------------------

- Object is also known as "Pseudo Class".


- Data is kept is properties and logic in functions.

Syntax:
var product = {
"key" : value,
"key" : function(){}

- The members of object are accessible within object using "this"


Keyword.
- A function in object can return any specific value or functionality.

FAQ's
1. How to read all keys from an object ?
Ans: By using "for..in" iterator or by using "Object.keys()"

Syntax:
for(var property in object)
{}

2. How do we know about the data type of value in Key?


Ans: By using "typeof" operator.

Syntax:
typeof object[key] => return value data type.

3. How to know the total count of keys in object ?


Ans:
Object.keys(product).length

4. How to find the existence of key in object ? how to find key?


Ans : By using "in" operator.

"key" in objectName; => true if found

5.How to remove key form object ?


Ans: By using "delete" operator.

Syntax:
delete object. Key;

Issue with Object:


===============
- All keys in object must be string types.
- All manipulations require explicit methods and operators.
- Hence it is slow.

Map Type:
========
- It is also a key and value collection like object.
- Key can be any type.
-Value can be any types.
- It provides all implicit methods for manipulation.
- Hence it is faster than object.
- But it is schema less [structure less].

Method Description
-----------------------------------------------------------------
set() : It configure a new key with value.
get() : It can access value with reference of key.
delete() : It removes a key.
clear() : It removes all keys.
size : It return the count of keys.
has() : It find a key.
keys() : It returns all keys.
values() : It return all values.
entries() : It returns all keys & values.

Syntax:
var topics = new Map();
topics.set(key, value);
topics.get(key);
topics.delete(key);
topics.size;
topics.clear();
topics.keys(); [] of keys
-----------------------------------------------------------------

JavaScript Data & Time type


===========================
-JavaScript date and time values are stored in memory by using "Date()"
constructor.

Syntax:
var now = new Date(); => loads current data & time into memory

var manufactured=new Date("years-month-day hrs:min:sec:millsec");

- JavaScript provides various method for handling data and time


getHOurs() It return hour number 0 to 23
getMinutes() It returns 0 to 59
getSecond() It return 0 to 59
getMilliSecond() It return 0 to 99
getDate() It return data number 1 to 31
getDay() It return weekday number 0 = Sunday
getMonth() It return month number 0 = January
getFullYears() It returns 4 digits years number
toLocalDateString()
toLocalTimeString()
toLocalString()

SetHourse()
SetMinutes()
SetSecond()
SetMilliSecond()
SetDate()
SetMonth()
SetYear()

End video no 48
================================================================

JavaScript Timer Events


-----------------------
Timer Events:
setInterval()
setTimeout()
clearInterval()
clearTimeout()
Timeout:
- It is used for handling debounce.
- Debounce is used to control the bounce of keys in electronic devices.
Syntax:
setTimeout(function(){},interval);

Interval:
- Timeout will remove the task from memory and release into processes.
- Timeout will execute only once.
-Interval will keep the task in memory and release into process at regular time
intervals.
- You have to remove explicitly.
-----------------------------------------------------------------Summery:

1. Primitive types:
- number
- string
- Boolean
- null
- undefined
- symbol
- bigint

2. Non Primitive Types


array
object
map

3. Date Type

4. Timer Events

5. JSON

6. Fetch Promise [API]

JavaScript Operators
====================
1. Arithmetic operators

+
-
*
/
%
**[power]
++[increment]
--[decrement]

syntax:
2 **3 => 8

syntax : post Increment, Decrement

var x = 10;
var y = x++; post increment[x=11, y=10]
var y = x--; post decrement[x=9, y=10]
Syntax: Pre Increment, Decrement

var y = ++x; x = 11, y = 11;


var y = --x x = 9, y=9

- JavaScript uses Math object to handle mathematical expression.

Math.PI
Math.cos()
Math.tan()
Math.sin()
Math.sqrt()
Math.pow()
Math.round()
Math.floor()
Math.ceil()
Math.random() ect..

End video no 49
=================================================================
What is difference between "==" & "===" ?
Ans: "==" can campare values of various types.
"===" can compare only identical types i.e same type.

var x = 10;
var y = "10";
x == y // true
x===y //false

5. Special Operators
new : dynamic memory allocation operator
?: : ternary operator
typeof : It return the data type of value stored in reference
delete : It deletes a key from object.
in : It can search for a key in object and return true if found.
void : It discards the return of a function.
yield : It return values of a function generator.
instanceOf : It return true if object belongs to specified class

JavaScript Statements
1. Selection Statements
if, else, switch, case, defualt
2.Looping Statements
for, while, do while
3.Iteration Statements
for..in, for..of
4. Jump Statements
break, continue, return,
5.Exception Handling
try, catch, throw, finally

JavaScript Exception Handling


- It is required in computer programming to avoid abnormal termination of
application.
- The statement required are

try : It defines a monitoring block


catch : It defines an handler block
throw : It throws the exception explicitly
finally : It executes always

Function Parameters:
- Parameters are required to modify a function

Syntax:
function Name (param) => param - formal parameter
{}

Name(value); => value - actual parameter

param = value;

End Videos no 50
----------------------------------------------------------------
Parameter Type
- A function parameter can e any type
a) Primitive
b) Non Primitive
c) Function

- In JavaScript formal parameter is just a reference name, into the parameter you
can store anything.

Syntax:
function demo(ref)
{} => ref -> number, string, Boolean, array, object

Multiple Parameter
- A function can have multiple parameters.
- Every parameter is required and have order dependency.
- If you want to ignore any specific parameter, then you have handle using
undefined type.

- ECMA allows max 1024 parameters.


- ES5+ version introduce "rest" parameters.
- A single rest parameter can handle multiple arguments
- A rest parameter is defined using "...paramName".
- It is an arrays type.
- Every function can have only one rest parameter.
- You can have other parameters along with rest parameter.
- Rest parameter must be the last parameter in formal list.

syntax:
function demo(..param1, ..param2) => invalid
function demo(..param1, title) => invalid
function demo(title, ..param1, ) => valid

- A rest parameter reads up-to end, hence it must be last parameter


Spread Syntax for Parameters
- A spread approach allows single value to spread into multiple formal parameters.

Syntax:
function demo(a,b,c,d)
{}
val values = =[10,20,25,50];
demo(..values)

Q. What is difference between rest parameter and spread parameter ?


Ans: rest parameter is use for formal parameter where's spread is
used for actual parameter.

Note: Rest is about the formal parameter, a single formal parameter allows multiple
arguments.

Spread is about the actual parameters , a single actual value can spread into
multiple formal parameters.
Spread actual value must be an array type.
Rest is also array

Function with Return


- Return is a jump statement.
- It terminates the function before it's memory is disposed.
- Hence we can use the function memory to store function values and access from any
another function.

Syntax:
function Name(){
return value;
}

- A function can return any type of value.


a) Primitive
b) Non Primitive
c) Function
End video no 51
================================================================

Function Closure

- Closure is a mechanism that allows the members of outer scope


accessible to inner scope.
- Ever function by default have a closure.
Syntax:

FUNCTION Outer()
{
function inner()
{
return value;
}
.. you can access inner value.
}

---------------------------------------------------------------
Function Generator
==================
- A function generator is used to create iterators in computer programming.
- Iterator is a software design pattern used to access elements from a collection
in sequential order.
- Iterator doesn't require condition, counter and initializer.
- Generator is defined using "&" which means zero or more times execution.
- The method "done()" returns true when there is no more value to read.

Syntax:
function * Name(){
yield value;
}
var ref = Name();
ref.next().value => return value
ref.next().done => return true if there are no
more values to red.
Function Call Back
==================

- It is a technique where we configure a set of functions that execute according to


state and situation.

- Call Back used blocking technique.


- It is Synchronous.
- It will not allow any other task to perform while executing the function.

Syntax:
function Name(classBack1, callBack2)
{
}
Name(function(){}, Function(){});

-----------------------------------------------------------------
Function Promise
- Promise Uses an Async technique.
- Async is an unblocking technique that allows the task to perform without blocking
tasks.
- Promise comprise of 3 phases.
a) pending : Initial phase
b) Resolved : It defined using then()
c) Rejected : It is defined using catch()

- then() will handle the response when it is success.


- catch() will handle the error when it failed.

Syntax:
var refName = Promise(function(resolve, reject){
if(condition)
{
resolve("on success");
} else{
reject("on failure");
}
});

refName.then(function()(){}).catch(function(){})

---------------------------------------------------------------
Arrow Function
- It is a short hand technique for writing a function expression.
- It uses following chars
() function & Its params
=> return and definition

Syntax without arrow


var addition = function(a,b){
return a+b;
}

Syntax: with arrow

var addition = (a,b) => a+b;

var hello=()=>{
stmt -1;
stmt -2;
}

Ex:
function Hello(uname)
{
document.write(`Hellow ! ${uname}`);
}

var Hello = uname=>document.write(`Hello ! {uname}`);


var Hello-(uname,age)=>document.write(`hello !${uname}
you age ${age}`);
================================================================
JavaScript OOPs
- In real world project development we use various programming systems like:
1. POPS
2. OBPS
3. OOPS

1. POPS
- Process Oriented programming System.
- It support low level features
- It can directly interact with hardware services.
- It is faster and used less memory.

Ex: C, Pascal

- Hard to extend
- Not having good dynamic memory
- Not good for reusability
- Not good in separation issues

2. OBPS
- Object Based Programming Systems
- It support reusability, separation
- I have dynamic memory

Ex: JavaScript, Visual basic,

- Extensibility issues
- No dynamic polymorphism
- No code level security
- no contracts & templates

3. OOPS
- Object Oriented Programming System
- Code reusability
- Code separation
- Code Extensibility
- Code Security

Ex: C++ , C#, JAVA

Drawback:

- Don't support direct low level features


- Can't directly interact with hardware
- The need more memory
- Complex in configure
- Tedious.

End Videos no 52
=================================================================
JavaScript Modules
==================
- A module is a set of values, functions and classes, which you can import and use
across location.
- It enables code reusability and extensibility.
- You can build a JavaScript library using modules.
- In order to use module you need a module system installed.
- There are various JavaScript module systems.
a) Common JS
b) Require JS
C) UMD (Universal Module Distribution)
d) AMD (Asynchronous Module Distribution)
e) ESMO

- If you are running JavaScript in browser with HTML page then browser have a
default modules system called "ESModule".

Syntax:
<script type="module">
</script>

How to Creating a module:

1. Go to "src" and add "library/modules" folders


2. Add a new file into modules folder

"home.module.js => module name is "home.module"

3. You can configure variable, function and classes in module, but every member in
module is private in access. If you want to access from remote location, then they
must be marked wht "export" keyword.

export const name= "";


export const name(){};
export const name{}
Every module can have one "default" export.
export default function name(){}

4. YOu have to import the module and it's member into HTML page by using "import"
statement.[other module systems have different statements]

import defaultMember, {other} form "moduleName";


import Welcom, {Hello} from "home.module.js"

document.querySelector("p).innerHTML = Welcome();
alert(Hello());
console.log(Welcome());
-----------------------------------------------------------------
Classes
- In computer programming class is a program template.
- A template provide sample data and logic which you can customize and implement
according to requirements.
- If a class is mapping to data requirements then it is referred as "module"
- If a class is mapping to business requirement then it is referred as "entity".
- If a class is action a source for several instances then it is referred as "Blue
Print"

Configuring class:

1. Declaration
class Name
{
}

2. Expression:

cons Name = class {


}

Class Members:
- Every JavaScript class can have only the following as class members

1. Property
2. Accessor
3. Contractor
4. Method

FAQ: Can we define variable or function as class member ?


Ans: No

FAQ: Can we define a variable or function in class ?


Ans: Yes

FAQ: Why function and variables are not allowed as class members
Ans: Variable and Function are Immutable.
A class member must be always mutable.
Hence variable and function can't be class member.

Accessing class members:


- The class member are accessible with in the class using "this" keyword
- The class members are accessible outside class by using instance of class.
Syntax:
class Employee
{
}
let obj = new Employee();
obj.Propery;
obj.Method();

Property :
-A property is used to store data.
- In JavaScript class property is having just a reference name.
- You can initialize any type of value.
- You can assign any type of value using instance of class.

Syntax;
class Product{
Name = "TV"; -> number, string, Boolean, null array ect
}
let obj = new Product();
obj.Name = "Samsung TV";
console.log(obj.Name);

- Property is mutable.
- A property can changes the behaviour dynamically according to state and
situation.

Accessors:
-Accessor are using to five fine grained control over the property.
- They allow to handle read and write operations on a property.
- There are 2 accessors
a. get() getter is used to read and return value of property.
b. setter is used to assign a new value into property.

Syntax:
get aliasName()
{
return property;
}

set aliasName(newValue)
{
property = newValue;
}

End video no 53
=================================================================
Method
======
- It is used for refactoring the code.
- It is similar to a function but mutable.
- All functionality is same like function.
Syntax:
class Name{
Method(){
}
}
Constructor
===========
- It is a special type of sub-routine using for instantiation.[creating object]
- Every class have a default constructor that creates an object for class.
- JavaScript constructor is "anonymous";
- It is defined with constructor keyword.
Syntax:
class Name{
constructor(){
}
}
let name = ClassName();
- Constructor is executed only once per object.
- JavaScript constructor doesn't support access modifiers, overloading ect.

Code Reusability & Extensibility


===============================

- You can handle conde reusability and extendibility by using 2 techniques.

1. Aggregation
2. Inheritance

- Reusability is the process the member from one class and using in another
classes.

- Extensibility is the process of extending the logic without modifying the


existing.

Aggregation:

- It is the process of accessing members of one class in another class without


configuring any relation between classes.

- It is known as "Object-to-Object" communication.


- It is often referred as "Has-A-Relation".

syntax:
class A
{
// members
}
class B
{
// create instance of class A to access it's members
}

Inheritance:

- It is the process of accessing members of one class in another class by


configuring relation between classes.

- You can use "extends" keyword that extends the existing class.
- The new class is known as "Derived" class.

Syntax:
class A {}

class B extends A {} => A is super & B is derived class

- You can access the members of super class using "super" keyword
- This is referred as "Is-A-Relation".

Polymorphism:

- Poly means "Many".


- Morphos means "Forms".
- The ability of a single component to work for various situations is referred as
situations is re as Polymorphism.
- A single base class object can the memory of multiple derived classes.

End Videos no 54
=================================================================
JavaScript Events
-----------------
- Event is a message sent by sender to it's subscriber in order to notify the
change.
- It follows a software design pattern called "observer".
- Observer is a communication pattern.

Syntax:
function InsertClick() => subscriber
{
}

<button onclick = "InsertClick()"> => sender

- Subscriber defines actions to perform.


- Sender triggers the notification.

- JavaScript events have 2 default arguments


a) this
b) event

<button onclick="InsertClick(this,event)">

- "this" sends information about current element, which includes id, name,
className, width, height, src, href ect.

- "event" sends information about current event, which includes client, clientY,
shiftKye, ctrlKey, altKey, ect..

- you can also sent custom arguments using event.


- Custom argument can be any type.
a) primitive
b) Non primitive
c) function ect.

Syntax:
function handleClick(obj, collection)
{
}

<button onclick="handleClick( {},[])">


- Every event comprises of following
a) Event
b) Event Handler
c) Event listener

onclick = "InsertClick()" => Event Handler


onclick => Event

- If element is dynamically created, then we have to configure events using Event


Listener.

EventListener required various events to configure dynamically, the JavaScript


events are classified into following categories.

1. Mouse Events
2. Keyboard Events
3. Button Events
4. Form Events
5. Touch Events
6. Element state Events
7. Timer Events
8. Clipboard Events ect.

1. Mouse Events:
- onmouseover
- onmouseout
- onmousedown
- onmouseup
- onmousemove

2. Keyboard Events
- onkeyup
- onkeydown
- onkeypress

3. Button Events
- onclick : single click
- ondbclick : double click
- oncontextmenu : right click
- onselectstart : hold down the button and drag to select

Note: If any event you want to disable, then define "return" false.

5. Touch Events
- ontouchstart
- ontouchand
- ontouchmove

6. Element state Events


- onchange
- onblur
- onfocus

7. Timer Events
- setTimeout()
- clearTimeout()
- setInterval()
- clearInterval()

8. Clipboard Events

- oncut
- oncopy
- onpaste

End videos no 55
================================================================
4. Font Event
- onsubmit
- onreset

- The form event are defined for <form> element.


- They fireup only on submit and reset button clicks.
- They define actions to perform when form is submitted or user resets the form.
Syntax:
<form onsubmit="function" onrest="function"></form>

FAQ: How to submit form using other HTML elements?


Ans: You have to call the form "submit()" on the specific element event.

Adding Event Listener


---------------------
- You can add events to HTML element without configuring and event handler.
- It allows dynamically to configure events.
- It make clean separation of code and UI.
- You have to configure Event Listener on specific event or using module system.

Syntax:
document.querySelector("button").addEventListener
// action perform
("evenName", functon(){
})

FAQ: How to change event for element dynamically ?


Ans: By adding Event Listener.

State Management Techniques


---------------------------

- Every web application uses "http or https" as protocol.


- Http is a state less protocol.
- It can't remember information between pages.
- Hence web application implement various state management techniques to store data
and access across pages or requests.
- The state management is classified into 2 types

a) Client side Management


b) Server side Management

a) Client side Management:


- Client side Management allows to store data on client device
- The various client side state management techniques are:
1. Query String
2. Local Storage
3. Session Storage
4. Cookies

1. Query String
- A query string is appended into URL with a key and value reference.
?key=value

- Any form can submit it's data into query string on "Get" request.
- You can access querying using "location.search"

Ex:
1. Add a new folder
"State"
2. Add files
home.html

Local Storage
-------------
- Every browser have a local storage.
- It is permanent storage.
- It is available even after you device shut-down.
- you have to delete manually from browser memory.
- It is accessible across all tabs in browser.

Syntax:
localStorage.setItem("key","value");

var value = localStorage.getItem("key");

Session Storage
---------------
- It is temporary storage.
- It is not accessible to other tabs.
- It is removed when browser is closed.

Note: You can store 10mp of data in local or session storage.

Syntax:
sessionStorage.setItem("key","value");

var value = sessionStorage.getItem("key");

sessionStorage.removeItem("key");

Cookies
-------
- Cookies are simple text documents.
- Client related information can be sorted in a cookie file and used later by page.
- Cookies need to be enabled in browser.
- You can verify cookie status by using

"navigator.cookieEnable" => true if enabled with cookies


- Cookies can be in-memory [temporary] or persistent[permanent]
Syntax:
document.cookie="key=value; expires=date time";

var ref = document.cookie;

document.cookie = "key;" => delete cookie

*****************************************************************

You might also like