Javascript Summary
Table of Content
- Basics
- Arrays
- Objects
- Functions
- Control Flow
- Loops - Iterations
- Filter and Reduse
- Document Object Model
- Events
- API Requests
- Promises
- Fetch Requests
Variables
Prefer not to use var
because of issue in block scope and functional scope
Data Types
- “use strict” Treats all JS code as newer version.
- number => 2 to power 53
- bigint
- string => “”
- boolean => true/false
- null => standalone value
- undefined =>
- symbol => unique
console.log(typeof undefined);
console.log(typeof null);
Comparisons
Null
console.log(null > 0);
console.log(null == 0);
console.log(null >= 0);
Undefined
console.log (undefined == 0);
console.log (undefined > 0);
console.log (undefined < 0);
Strings
String operations
- slice
- trim => removes spaces
- replace
- includes, join
- split => Array
Nums
const hundreds = 1000000
console.log(hundreds.toLocaleString());
console.log(hundreds.toLocaleString('en-IN'));
Maths
console.log(Math);
console.log(Math.abs(-4));
console.log(Math.round(4.6));
console.log(Math.ceil(4.2));
console.log(Math.floor(4.9));
console.log(Math.min(4, 3, 6, 8));
console.log(Math.max(4, 3, 6, 8));
console.log(Math.random());
console.log((Math.random()*10) + 1);
console.log(Math.floor(Math.random()*10) + 1);
const min = 10
const max = 20
console.log(Math.floor(Math.random() * (max - min + 1)) + min)
Dates
Date is of object Datatype
let myDate = new Date();
console.log(myDate.toString());
console.log(myDate.toDateString());
console.log(myDate.toLocaleString());
console.log(typeof myDate);
Arrays
Array Methods
- push, pop
- shift, unshift
- includes, indexOf
- join
- slice, splice
- concat
- Array.from() - String to Array
- Array.of()
const marvel_heros = ["thor", "Ironman", "spiderman"]
const dc_heros = ["superman", "flash", "batman"]
const all_new_heros = [...marvel_heros, ...dc_heros]
console.log(all_new_heros);
console.log(Array.from({name: "Mohit"}))
let score1 = 100
let score2 = 200
let score3 = 300
console.log(Array.of(score1, score2, score3));
Objects
const mySym = Symbol("key1")
const JsUser = {
name: "Mohit",
full_name: "Mohit Kholiya",
[mySym]: "mykey1",
age: 20,
lastLoginDays: ["Monday", "Saturday"]
}
console.log(Object.keys(JsUser));
console.log(Object.values(JsUser));
console.log(Object.entries(JsUser));
const obj1 = {1: "a", 2: "b"}
const obj2 = {3: "a", 4: "b"}
const obj3 = {...obj1, ...obj2}
console.log(obj3);
Functions
Syntax
function addTwoNumbers(number1, number2){
return number1 + number2
}
console.log(addone(5))
function addone(num){
return num + 1
}
addTwo(5)
const addTwo = function(num){
return num + 2
}
- addone => Function declarations are hoisted. This means you can call the function before its declaration without any error.
- addTwo => Only the variable declaration is hoisted, not the function assignment. Thus, calling the function before its definition results in an error.
Arrow Functions
const addTwo = (num1, num2) => {
return num1 + num2
}
const addTwo = (num1, num2) => num1 + num2
const addTwo = (num1, num2) => ( num1 + num2 )
Functions that execute immediately after they are defined.
(function chai(){
console.log(`DB CONNECTED`);
})();
( (name) => {
console.log(`DB CONNECTED TO ${name}`);
} )('MongoDb')
Control flow
-
If-Else-Switch
-
We all know the syntax, so lets just skip it.
-
Falsy values
-
false, 0, -0, BigInt 0n, “”, null, undefined, NaN
-
Truthy values
-
“0”, ‘false’, " ", [], {}, function(){}
Nullish Coalescing Operator (??)
let val1;
val1 = 5 ?? 10
val1 = null ?? 10
val1 = undefined ?? 15
val1 = null ?? 10 ?? 20
console.log(val1);
Loops - Iterations
For / While Loops
let myArray = ["flash", "batman", "superman"]
for (let index = 0; index < myArray.length; index++) {
const element = myArray[index];
console.log(element);
}
let myArray2 = ['flash', "batman", "superman"]
let arr = 0
while (arr < myArray2.length) {
console.log(`Value is ${myArray2[arr]}`);
arr++;
}
For of Loops
const arr = [1, 2, 3, 4, 5]
for (const num of arr) {
console.log(num);
}
const greetings = "Hello world!"
for (const greet of greetings) {
console.log(`Each char is ${greet}`)
}
Maps
const map = new Map()
map.set('IN', "India")
map.set('USA', "United States of America")
for (const [key, value] of map) {
console.log(key, ':-', value);
}
const myObject = {
game1: 'NFS',
game2: 'Spiderman'
}
for (const [key, value] of myObject) {
console.log(key, ':-', value);
}
For in and For Each Loop
const programming = ["js", "rb", "py", "java", "cpp"]
for (const key in programming) {
console.log(programming[key]);
}
const coding = ["js", "ruby", "java", "python", "cpp"]
coding.forEach( (item) => {
console.log(item);
} )
coding.forEach( (item, index, arr)=> {
console.log(item, index, arr);
} )
Filter And Reduce
const myNums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const newNums = myNums.filter( (num) => {
return num > 4
} )
console.log(newNums);
const myNums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const myTotal = myNums.reduce( (acc, curr) => acc+curr, 0);
console.log(myTotal);
DOM - Document Object Model
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as a tree of nodes, where each node corresponds to a part of the document (such as an element, attribute, or text).
const parent = document.querySelector('.parent')
console.log(parent);
console.log(parent.children);
console.log(parent.children[1].innerHTML);
parent.children[1].style.color = "orange";
Append
const div = document.createElement('div')
div.className = "main"
div.style.backgroundColor = "cyan"
div.style.color = "black"
const addText = document.createTextNode("Hello , I am Mohit")
div.appendChild(addText)
document.body.appendChild(div)
Add - Edit - Remove
function addLanguage(langName){
const li = document.createElement('li');
li.innerHTML = `${langName}`
document.querySelector('.language').appendChild(li)
}
addLanguage("python")
addLanguage("typescript")
const secondLang = document.querySelector("li:nth-child(2)")
const newli = document.createElement('li')
newli.textContent = "Mojo"
secondLang.replaceWith(newli)
const firstLang = document.querySelector("li:first-child")
firstLang.outerHTML = '<li>TypeScript</li>'
const lastLang = document.querySelector('li:last-child')
lastLang.remove()
Events
document.getElementById('owl').onclick = function(){
alert("owl clicked")
}
- type, timestamp, defaultPrevented
- target, toElement, srcElement, currentTarget,
- clientX, clientY, screenX, screenY
- altkey, ctrlkey, shiftkey, keyCode
document.getElementById('images').addEventListener('click', function(e){
console.log("clicked inside the ul");
}, false)
document.getElementById('owl').addEventListener('click', function(e){
console.log("owl clicked");
e.stopPropagation()
}, false)
document.getElementById('google').addEventListener('click',function(e){
e.preventDefault();
e.stopPropagation()
console.log("google clicked");
}, false)
SetTimeout and ClearTimeout
const changeMe = setTimeout(changeText, 2000)
document.querySelector('#stop').addEventListener('click', function(){
clearTimeout(changeMe)
console.log("STOPPED")
})
SetInterval and ClearInterval
const intervalId = setInterval(sayDate, 1000, "hi")
clearInterval(intervalId)
Api Requests
The readyState property of the XMLHttpRequest object holds the status of the XMLHttpRequest. It can have one of five values:
- UNSENT => Client has been created. open() not called yet.
- OPENED => open() has been called.
- HEADERS_RECEIVED => send() has been called, and headers and status are available.
- LOADING Downloading => responseText holds partial data.
- DONE => The operation is complete.
const requestUrl = 'https://api.github.com/users/Mohit-Alive'
const xhr = new XMLHttpRequest();
xhr.open('GET', requestUrl)
xhr.onreadystatechange = function(){
console.log(xhr.readyState);
if (xhr.readyState === 4) {
const data = JSON.parse(this.responseText)
console.log(typeof data);
console.log(data.followers);
}
}
xhr.send();
Promises
const promiseFive = new Promise(function(resolve, reject){
setTimeout(function(){
let error = true
if (!error) {
resolve({username: "javascript", password: "123"})
} else {
reject('ERROR: JS went wrong')
}
}, 1000)
});
promiseFour
.then((user) => {
console.log(user);
return user.username
}).then((username) => {
console.log(username);
}).catch(function(error){
console.log(error);
}).finally(() => console.log("The promise is either resolved or rejected"))
async function consumePromiseFive(){
try {
const response = await promiseFive
console.log(response);
} catch (error) {
console.log(error);
}
}
Fetch Requests
async function getAllUsers(){
try {
const response = await fetch('https://api.github.com/users/Mohit-Alive')
const data = await response.json()
console.log(data);
} catch (error) {
console.log("E: ", error);
}
}
getAllUsers()
fetch('https://api.github.com/users/Mohit-Alive')
.then((response) => {
return response.json()
})
.then((data) => {
console.log(data);
})
.catch((error) => console.log(error))
评论