Sr. No | Topic Name |
---|---|
1. | Javascript |
2. | Adding JS to the HTML |
3. | Javascript datatypes |
4. | Variables, Constants, NAN and Comments |
5. | Short hand Notation, Ternary operator and Template string |
6. | Loose vs Strict Comparison |
7. | Type Conversion |
8. | Conditional Statements , Switch, Loops in JS |
9. | Break and Continue |
10. | Functions and Methods |
11. | Arrow Function => |
12. | Callback Methods |
13. | Date and Time object in JS |
14. | Object literals, Array, Set, String and Map in JS |
15. | DOM (Document Object Manipulation) |
16. | Regular Expression |
17. | More ES6 JS Features (like spread, rest etc) |
18. | Throwing and Catching Error |
19. | Objects and Classes in JS |
20. | Local Storage |
21. | Async JS |
22. | Callback functions and Fetch API |
23. | Promises and Async and Await |
JavaScript often abbreviated as JS, is a programming language that confirms to the ECMAScript specification.JavaScript is :-
- High-level
- Just-in-time compiled
- Multi-paradigm
- Dynamic typing
It has curly-bracket syntax, prototype-based object-orientation, and first-class functions.
To write JS code in same HTML file.
<script>
code blocks..
</script>
When JS code is written in different file.
<script src = 'JS file location with name eg. /a.js'>
</script>
- Numbers : To describe any numbers.
- String : To describe any sequence of characters.
- Boolean : To describe True or False.
- Null : Explicity set a variable with no value.
- Undefined: For Variables that have not yet been defined.
- Object : To describe real world objects.
- Symbol : To uniquely identify objects.
let age = 21; // Number
let lastName = "Krishna"; // String
let fullName = {firstName:"Narayan", lastName:"Krishna"}; // Object
let checkFlag = true // Boolean
let fav // Undefined
let symbolOne = Symbol() // Symbol
git checkout JS_Datatypes //includes more examples in index.html
var (block the use of block scope), let and const were used for storing variables.
According to ECMA script :-
- let : for using variables
- const : for using constant value
Comments are used for describing our code.
/* Multi line
Comment */
// Single Line Comment
In JS NaN stands for Not a Number.
- Short hand notation is used for assigning values.
- Template string is used for formatting string.
Syntax :
`Sequence of characters ${variable_name}`
- Ternary operator is used to shortend conditional statement.
Syntax :
Conditional statement ? code blocks if true : code blocks if false or else code blocks
Some Examples :-
// Short hand notation
/* +=, *=, /=, %=
eg. a+=1 is a = a+1
*/
let a = 5, b = 5
a+=1
console.log(a)
b = b+1
console.log(b)
// Template string
let name = 'Narayan'
let greet = `My name is ${name} and hello.`
console.log(greet)
// Ternary Operator
let pass = true
pass ? 'gate open' : 'gate closed'
Loose comparison : Doesn't type check and denoted by ==
Strict Comparision: Does type check and denoted by ===
let age = 25
console.log(age=='25') //loose comparision
//Strict comparision
console.log(age===25)
console.log(age==='25')
It is used to convert one datatype to another if possible.
Examples :-
let score = '100'
let check = True
console.log(score)
//Type conversion to number
score = Number(score)
console.log(score)
//Type conversion to boolean
check = Boolean(check)
console.log(check)
//Type conversion to string
score = String(score)
console.log(score)
Syntax :-
if (condition){
code block..
}
else if (condition){
code block..
}
else {
code block..
}
Syntax :-
switch(variable_name){
case 1: code block..
break
case 2: code block..
break
.
.
.
case n: code block..
break
default: code block that always executes
break
}
To iterate elements. Syntax :-
// while loop : Iterate when condition is true
while(condition){
code block..
}
// do while loop : Iterate at least one time wheither condition is true or not.
do{
code block..
}while(condition)
// for loop
for (let i = start_value; i<stop_value; i++ /* jump over value */ ){
code block..
}
// for of and for each loop
// for of loop
for (let element of arr){
console.log(element)
}
//forEach loop
array_name.forEach(function_name /* Function that executes for every element in array_name */)
Break : Break out of the loop.
Continue : Goes to the next iteration and also don't execute the code for ongoing iteration.
Keywords used - break
, continue
Functions are used to use same block of code multiple times without writing whole code again and again.
Methods are the functions used inside the class. Syntax :-
// Function Declaration
function function_name (){
// block of codes....
}
// Function Expression
const function_name = function(){
// block of codes
}
// Function call
function_name()
Arrow function is used to shortend function declaration.
Syntax :-
const function_name = () => {
// code block
return value
}
When function is pass as an argument to an another funtion then the function that is an argument is called callback function.
Syntax :-
function callback_function_name(){
// block of code...
}
function function_name(callback_function_name){
callback_function_name(value)
}
To use date and time in javascript.
Syntax :-
const date_variable_name = new Date() // Date constructor
Have Multiple Props (i.e multiple variables or functions).
Syntax :-
let object_literal_name = {
prop_1 : '...';
prop_2 : '...';
.
.
.
}
// To access props from object literal
object_literal_name.prop_1
Ordered collection of elements.
Syntax :-
let array_name = []
let array_name = new Array( /* no. of elements */ )
// Some array methods
array_name.length
array_name.pop()
array_name.push()
array_name.sort()
array_name.reverse()
array_name.map(function_name)
Sequence of characters.
Syntax :-
let string_name = ''
// Some methods
string_name.toUpperCase()
string_name.trim()
string_name.startsWith()
string_name.replace(s1, s2)
string_name.slice()
string_name.substr()
string_name.indexOf()
Unordered collection of elements, O(1) time complexity.
Syntax :-
let set_name = new Set()
// Some methods
set_name.has()
set_name.add()
set_name.size
set_name.delete()
set_name.values()
Mix of Array and Set, Have keys and values also override similar keys.
Syntax :-
let map_name = new Map()
// Some methods
map_name.get('key_name')
map_name.set('key_name', value)
map_name.delete('key_name')
map_name.size
map_name.has('key_name')
map_name.clear()
map_name.entries()
- Main Part of webpage manipulation through JS.
- Interaction with HTML through JS.
- "document" object
document.querySelector() // . represents class, # represents id
document.querySelectorAll()
document.getElementById() // Single Element grab
document.getElementByClassName() // Multiple items of same class grab
document.getElementByTagName()
element_name.innerText = ` `
element_name.innerHTML = ` `
element_name.setAttribute('style','color : green')
element_name.getAttribute('attribute_name')
HTML Collection | Node List |
---|---|
Collection of HTML elements | Collection of document nodes |
Can be access through name, id, index | Can be accesed by their index number |
To add functionality to events that can be mouse or keyboard event.
.addEventListener('event', function())
Window object is global object and is defaultly used.
It is used for string pattern matching.
Example :-
let test_ex = 'Krishna'
const pattern = /^[a-z]{6,}$/ // /-> start and end; ^-> start; [a-z]-> a to z;{ }->length; $->end;
console.log(pattern.test(test_ex))
rest
is used for packing or bundling of multiple variables.spread
is used for unpacking ir unbundling of multiple variables.
Syntax :-
...variable_name // rest : converts from group of numbers to array and spread : converts from array to group of numbers
Error handling.
Syntax :-
try {
// block of code
}
throw new Error()
catch(err){
// Error handling
}
finally{
// block of code executes regardless of try/catch.
}
Implementation of real world objects and their structure/blueprint. It is a modern JS feature and is working along with prototypes to provide OOPS concept.
Syntax :-
// class
class ClassName{
constructor(attributes){
// Initialization of class
this.attributes = attributes
}
}
// object
let object_name = new ClassName()
// the 'new' keyword creates a new empty object {} and binds the value of 'this' to the new empty object.
// Subclasses and Inheritance
class SubClassName extends ParentClassName{
constructor(attributes,inherited_attributes){
super(inherited_attributes)
this.attributes = attributes
}
}
It provide local storage to store and retrive data from the browser.
// Store data in local storage
localStorage.setItem('key_of_the_object','value_of_the_object')
// Get data from local storage
let variable_name = localStorage.getItem('key_of_the_object')
// Updating the data
localStorage.setItem('key_name','value')
// or
localStorage.key_name = 'value'
// Deleting data
localStorage.removeItem('key_name')
localStorage.clear() // to delete all file
Asynchronous model allows multiple things to happen at the same time while in synchronous model things happens one at a time.
AJAX
- Asynchronous Javascript And XML
- No page reload/refresh
- XML is replaced by JSOn
How AJAX Works ?
AJAX uses XMLHttpRequest object to accomplish no page reload. Data can be transferred in any format http is not neccesary.
Working of AJAX :-
const xhr = new XMLHttpRequest() // Create an object
xhr.open('GET/POST','file_name',true)// Open the object
xhr.onprogress = function_name // What to do when in progress
xhr.onload = function_name // What to do when response is ready
xhr.send() // send the request
Function passes or executes after completion of first function.
Callback Hell, phenomenon that occurs due to nesting of callbacks. To avoid it we use promises in JS.
Three steps :-
- fetch data
- take response promise
- access data
Syntax :-
fetch(location_of_resource) // return promise
.then((response)=>{
console.log('resolved_response')
return response.json()
})
.then(data=>{
console.log(data)
})
.catch(error=>{
console.log(error)
})
- pending
- resolved
- rejected
Gives more readabilty to async JS code.
Syntax :-
async function function_name(){
const function_name_1 = await fetch('')
}