-
JavaScript
----------
[Link] was created in 1995 by Brendan Eich while working at Netscape Communications
Corporation.
[Link], it was developed in just 10 days and was intended to add dynamic content and
interactivity to webpages.
interaction
-----------
trainer (speaking - output) --> students (listening - input)
students (speaking - output) --> trainer (listening - input)
trainer <--> students
webpage
-------
pages viewing (logo, icons, buttons, images, text....) on the browser is called a webpage.
end user <input, output : keyboard, mouse> webpage
[Link] Confusion: Despite the similarity in name, Javascript is not related to Java. The name
was chosen due to Java's popularity at the time, which was seen as a marketing strategy.
[Link] browser that influenced its development was Netscape Navigator, which was one of the
most popular web browsers during the mid-1990's.
[Link] was quickly adopted by other browsers, leadings to its wide usage across the web.
[Link] first version was called Mocha, then LiveScript, before finally being named JavaScript.
[Link]-End or Client-Side or Browser based Development
-------------------------------------------------------
JavaScript frameworks and libraries like React (lib), Angular (framework), [Link], jQuery have
revolutionized front-end development.
[Link]-End Development
----------------------
JavaScript is not limited to front-end development. With the advent (arrival) of [Link],
JavaScript can now be used for server-size programming as well. Node.s allows developers to
build scalable and high-performance back-end services using javascript.
[Link] and Structure:
-----------------------
JavaScript shares some syntax similarities with other programming languages like Java and C,
But it has unique features.
[Link] primarily event-driven. This means JavaScript code is often written to respond to
user actions clicks, form submissions, or keyboard inputs.
[Link] is dynamically typed, meaning we don't need to declare variable types explicitly (It
means that we do not have to clearly and specifically define or state the type of variable (Such
as whether it's a number, string or Boolean..) when declaring it in JavaScript.).
C, C++, Java : Statically Typed
JavaScript, ECMAScript : Dynamically or Loosely or Lightweight Typed
C Javascript
----------------------------------------------------
int a=10; var a=10;
float b=10.14; var b=10.14;
[Link] save it with .js extension.
Types of Scripts
----------------
[Link] script
-----------------
[Link] we write script part in our html file itself is called internal script.
[Link] save it with .html extension.
[Link]() method or function is used to write content directly to the html document.
Method is like a verb which performs some work or action.
window and document
-------------------
window : Entire browser
document : Particular part in the window
[Link] Script
-----------------
[Link] we write script part outside our html file is called external script.
[Link] save it with .js extension.
[Link] Script
---------------
[Link] write script code directly with an html HTML element is called inline script.
[Link] save it with .html extension.
[Link] using the onclick, onload or similar event attributes.
[Link] : An actions (onclick, onload, onmouseover.....) performed on the browser.
write() / writeln() : new line or line break (pre tag)
------------------------------------------------------
[Link] case if writeln we can see space between writeln statements.
Output :
--------
JavaScript can display content in different ways
[Link]() / [Link]() - writing into the html document (browser)
[Link]() - browser console
[Link]() or alert() - popup box
[Link] - to update content in html element
[Link]() - method in the browser to print the content of the current window
DOM - Document Object Model methods
Comments
--------
[Link] Line (//)
[Link]-line (/* */)
[Link] (<!-- -->)
NOTE
----
[Link] explain Javascript code in program itself.
[Link] hide or prevent the code from execution.
[Link] + ? or ctrl + / = to add or remove the comment.
[Link]+shift+a = to add or remove multi-line comment.
[Link] tags (p, style, script...) supports only html comment.
lowercase : sivasofttraining
uppercase : SIVASOFTTRAINING
underscore : siva_soft_training
Camel Case or Lower Camel Case : sivaSoftTraining
Upper Camel Case (Pascal Case) : SivaSoftTraining
Variables
---------
var - prefix - js
let, const - prefix - es6 / typescript
[Link] are used to assign (store or hold) the values
[Link] variable should starts with prefix called var.
ex : var x=10;
[Link] variables are Dynamically or Loosely or Lightweight Typed
C Javascript
----------------------------------------------------
int a=10; var a=10;
float b=10.14; var b=10.14;
[Link] variables can starts an Alphabets or underscore(_) or dollar($) not with a number but can
include number
[Link] variables are case-sensitive (A not equal to a)
[Link] variables can be a short-name (a) or a descriptive name (carname).
[Link] words (like javascript keywords) cannot be used as variables
ex:
---
Some examples of JavaScript reserved words include:
break, case, class, const, continue, debugger, default, delete, do, else, export, extends, finally,
for, function, if, import, let, return, super, switch, this, throw, try, typeof, var, void, while, with,
yield.
NOTE: Avoid using hyphen's (-) in javascript variables.
[Link] soft
2.siva_soft
[Link]-soft
siva-soft (subtraction)
10-5 = 5 (subtraction)
Automatically Declared variables
Operators
---------
[Link] Operators
----------------------
Addition(+), subtraction(-), multiplication(*), division(/), modulus(%), increment(++),
decrement(--)
ex : 10/2 = 5 (quotient) , 10%2 = 0 (remainder)
2)10(5
10
__
(0)
x+y
+ : Operator
x,y : Operands
[Link] Operators
----------------------
Assignment operators assign values to javascript variables.
=, +=, -=, *=, /=, %=
ex : x+=y x*=y
x=x+y x=x*y
JavaScript has 8 Datatypes
--------------------------
String
Number
Bigint (Es6)
Boolean
Undefined
Null
Symbol (Es6)
Object
Popup Boxes
-----------
[Link]() or alert()
[Link]() or confirm()
[Link]() or prompt()
parseInt() function
-------------------
to convert string to number
"10" = 10
"2.4" = 2
parseFloat() function
-------------------
to convert string to decimal
"10" = 10
"2.4" = 2.4
Comparison Operators
--------------------
var x=10;//Assignment or Storing
(x==10);//(10==10) true Comparison or checking
Operators condition result
------------------------------------------------------------------------------------------------------
== (equal to) x==10 true
x=="10" true
=== (based on data type or exactly equal to) x===10 true
x==="10" false
!= (not equal) x!=10 false
x!="10" false
!== (based on data type or exactly not equal to) x!==10 false
x!=="10" true
> (greater than) x>10 false
x>"10" false
>= (greater than or equal to) x>=10(x>10 f or x==10 t) true
x>="10"(x>"10" f or x=="10" t)true
< (less than) x<10 false
x<"10" false
<= (less than or equal to) x<=10(x<10 f or x==10 t) true
x<="10"(x<"10" f or x=="10" t)true
Conditional statements
----------------------
[Link] statement
[Link]..else statement
[Link]..else if..else statement
[Link] statement
[Link] statement
--------------
Code to be executed if the specified condition is true
syntax
------
if(condition){
code to be executed if the condition is true
}
{ } - declaration block or block
[Link]..else statement
--------------
Code to be executed if the specified condition is true or false
syntax
------
if(condition){
code to be executed if the condition is true
}
else {
code to be executed if the condition is false
}
[Link]..else statement
--------------
Code to be executed from one of many blocks of code
syntax
------
if(condition1){
code to be executed if the condition1 is true
}
else if(condition2){
code to be executed if the condition2 is true
}
else {
code to be executed if the condition1 and 2 are false
}
Logical Operators
------------------
&& (AND) : It should satisfy all the conditions
|| (OR) : It should satisfy atleast one condition
! (NOT) : pending
Switch statement
----------------
Code to be executed from one of many statements.
syntax
------
switch(n){
case label1:code to be executed if label1=n;break;
case label2:code to be executed if label2=n;break;
case label3:code to be executed if label3=n;break;
default:code to be executed;
}
Loops
-----
[Link] loop
[Link] loop
[Link]..while loop
[Link]/in loop
[Link]/of loop
[Link] loop
----------
Loops through a block of code specified number of times
syntax
------
for(initialization;condition;increment){
code to be executed
}
initialization : start
increment : 10++ = 11
[Link]..loop
-------------
loops through a block of code until the specified condition is true
syntax
------
while(condition){
code to be executed
}
Note
----
for..loop : A for loop is used when we know the number of iterations in advance.
while..loop : A while loop is used when the number of iterations is not known before and
depends on a condition. It executes as the condition is true.
Assignment
9:30AM - 10:30AM : 1hr for loop : 10 times (10min,20min,5min)
9:30AM - 10:30AM : 1hr while loop : 10,20,100times
java,node,python --> rest api
javascript : while
[Link] : 1000 students (email and password)
[Link]..while loop
----------------
Loops through a block of code atleast once and code to be executed as long as the specified
condition is true
syntax
------
do{
code to be executed
}while(condition)
Note
----
while loop: first it checks the condition if the condition is true then only code to be executed
do..while loop: first it executes the output (js statement) then only it checks the condition if the
condition is true then the code will be executed otherwise loops execution stops.
[Link]..in loop
--------------
The javascript for in statement loops through the properties of an object.
syntax
------
for(key in object){
code to be executed
}
NOTE: In JavaScript each and everything will be considered as object.
ex : number(x=10), string(x="siva"), boolean(true or false), { } - object, [ ] - arrays, function, Date,
Math,.....
person={firstname:"Siva",lastname:"Soft",age:15}
firstname, lastname, age = keys or properties or names
Siva, Soft, 15 = values
[Link] of loop
-------------
The javascript for of statement loops through the values of an iterable object (array)
syntax
------
for(variable of iterable){
code to be executed
}
function
--------
A function will be executed just by a call or an event.
syntax
------
function functionname(){
code to be executed
}
function with arguments or parameters
-------------------------------------
In JavaScript, a function with arguments allows us to pass values to the function when it is
called. These values are recieved by the function as parameters.
syntax
------
function functionname(argument1,argument2,........){
code to be executed
}
function with return statement
------------------------------
[Link] is used to return the value whenever we call the function.
[Link] return statement should be the last statement inside the function (one return statement
then return should be the last statement or even if we have block also in that block return should
be last statement).
[Link] return statement terminates the function's execution and specifies the value to be
returned.
syntax
------
function functionname(){
code to be executed;
return;
}
Local and Global Variables
--------------------------
Local variables : Local variables are used within a specific function or block and cannot be
accessed outside the function or block.
Global variables : Global variables are declared outside of any function or block and cannot be
accessed from anywhere in the script (inside and outside the function)
Function Invocation(calls)
--------------------------
The code inside the function will execute when something invoke(calls) the function
[Link] it invoked(called) from javascript code
[Link] (self invoked) (Anonymous function (no name))
-------------------------------------------------------------
Function Declaration Vs Function expression
-------------------------------------------
Declaration
-----------
Defines a function and assign it a name. It's a statement, not an expression.
function sayHello(){
[Link]("Hello");
}
sayHello();
Expression
----------
Defines a function and can be assigned to a variable. It is treated as an expression
var sayHello=function(){
[Link]("Hello");
}
sayHello();
Automatically (self invoked) (Anonymous function (no name))
-----------------------------------------------------------
(function(){
var message="This is a self-invoked function!";
[Link](message);
})
();//Immediate invocation
(function(){....}): This creates a function expression. The parenthesis around the function
declaration tell javascript to treat the function as an expression.
Closures
--------
A Closure is a features in javascript where inner function access to outer(enclosure) function's
variables - a scope chain.
NOTE:
-----
LOCAL VS GLOBAL is the sample scope (scope refers to the context or region within a
program where a variable or function is accessible).
[Link] to its own scope (variables defined between its curly brackets)
[Link] to the outer function's variables
[Link] to global variables.
[Link] an even occurs (when a user clicks button)
-------------------------------------------------
JavaScript events are actions or occurrences that happen in the web browser that javascript can
detect and respond to. These events can be user-initiated, like clicks and key presses, or
browser-initiated, like page loading or unloading.
NOTE:
-----
Events are case-insenstive(onClick = onclick)
Common Event Types:
-------------------
[Link] Events:
---------------
click: Occurs when an element is clicked.
dblclick: Occurs when an element is double-clicked.
mouseover: Occurs when the mouse pointer is over an element.
mouseout: Occurs when the mouse pointer leaves an element.
mousedown: Occurs when the mouse button is pressed on an element.
mouseup: Occurs when the mouse button is released over an element.
[Link] Events:
------------------
keydown: Occurs when a key is pressed down.
keypress (Deprecated): Occurs when a key is pressed and held (doesn't capture special keys
like Shift or Ctrl).
keyup: Occurs when a key is released.
Form Events:
-----------
submit: Occurs when a form is submitted.
change: Occurs when the value of an element is changed.
focus: Occurs when an element gains focus.
blur: Occurs when an element loses focus.
input: Occurs when the user input changes the value of an element.
Window Events:
-------------
load: Occurs when the document has finished loading.
resize: Occurs when the browser window is resized.
scroll: Occurs when the user scrolls the content.
unload: Occurs when the user leaves the page.
Document Events:
----------------
DOMContentLoaded: Occurs when the HTML document has been completely loaded and
parsed.
visibilitychange: Occurs when the content of a tab becomes visible or hidden.
In JavaScript each and everything will be considered as object.
ex : number(x=10), string(x="siva"), boolean(true or false), { } - object, [ ] - arrays, function, Date,
Math, elements (p,h1-h6,a...), this, event or e (event object), .....
HTML Forms
----------
In HTML, a form is an element used to collect user input (typing, checking, selecting, clicking
and so on).
It allow users to enter information and then submit it to a server to store form data in this
database
HTML --> user input --> click on submit --> python, nodejs --> mysql or mongodb or sql or
postgresql
input
-----
It is used to accept user input.
text : Single-line text field
email
password
submit : Button to submit the form (to send form data to the server page)
radio
checkbox
form
----
method="get" (The Get method is used to send the data in the URL query string) :
--------------------------------------------------------------------------------
[Link] form data to the URL(uniform resource locator)
[Link] can send limited data i.e, 2048 characters
[Link] secure (form data in URL)
method="post" (The POST method is used to send the data in the request body instead of URL
):
-------------------------------------------------------------------------------------
[Link] can send form data in Hidden format (we can't see any data in the URL)
[Link] can send Unlimited form data to the server page (action="[Link]")
[Link] Secure (we can't see any data in the url)
refactoring
Math Objects
------------
[Link]()
[Link]()
[Link]()
[Link]() - ES
[Link]()
setTimeout() function or method or object
-----------------------------------------
The setTimeout method executes a function once after a specified delay(in milliseconds)
syntax : setTimeout(function, delay)
1000ms = 1s
setInterval() function
----------------------
The setInterval method in javascript that repeatedly calls a function or executes a code
snippet(some lines of code) at specified time intervals (in milliseconds), until it is stopped with
clearInterval.
syntax : setInterval(function, interval)
1000ms = 1s
<input type="button" onclick="ss()">
addEventListener
Event Bubbling
--------------
parseInt()
parseFloat()
Escape characters
-----------------
\' , \", \\
\b, \n, \r, \r, \t - javascript
Template strings (es6)
----------------
''
""
`Siva ` - backticks
Arrays :
--------
Arrays are used to assign more than one value.
or
Collection of objects.
ex : mixed types : number, string, boolean......
or
An Ordered, integer indexed collection of objects
ex : var x=[3,4,"Siva",true]
x[0] = 3
x[3]=true
Associative Arrays
------------------
Many programming languages supports arrays with named indexes
Arrays with named indexes are called Associative arrays (or hashes)
JavaScript doesn't support arrays with named indexes
In javascript, arrays always use numbered indexes
var z=new Array();
z[0]="siva";
z[1]="soft";
z[2]="12";
JS DOM (Document Object Model)
-----------------------------
Document (.html)
Object (html, p, title, a....)
Model (Tree of objects)
Document (.html)
|
<html>
<head> <body>
| |
<title> <p> --> align
| <a> --> href
my title |
</head> </body>
</html>
with the object model, javascript gets all the power it needs to create dynamic HTML
------------------------------------------------------------------------------------
[Link] can change all the HTML elements in the page.
[Link] can change all the HTML attributes in the page.
[Link] can change all the CSS styles in the page.
[Link] can remove existing html elements and attributes.
[Link] can add, replace new html elements and attributes.
[Link] can react to all existing html events in the page.
[Link] can create new html events in the page.
DOM Methods
-----------
HTML DOM methods are actions we can perform on HTML elements.
[Link]()
[Link]()
[Link]()
innerHTML - property (store or hold)
BOM (Browser Object Model) methods
----------------------------------
window
[Link] Boxes
-------------
[Link]() or [Link]()
[Link]() or [Link]()
[Link]() or [Link]()
[Link]
--------
setTimeout() or [Link]()
setInterval() or [Link]()
[Link]
-----------------
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]()
[Link]
---------------
[Link]
------------------
[Link]
----------------
Object contains the browsers history
Cookie : we can store and retreive data from our browser
as per HTML5 w3c cookie is deprecated (removed)
----------------------------------------------
[Link] having security concern
[Link] can store 4kb of data
[Link] of javascript cookie we are HTML5 web storage (localStorage and sessionStorage)
with security and we can store a maximum 5MB of data.
Form Validation
regular Expressions
-------------------
character classes
-----------------
\d : Matches any digit (equivalent to [0-9])
\D : Matches any not-digit
\w : Matches any word character (equivalent to [a-zA-Z0-9_])
\W : Matches any non-word character
\s : Matches any whitespace character
\S : Matches any non-whitespace character
. : Matches any character except new line
Anchors
-------
^ (carat) : Asserts the start of the string
$ : Asserts the end of the string
Quantifiers
-----------
* : Matches 0 or more times
+ : Matches 1 or more times
? : Matches 0 or 1 time
{n} : Matches exactly n times
{n,} : Matches n or more times
{n,m} : Matches between n and m times
Groups and Ranges
-----------------
[abc] : Matches any of a,b, or c
[a-z] : Matches any lowercase letter
[A-Z] : Matches any uppercase letter
| : Acts as an 'OR' operator within regex
Alphabetical
------------
/^[a-zA-Z]+$/ : a,b,...z A,B.....Z + one or more
/^[a-zA-Z]{3,5}$/ : a,b,...z A,B.....Z {3,5} min 3 and max 5
Alphanumeric
------------
/^[a-zA-Z0-9]+$/ : a,b,...z A,B.....Z 0,1,2....9 + one or more
/^[a-zA-Z0-9]{3,5}$/ : a,b,...z A,B.....Z 0,1,2....9 {3,5} min 3 and max 5
Email
-----
/^[a-zA-Z0-9._%+-]+@[Link]$/ : s-df+sd_fs.dF%9@[Link]
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/; : s-df+sd_fs.dF%9@[Link]
[Link] : info@[Link], sivasoft@[Link]
[Link] : info@[Link]
Password
--------
^ : Asserts the start of the string
(?=.*[A-Z]) : Ensures there is atleast one uppercase letter
(?=.*[a-z]) : Ensures there is atleast one lowercase letter
(?=.*\d) : Ensures there is atleast one digit
(A-Za-z\d){8,} : Matches letter and digits, with a minimum length of 8 characters
$: Asserts the end of the string
/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[A-Za-z\d]{8,}$/;
Image
-----
[Link]
[Link]
[Link]
/\.(jpg|png|gif)$/i
i : Case-insenstive flag(condition)
async / await
javascript
ECMAScript
typescript
(variables, operators, conditions or decisions, loops, functions)
JS Variables : var x=10;
ES6 variables : let x=10; or const x=10;
TS variables : let x:number=10; or const x:string="Siva";
Browser Compatibility Issues: not support in the available browsers
bootstrap
angular or react
let, const, arrow functions - react
let, const, arrow functions, class - angular
Hoisting
--------
Hoisting is JavaScript's default behavior of moving declarations to the top
AJAX
----
1. Asysnchronous Javascript and XML
2. Definition: AJAX is a web development technique used for creating interactive web
applications. It allows a webpage to send and receive data from a server Asysnchronously
without refreshing or reloading the entire page. This makes the user experience more dynamic
and responsive.
Asysnchronously: AJAX allows parts a webpage to be updated independently, making the data
retrieval process non-blocking, meaning user can continue interacting with the page while data
is being fetched.
How AJAX Works
--------------
onreadystatechange: Defines a function be called when the readyState property changes.
readyState :
------------
Holds the status of the XMLHttpRequest object.
0: request not initialized
1: server connection established
2: request recieved
3: processing request
4: request finished and response is ready
status
------
200 : "OK"
404 : "Page not found"
open(method,url,async)
---------------------
Specifies the type of request
method : the type of request: GET(to get the data from doc or serverpage) or POST(to send the
data to the server page)
async : true (Asynchronous) or false(synchronous)
send() : Sends the request to the server (used for GET)
send(string) : Sends the request to the server (used for POST)
Callbacks
---------
Callback Function: A Callback is a function passed as an argument to another function.
This technique allows a function to call another function.
A callback function can run after another function has finished
Asynchronous
------------
Functions running in parallel with other functions are called Asysnchronous.
Promises
--------
I Promise a Result
"Producing Code" is code that can take some time
"Consuming Code" is code that must wait for the result
A Promise is an Object that links Producing Code and Consuming Code
Async/Await
-----------
aync and await make promises easier to write
async makes a function return a promise
await makes a function wait for a promise
function myFunction(){
return [Link]("hello");
}
async function myFunction(){
return "hello";
}
Await
-----
await keyword can only be used inside async function
The await keyword makes the function pause the execution and wait for resolved promise
before it continues
var value=await promise;
Nested Objects : JSON
x=1
x=x+10
x=1+10
[Link](x)//11
x=0
x++
x=x+1
x=0+1
x=1
x++
x=x+1
x=1+1
x=2
Angular ts is mandatory
React JS / TS