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

Javascript Notes

Uploaded by

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

Javascript Notes

Uploaded by

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

/*

console.log("Dheeraj");
console.log('Naik');
age = 24;
console.log(age);
price = 99.99;
variable = null;
console.log(variable)
y = undefined;
console.log(y)
trueFalse = true;
console.log(trueFalse)
*/

/*
Can store anything number(int), boolean value, string, float etc
unlike other code language which need to define wheather it is number,
boolean and string or another variable type
*/

/*
firstLast = 25;
firstLast = "will change",
console.log(firstLast)
*/

//Display the latest value and even we can update


// "=" assignment operator, "==" if two variable has equal value, "===" if both has
equal value and same type

// let a = 5;
// let b = "5";
// let c = 5;

// console.log(a == b); //true


// console.log(a === c); //true

// This will print true because a is a number and b has the same value but
different in type,but in case of === it will become false as type are different
// This will print true because a and c are both numbers and both has same value

//Variable name
//1.apple and Apple are treated different
//2. Only digits,letters,underscore,$ is allowed....space is also not allowed
//3. Only a letter,underscore(_) or $ should be the first character
//4. Reserved words cannot be variable name like:
console,extends,fale,finally,for,function,if,import,in,instanceof,new,null,return,s
uper,switch,this,throw,true,try,typeof,var ....and many more

/*
fullName = "check";
console.log(fullName)

$hello = "correct";
console.log($hello)

_good = "better";
console.log(_good)
now_123 = "number";
console.log(now_123)
*/

// fullName(Camel case) ......most preferred case


// fullname(not used)
// full_name(snake case)
// full-name(kebab case)
// FullName(Pascal case)

// keyword let,const and var

/*
var price = 256;
var price = 33;
console.log(price)
*/

//used before 2015 because value use to redeclare

/*
let age = 25;
age = 55;
console.log(age)
*/
//we can update it but cannot redeclare it, which is good

/*
let value;
console.log(value); // undefined
*/

/*
let empty = null;
console.log(empty);//null
*/

//BigInt
// case 1 :
/*
let num1 = BigInt(123);
console.log(num);
*/

// cas 2:
/*
let num = BigInt("123");
console.log(num);
*/
// Both case are correct
//JavaScript's Number type has precision limitations (Number.MAX_SAFE_INTEGER is
2^53 - 1).
//example :
/*
let bigNum = BigInt("123456789012345678901234567890");
console.log(bigNum); // 123456789012345678901234567890n
*/

//Symbol
/*
let sym = Symbol("unique");
console.log(sym);
*/
// use case:
/*
const ID = Symbol("id");
const user = { [ID]: 12345 };
console.log(user);
*/
//A Symbol is a unique and immutable primitive value, often used as keys for object
properties to

/*
const name = "Dheeraj"
console.log(name)
*/

//cannot be update and cannot be redeclare

//mostly used let and const


//undefined when value is not given
//always give initializa value to const....not giving initialize value to let is oK
//{} This is a block...mostly used in function

/*
{
let a = "hello"
console.log(a)
}

{
let a = "bye"
console.log(a)
}
*/

//both block are treated different


//Primitive data types (7 types): Number, string, boolean, Undefined, null, BigInt,
symbol
// null variable is actually object but since there is no value or null it is
consider as primitive data types
//SHraddha khapra video (1:01:29 time)-(Undefined,null,BigInt,Symbol)
//Non- primitive data types (objects): Arrays, functons...it is a collection of
values..primitive values collection
//typeof and variable to check the type

/*
const student = {
fullName: "Dheeraj Naik",
age: 20,
cpga: 8.2,
isPass: true,
};

console.log(student.isPass);

student["age"] = student["age"] + 1;
console.log(student["age"]);
student["fullName"] = "Gaurav Sharma";
console.log(student["fullName"]);
*/

//const key value can be update

// practice questions

/*
const penSpec = {
name : "Parker pen",
price : 270,
offer : 5,
rating : 4,
};

console.log(penSpec)

const profile = {
fullName: "Dheeraj Naik",
Post : 24,
followers : 294,
following : 300,
email : "dheerajnaik1908@gmail.com",
about : "Information Technology Engineer",
}

console.log(profile)

console.log(typeof profile["fullName"])

//Type checking of key value

//operations: +,-,*,/
//Arithematic operators
//Unary operators
//Assignment operators
//Comparison operators
//logical operators

//Arithematic operators
// a = 5;
// b = 3;

// console.log("a + b = ",a+b)
// console.log("a - b = ",a-b)
// console.log("a / b = ",a/b)
// console.log("a * b = ", a*b)
// console.log("a%b = ", a%b)
// Modulus % basically remainder
// console.log("a**b = ", a**b)
//exponential

//Unary operator
//++a,a++,--a,a--
// a = 5;
// b =5;
// a++;
// console.log(a)
// //increment basically a++ = a+1, post (a++ value will change on the next print
line) and pre(++a it will change before)
// b--;
// console.log(b)
//decrement basically a-- = a-1, post (a-- value will change on the next print
line) and pre(--a it will change before)

//Assignment Operators
//=,+=,-=,%=,**=,*=
//Example
// let a = 5;
// console.log("a*=4 ", a*= 4)
// and all same

//Comparison operators
// Equal to (==),
// Equal to and Type(===),
// Not equal to(!=),
// Not equal to and type (!==)
// > (greater and less)
// >= (greater than and equal to and less than and equal to)
// < (greater and less)
// <= (greater than and equal to and less than and equal to)

//logical operators
// &&(AND) both condition should be true
// ||(OR) Either one condition should be true
// !(Not) false to true and true to false

//condition statement: if statement,if-else statement,else-if statement

// let age = 15
// if(age>=18){
// console.log("you are eligible to drive a car");
// }
// if(age<18){
// console.log("you cannot drive a car");
// }

// let mode = "light";


// let color;

// if(mode==="dark-mode")
// {
// color="Black"
// }

// if(mode==="light")
// {
// color="White"
// }

// console.log(color)

// let temperature = "hot";


// let sunStatus;
// if(temperature==="hot")
// {
// sunStatus="Afternoon";
// }
// else
// {
// sunStatus="Night";
// }

// console.log(sunStatus)

// let num = 10;

// if(num%2===0){
// console.log(num,"is even number");
// }
// else
// {
// console.log(num,"is odd number");
// }

// else-if statement
// let num = 100;

// if(num>100){
// console.log("Above 100")
// }
// else if(num<100){
// console.log("Below 100")
// }
// else if(num===100){
// console.log("Value is equal")
// }
// else{
// console.log(num,"is not fitting in any criteria")

// }

//ternary operator (special operator it consist of 3 operands)-> a(condition)?b(if


condition isTrue):c(if condition is False)
// let a = 19;

// let result = a >= 20 ? "adult" : "child";


// console.log(result)

// or another method

// let b = 40;

// b<45 ? console.log("Young") : console.log("Old")//simpler,compact If-else


statement

//MDN Docs to study more about the topic with code and explanation

//Switch statement

// const color="pink";
// switch(color){
// case "Orange":
// console.log("Bravery")
// break;
// case "Green":
// console.log("Nature")
// break;
// case "White":
// console.log("Peace")
// break;
// default:
// console.log("Sorry color is not available")
// }

// Practice question

// let value = prompt("Enter a number")


// console.log(value)

// if(value%5===0){
// console.log(value,"is multiple by 5")
// }
// else
// {
// console.log(value,"is not multiple by 5")
// }

// let score = 35

// if(score>=90 && score<=100){


// console.log("A")
// }
// else if(score>=70 && score<=89){
// console.log("B")
// }
// else if(score>=60 && score<=69){
// console.log("C")
// }
// else if(score>=50 && score<=59){
// console.log("D")
// }
// else if(score>=0 && score<=49){
// console.log("F")
// }

// loops and string

//loops: for loop, infinite loop, while loop, do while loop, for-of loop, for-in
loop

//initialize statement;stopping condition statement;updation statement


// for(let i=1;i<=5;i++){
// console.log("Dheeraj")
// }

// console.log("loop has ended")

//sum of calculator
// let n = 100;
// sum = 0;
// for(i=1;i<=n;i++){
// sum += i;
// }

// console.log(sum,"is the sum of all values")


// console.log("loop has eneded")

//just printing

// for(i=0; i <= 5; i++){


// console.log("i =",i)
// }

//Infinite loop (takes too much memory...website can crash)


// for(i = 0; i >= 0; i++){
// console.log("i =",i)
// }

//while loop
// let a = 15;
// while(a<=20){
// console.log(a)
// a++;
// }

//Do while loop: It will run atleast one time


// let i = 1;
// do{
// console.log(i);
// i++;
// }while(i<=12);

//for-of loop: used for strings and arrays


// let b = "hello"
// let length=0;
// for(let i of b){
// console.log("i = ", i)
// length++;
// }

// console.log("Length of string = ",length)

//for-in loop: used for objects and arrayss

// let student = {
// Name: "Dheeraj Naik",
// Age: 20,
// Location: "Mumbai",
// Country: "India",
// };

// for(let i in student){
// console.log("Key = ", i,",", "Value = ", student[i])
// }

//Practice question even numbers from 0 to 100


// for(let i =0; i<=100; i++){
// if(i%2===0){
// console.log("i = ",i)
// }
// }

//practice question ,start with random until correct number is guessed

// let guess = prompt("Please Enter a number");


// while(guess!=25){
// guess = prompt("Please try again!");
// }
// console.log("The guess was correct")

//Strings
// let str = "ok";
// console.log(str.length)//predefined
// console.log(str[1])//predefined

//template literals
//Data can be displayed in a form of string using ${} and
backticks(``),placeholders${}or string interpolation

// let obj = {
// location: "Mumbai",
// State: "Maharashtra",
// Pin: 400092,
// }
// let specialString = `${obj.location} is in ${obj.State} and the pin no. is $
{obj.Pin}`
// console.log(specialString)

//also

// let specialString =`Total of 5 plus 5 is ${5+5}`;


// console.log(specialString)

//escape characters next line(/n) and tab space (/t)


// console.log("Myself\nDheeraj Naik \t from Borivali")

//imp \n consider as 1 in a string length


// let str2 = "okk\nbye"; console.log(str2.length)

//string functions/methods:
//
toUpperCase(),toLowerCase(),trim(),slice(),concat(),replace(),replaceAll(),charAt()
// let str = "something"
// console.log(str.toUpperCase())

//or

// let str1 = "SOMETHING";


// let str2 = str1.toLowerCase();
// console.log("Before: ",str1)
// console.log("After: ",str2)

//trim() removes starting and final spacing

// let str3 = " Start and Final ";


// console.log(str3.trim())
// let num = "0123456789";
// let value = "helloworldhelloworld";

// console.log(num.slice(0,5))
// console.log(num.concat(value))
// console.log(value.replace("world","bye"));//replace only one time
// console.log(value.replaceAll("world","bye"));//replace all similar value
// console.log(value.charAt(5));

// let str1 = prompt("Please enter your first name")


// let str2 = str1.length;
// let str3 = "@";

// console.log(str3 + str1.toLowerCase() + str2)


//toLowerCase()..addition

//Arrays: Collection of items and all types. Array is a object


// let God = ["Ganpati","Hanuman","Ram","Vishnu","Narayan","Shankar"];
// console.log(God[1]);
// console.log(God.length);
// God[1] = "Laxmi";
// console.log(God);

//strings are immutable and arrays are mutable

// arrays in loop
// for(i=0; i<God.length; i++){
// console.log(God[i]);
// }

//for of loop
// for(let i of God){
// console.log(i);
// }

// Practice question: marks of students and have to find the average from them

// let marks = [85, 97, 44, 37, 76, 60];


// let sum = 0;

// for(let i of marks){
// sum += i;
// }

// let avg = sum/marks.length;


// console.log(`So the average marks are ${avg}`)

//Practice question: 5 items arae give apply 10% offer on them and print them

//for of
// let itm = [250,645,300,900,50];
// let i = 0;

// for(let val of itm){


// let offer = val/10;
// itm[i] = itm[i] - offer;
// console.log(itm[i])
// i++;
// }

//Now in for loop


// let itm = [250,645,300,900,50];

// for(let i=0; i<itm.length; i++){


// let offer = itm[i]/10;
// itm[i] -= offer;
// }
// console.log(itm);

// Array methods: push(),pop(),toString(),Concat(),unshift()(like push),shift()


(like pop),slice(),splice()

// let vege = ["tomato","Bringal","Cabbage"]


// vege.push("jam","ketchup")
// console.log(vege);
//item added on last

// let vege = ["tomato","Bringal","Cabbage"]


// vege.pop()
// console.log(vege);
//item deleted from last

// let vege = ["tomato","Bringal","Cabbage"]


// console.log(vege.toString());

// let arr1 = [1,2,3,4,5,6,7,8,9,10];


// let arr2 = [11,12,13,14,15,16,17,18,19,20];
// let arr3 = ["hello", "bye", "good", "bad","sad"];
// let join = arr1.concat(arr2,arr3);
// console.log(join);

// let vege = ["tomato","cabbage", "Cucumber" ]


// vege.unshift("orange");
// console.log(vege)

// let vege = ["tomato","cabbage", "Cucumber" ]


// vege.shift();
// console.log(vege)

// let God = ["Ganpati","Hanuman","Ram","Vishnu","Narayan","Shankar"];


// console.log(God.slice(1,4));

// let God = ["Ganpati","Hanuman","Ram","Vishnu","Narayan","Shankar"];


// God.splice(1,3,1000,1005,100006);
// console.log(God);
//slice(startindx,delcount.newelement)

// let God = ["Ganpati","Hanuman","Ram","Vishnu","Narayan","Shankar"];


// God.splice(3);
// console.log(God)

// Practice question :
//a. remove first company from the array,
// b.Remove Uber and Add Ola in its place and
// c.Add Amazon at the end

// let companies = ["bloomberg","Microsoft","Uber","Google","IBM","Netflix"];


// companies.splice(0,1)
//or shift()
// console.log(companies);
// companies.splice(1,1,"Ola");
// console.log(companies);
// companies.push("Amazon")
// console.log(companies);

//Functions: Perform a block of code, can be invoked whenever needed .types:arrow


function,forEach loop(Array method), Map function (array method) similar to
forEach,Filter function (array method),reduce function (array method)->to return
single value
//function: reduces redundancy -> repeat

//parameter in function
// function myFunction(x){
// console.log(x);
// }
// myFunction("hello");
//argument in function call

// function adding(a, b){


// console.log(a*b);
// }
// adding(2, 3)

//function parameter -> like local variables of function -> block scope
// function subTraction(a, b){
// s = a - b;
// return s;
// }
// let val = subTraction(3, 2);
// console.log(val);

//Arrow function: compact way of writing a function


// const arrowMulti = (a, b)=>{
// console.log(a*b)
// }
// arrowMulti(4, 3);

//or

// const arrowMulti = (a, b)=>{


// return a*b;
// }
// const val = arrowMulti(4, 3);
// console.log(val);

// function myf(){
// console.log("hello");
// }
// myf();

// Practice question: take a string as a argument and return vowels in it.

// function myf(vowels){
// let count = 0;
// for(let v of vowels){
// if(v==="a"||v==="e"||v==="i"||v==="o"||v==="u"){
// count++;
// }
// }
// console.log(count)
// }
// myf("helloo")

//with arrow function


// let arrowf = (str) => {
// let count = 0;
// for(let i of str){
// if(i === "a"||i === "e"||i === "i"||i === "o"||i === "u")
// {
// count++;
// }
// }
// console.log(count);
// }

// arrowf("hellooo")

// Interview: Higher Order function/methods? : forEach(CallBackFunction),higher


order function take another function as parameter or return another function as
there output.

// Q. why it is called callbackfunction?


// Ans. A callback function is called so because it is a function that is "called
back" by another function after a specific event or operation is completed.
// Instead of calling the function directly, you pass it as an argument to another
function,
// and that other function decides when and how to execute it.

// Practice question: squaring the array value


// let arr = [1,2,3,4,5];
// let arr2 = arr.forEach((val)=>{
// console.log(val**2);
// })

//map function
// let arr = [1,2,3,4,5,6,7]

// let arr2 = arr.map((val)=>{


// return val**2;
// })

// console.log("Before: ",arr);
// console.log("After: ",arr2)

//filter function
// eg: all even numbers
// let num = [1,2,3,4,5,6,7,8,9,10];
// let num2 = num.filter((val)=>{
// return val%2===0;
// })
// console.log(num2);

//reduce method:
// let arr = [1,2,3,4,5];
// let arr2 = arr.reduce((prev,curr)=>{
// return prev > curr? prev:curr;
// })
// console.log(arr2);

//Practice question: student that scored marks 90,


// let marks = [80,90,70,89,95,96,97,98,78,56];

// let ninty = marks.filter((val)=>{


// return val>90;
// })
// console.log(ninty);

//Practice question: take n as input , which will become number of values from 1 to
n,then by using reduce method remove the sum of values and also use reduce method
to remove the multiplication value of the array numbers.
// let n = prompt("Enter the number");
// let arr = [];
// for(let i=1; i<=n; i++){
// arr[i-1] = i;
// }
// console.log(arr);

// let sum = arr.reduce((prev, curr)=>{


// return prev+curr;
// })

// console.log("Sum of all array values",sum);

// let multi = arr.reduce((prev,curr)=>{


// return prev*curr;
// })

// console.log("Multiplication of all array values ",multi);

//DOM 1
//interview: what is window object: Is a browser object and it is automayically
created by browser,the window object represents an open window in a browser
//interview: why javascript is used in HTML for web development to make dynamic
changes in website.
//console.log()-> to print anything
//console.dir(window.document)= gives all properties and method to print
// console.log(document.window);
// console.dir(document.body);
// console.dir(document);
// DOM Manipulation:
document.getElementById(),document.getElementsByClassName(),document.getElementsByT
agName(),document.querySelector("myid/myclass/
tag"),document.querySelectorAll("myid/myclass/tag")
//properties: tagName: returns tag for element nodes,
// innerText: returns the text content of the element and all its
children(descendent),also remember: Parent->Children->Siblings
// innerHTML:returns the plain text or HTML contents in the element,
// textContent(Even visbility is hidden with textContent we can see the
text):returns textual content even for hidden elements,
//study: firstChild node,lastChild node,child node,
(text,element,comment)node,nodeName,nodeType,nodeValue,childNodes
//Shradha khapra javascript(16:15:04)
// const head = document.getElementById("header");
// console.dir(head);
//for id

// const classes = document.getElementsByClassName("division");


// console.dir(classes);
// console.log(classes);
//for class
//It is a HTML collection -> very similar to an array..it consist of length, index
etc.

// const para = document.getElementsByTagName("p");


// console.log(para);
// console.dir(para);
//for tag

// const ele1 = document.querySelector("p");


// console.dir(ele1);
//first tag

// const eleAll = document.querySelectorAll("p");


// console.dir(eleAll);
//all tags
//querySelector() are nodelist and to mention about class use ".myclass" and for id
use #myid"

// console.log(head.tagName);
// console.log(head.innerHTML);
// console.log(head.innerText);
// console.log(head.textContent);

// let tryl = document.querySelector("#test");


// let try2 = tryl.firstChild;
// console.log(try2);
//firstChild

// let tryl = document.querySelector("#test");


// let try2 = tryl.lastChild;
// console.log(try2);
//lastChild

// let tryl = document.querySelector("#test");


// let try2 = tryl.children;
// console.log(try2);
//children

// let tryl = document.querySelector("#test");


// let try2 = tryl.TEXT_NODE;
// console.log(try2);
//TEXT_NODE(numeric value 3)

// let tryl = document.querySelector("#test");


// let try2 = tryl.ELEMENT_NODE;
// console.log(try2);
//Element_NODE(numeric value 1)

// let tryl = document.querySelector("#test");


// let try2 = tryl.COMMENT_NODE;
// console.log(try2);
// COMMENT_NODE(numeric value 8)

// let tryl = document.querySelector("#test");


// let try2 = tryl.childNodes;
// console.log(try2);
// mentioned above

// let x = document.querySelector(".fruit");
// let y = x.innerText;
// console.log(y);
//innerText..we can also change the value in console

// let x = document.querySelector(".fruit");
// let y = x.innerText;
// console.log(y);
//innerHTML..we can change the value in console and tags also

// let x = document.querySelector("#header");
// let y = x.textContent;
// console.log(y);
//(Even visbility is hidden with textContent we can see the text)

//practice question : creating h1 with some text and then adding a text to it
// let x = document.querySelector("h2");
// let y = x.innerText + " Bye Javascript";
// console.log(y);

//practice question: creating 3 divs of sam class name and adding unique text to
each
// let x = document.querySelectorAll(".box");
// x[0].innerText="hello";
// x[1].innerText="bye";
// x[2].innerText="stop";

//or
// let x = document.querySelectorAll(".box");
// idx=1;
// for(let div of x){
// div.innerText=`division ${idx}`;
// idx++;
// }

//DOM 2
//DOM Maipulation:
//getAttribute(attr)->get the attribute value
//setAttribute(attr,value)->to set the attribute val th
//style: node.style
//Insert Element: node.append(el): adds at the end of nde (inside)
// node.prepend(el): adds at the start of node (inside)
// node.before(el): adds before the node (outside)
// node.after(el): adds after the node (outside)
// Delete Element:node.remove(): removes the node
//claasList.add or remove and many thing(adds attribute of two classes..we can also
do classList.remove and many things)
//addEventListener
//removeEventListener

// let x = document.querySelector("h1");
// console.log(x);
// let value = x.getAttribute("id");
// console.log(value);
//getattribute

// let x = document.querySelector("#header");
// let y = x.setAttribute("id","newName")
// console.log(y);
//setattribute ...check in inspector HTML code

// let xyz = document.querySelector("h2");


// xyz.style.color="white";
// xyz.style.backgroundColor="purple";
// xyz.style.fontSize="50px";
// xyz.innerText="Changed by Javascript";
//node.style

// let btn = document.createElement("button");


// btn.innerText="click here";
// btn.style.backgroundColor="brown";
// btn.style.color="white";
// btn.style.fontSize="30px";
// console.log(btn)
// let b = document.querySelector("div")
// b.append(btn);
//adds at the end of the node

// let btn = document.createElement("button");


// btn.innerText="click here";
// btn.style.backgroundColor="brown";
// btn.style.color="white";
// btn.style.fontSize="30px";
// console.log(btn)
// let b = document.querySelector("div")
// b.prepend(btn);
//adds at the start of node

// let header = document.createElement("h1");


// header.innerText="Adding header text before div";
// header.style.backgroundColor="brown";
// header.style.color="white";
// header.style.fontSize="30px";
// console.log(header)
// let b = document.querySelector("div")
// b.before(header);

// let header = document.createElement("h1");


// header.innerText="Adding header text After div";
// header.style.backgroundColor="brown";
// header.style.color="white";
// header.style.fontSize="30px";
// console.log(header)
// let b = document.querySelector("div")
// b.after(header);

// let g = document.createElement("h1");
// g.innerHTML="<i>Hello people I was added!</i>";
// document.querySelector("body").prepend(g);
// //To add tag any tag in body
// let para = document.querySelector("p");
// para.remove();
//node.remove(), to remove any tag

//study: appendChild and removechild

// let r = document.createElement("h1");
// r.innerText="checking append child";
// document.querySelector("div").appendChild(r);
//appendChild...to append node in parent node at the bottom.

// let para = document.querySelector("p");


// document.querySelector("div").removeChild(para);
//removechild....to remove node from parent node.

//practice question: Create a new button element. Give it a text "click me",
background color of red & text color of white.
// Insert the button as the first element inside the body tag.

// let newBtn = document.createElement("Button");


// newBtn.innerText="click me";
// newBtn.style.color="white";
// newBtn.style.backgroundColor="red";
// document.querySelector("body").appendChild(newBtn);

// practice question: Create a <p> tag in html, give it a class & some styling.
// Now create a new class in CSS and try to append this class to the <p> el Did you
notice,
// how you overwrite the class name when you add a new Solve this problem using
classList.

// let para = document.querySelector("p");


// para.classList.add("newClass")
// //classList.add...adds attribute of two classes..we can also do classList.remove
and many things.

//Events
//onlick event: triggers when clicked
//ondblclick: triggers when clicked 2 times
//onmouseover
//In-line event handling when added into the tag of html file
//for Javascript ....javascript file code is prioritize over In line code of
javascript in tag
//In js file if any event handler for a tag is defined than the event which is
defined last with that tag is applied to that tag

// let btn1 = document.querySelector("#btn");


// btn1.onclick = (evt)=>{
// console.log('Mouse was clicked');
// let a = 25;
// a++;
// console.log(a);
// console.log(evt.type);
// console.log(evt.clientX);
// console.log(evt.clientY);
// }

// btn.addEventListener("click",()=>{
// console.log("Button was clicked");
// })
//addEventlister(Event,callback)

// btn1.addEventListener("click",()=>{
// console.log("handler 1");
// })
//addeventListener(Event,callback)

// handler2 = () => {
// console.log("handler2")
// }
// btn1.addEventListener("click",handler2);
// btn1.removeEventListener("click",handler2);
//addEventListener(Event,callback) and removeEventlistener(Event,callback)

// let btn1 = document.querySelector("#btn");


// btn.onclick =()=>{
// console.log('Hello')
// }
//onclick

// let btn1 = document.querySelector("#btn");


// btn.ondblclick =()=>{
// console.log('Hello')
// }
// ondblclick

// let btn1 = document.querySelector("#btn");


// btn.ondblclick =()=>{
// console.log('Hello')
// }

// let divi = document.querySelector(".division");


// divi.onmouseover=(e)=>{
// console.log("Hello and Bye");
// divi.style.backgroundColor="black";
// divi.borderRadius="2px solid green"
// }
// onmouseover

// let divio = document.querySelector(".division");


// divio.onmouseout=()=>{
// divio.style.backgroundColor="blueviolet";
// }
// onmouseout

// let divi = document.querySelector(".division");


// divi.addEventListener("mouseover",()=>{
// divi.style.backgroundColor="red";
// })
// let divio = document.querySelector(".division");
// divio.addEventListener("mouseout",()=>{
// divio.style.backgroundColor="blueviolet";
// })
// addEventListener

// let divi = document.querySelector(".division");


// divi.addEventListener("click",()=>{
// console.log("Sentence1")
// })

// divi.addEventListener("click",()=>{
// console.log("Sentence2")
// })

// divi.addEventListener("click",()=>{
// console.log("Sentence3")
// })

// exception = ()=>{
// console.log("Sentence4")
// }
// divi.addEventListener("click",exception)
// divi.removeEventListener("click", exception)

// practive question: Create a toggle button that changes


//the screen to dark-mode when clicked & light-mode when clicked again.

// let mB = document.querySelector("#mode");
// let cM = "light";
// //or// let body = document.querySelector("body");

// mB.addEventListener("click",()=>{
// if(cM==="light"){
// cM = "dark";
// document.querySelector("body").style.backgroundColor="black";
// document.querySelector("#mode").style.backgroundColor="aqua";
// document.querySelector("body").style.color="Black";
// //or body.classList.add("light")//need to mention in css..in.light or dark
// //also can do body.classList.remove("light")//need to mention in
css..in.light or dark
// }else{
// cM = "light";
// document.querySelector("body").style.backgroundColor="white";
// document.querySelector("#mode").style.backgroundColor="white";
// document.querySelector("#mode").style.color="black";
// //or body.classList.add("light")//need to mention in css..in.light or dark
// //also can do body.classList.remove("light")//need to mention in
css..in.light or dark

// }
// console.log(cM);
// });

//Classes and Objects

//Prototype in javascript
//prototype(Type: it is an reference to an object ,
// throgh which we can access an object by using address): It is a special
property,
// it consist of properties and method.

// const student = {
// name: "Dheeraj",
// marks: 95,
// printMarks: function() {
// console.log("my marks =", this.marks);
// }
// };

// console.log(student)

// const num = {
// student(){
// console.log("100 students");
// }
// }
//defining function inside object
//or other way
// const num = {
// student: function(){
// console.log("100 students");
// }
// }

// const num = {
// student(){
// console.log("100 students");
// }
// }
// const num2 = {
// student2(){
// console.log("200 students");
// }
// }
// const num3 = {
// student3(){
// console.log("300 students");
// }
// }
// const num4 = {
// student4(){
// console.log("400 students");
// }
// }
// const num5 = {
// student5(){
// console.log("500 students");
// }
// }

// num2.__proto__=num;
// num3.__proto__=num;
// num4.__proto__=num;
// num5.__proto__=num;
//Using other object properties in other object properties using prototype
//if two object has same name function then the function within the object will be
called(closes and nearest win)

//Classes
// class is a program-code template fpr creating objects,
// it will have some state (variables) & some behaviour (functions) inside it.
//blueprint
//Code:
//class myClass{
//constructor(){...}; //It is a special method,it is reserved keyword,it
automatically invoked by new,it initializes object
//myMethod(){...}
// }
//let myObj = new myClass();

// class carCs{
// start(){
// console.log("start the car")
// }
// stop(){
// console.log("stop the car")
// }
// }

// let carName = new carCs();

// class bus{
// start(){
// console.log("Start the bus");
// }
// stop(){
// console.log("stop the bus")
// }
// setBrand(brand){
// this.brandName = brand;
// }
// }

// const busName = new bus();


// busName.setBrand("force");
//how to define a varibale in a class

// class bus{
// constructor(brand, distance){
// console.log("printing text with the help of constructor");
// this.brandName = brand;
// this.dist = distance;
// }
// start(){
// console.log("Start the bus");
// }
// stop(){
// console.log("stop the bus")
// }
// // setBrand(brand){
// // this.brandName = brand;
// // }
// }

// const busName = new bus("force", 10);//constructor


// console.log(busName);
// const carName = new bus("Volvo", 20)//constructor
// console.log(carName);
//Using constructor

//Inheritance
// inheritance is passing down properties & methods from parent class to child
class
// code:
// class parent{...
// ...}
// class Child extends Parent{...
// ...}
// If child & Parent have same method, child's method will be used(Method
Overriding)
//we uses function for properties and method in class and inheritance to reduce
complexity and easy programming.

// class father{
// constructor(name,color,Dpt,Dpt2){
// this.naming = name;
// this.fav = color;
// this.words = "word";
// this.branch = Dpt;
// this.branch2 = Dpt2;
// }
// fatherSpeak(){
// console.log("Hello son");
// }
// }
// class son extends father{
// constructor(Dpt,Dpt2){
// super(Dpt,Dpt2);
// this.engineer = Dpt;
// this.engineer2 = Dpt2;
// }
// sonSpeak(){
// console.log("Hi father");
// }
// }
// let talks = new father("Rahul","blue","IT Engineer","CS Engineer");
// let talk = new son();//to call function from class son...for example in this
sonSpeak(){..}
//Use of function and constructor ,and inheriting the properties and method using
Inheritance

// practice question: Qs. You are creating a website for your college. Create a
class User with 2 properties, name & email. It also has a method called viewData()
that allows user to view website data.
//both are connected question above and below
//practice question: s. Create a new class called Admin which inherits from User.
Add a new method called editData to Admin that allows it to edit website data.

// solution code:
// let Data = "Secret Info"
// class User{
// constructor(name,email){
// this.psName = name;
// this.psEmail = email;
// }
// viewData(){
// console.log("Website content", Data);
// }
// }
// class Admin extends User{
// constructor(name,email){
// super(name,email);
// }
// editData(){
// Data = "New Info added sucessfully";
// }
// }

// let userObj = new User("Ramesh","ramesh@email.com");


// let userObj2 = new User("Suresh","suresh@email.com");
// let userObj3 = new User("Jayesh","jayesh@email.com");
// let admin = new Admin("Admin", "admin@email.com");

//Error Handling

//try-catch code:
// try {
// normal code
// } catch (err) { //err is error object HP
// handling error
// }

// a = 5;
// b = 5;
// c = 6;
// console.log(a+b);
// try{
// console.log(a+g);
// }
// catch(err){
// console.log(err);
// }
// console.log(a+c);
// console.log(a+b+c);
//error handling

//callback
// async wait >> promise chains >> callback hell
// synchronous and asybchronous programming

// function bye(){
// console.log("bye")
// }
// setTimeout(bye, 4000)//timeout function , 4s = 4000ms

//or it also works like this


// setTimeout(
// ()=>{
// console.log("Using setTimeout function to display this");
// }, 5000
// )
//example of setTimeout()

// console.log("one");
// console.log("two");
// console.log("three");
// console.log("four");
//synchronous example

//asynchronous example
// console.log("one");
// console.log("two");
// setTimeout(
// ()=>{
// console.log("Using setTimeout function to display this");
// }, 5000
// )
// console.log("three");
// console.log("four");

// function sum(a, b){


// console.log(a+b);
// }
// function val(a, b, sumcallback){
// sumcallback(a, b);
// }
// val(3, 5, sum)
//synchronous in callback

// const hello = () => {


// console.log("Hello");
// }
// setTimeout(hello, 5000);
//half synchronous and half asynchronous in some callback

//nesting

// let age = 17;

// if(age>=18){
// if(age>=40){
// console.log("Senior")
// }
// else
// {
// console.log("Adult");
// }
// }
// else
// {
// console.log("Child")
// }
//nesting if-else
//nesting for loop also exist

// function data(dataId){
// setTimeout(() => {
// console.log(`just checking the data ${dataId}`);
// }, 4000);
// }
// data(100);
//just practice

// function data(dataId, nextData) {


// setTimeout(() => {
// console.log("Data displayed after 2 seconds:", dataId);
// if (nextData) {
// nextData();
// }
// }, 2000);
// }
// data(1, () => {
// console.log("gatting next data.....")
// data(2, ()=>{
// console.log("gatting next data.....")
// data(3, ()=>{
// console.log("gatting next data.....")
// data(4, ()=>{
// console.log("gatting next data.....")
// data(5, ()=>{
// console.log("gatting next data.....")
// data(6, ()=>{
// console.log("gatting next data.....")
// data(7)
// })
// })
// })
// })
// });
// });
//This type of program with too much nesting is called callback hell
//executing each data after setTimout interval, sequence by sequence with a
specified interval set

//promises
// To resolve callback hell issue we have promises
//code: let promise = new Promise((resolve, reject) => {....})//It has function
with handlers
//resolve(fulfilled) and reject(rejection) are two callback function in javascript
//uses of promise: promise.then((res)=>{..}) and promise.catch((err)=>{..})

// let myPromise = new Promise((resolve,reject)=>{


// console.log("Promise is created");
// reject("Error displayed");
// })

//example
// function data(dataId, nextData) {
// return new Promise((resolve,reject)=>{
// setTimeout(() => {
// console.log("Data displayed after 2 seconds:", dataId);
// resolve("sucess");//or reject("Sucess error")
// if (nextData) {
// nextData();
// }
// }, 5000);
// })
// }
//either resolve is displayed or reject is displayed

// const myPromise = () => {


// return new Promise((resolve,reject)=>{
// console.log("My promise")
// // resolve("problem resolve");
// reject("problem not resolved");
// })
// }

// let confirm = myPromise();


// confirm.then((res) => {
// console.log("problem resolved", res);
// });

// confirm.catch((err) => {
// console.log("issue not resolved", err);
// })
//uses of promise: promise.then((res)=>{..}) and promise.catch((err)=>{..})

// const data = (info) => {


// return new Promise((resolve, reject) => {
// setTimeout(() => {
// console.log("data display", info);
// resolve("success");
// }, 8000);
// });
// };

// const data2 = (info) => {


// return new Promise((resolve, reject) => {
// setTimeout(() => {
// console.log("data display", info);
// resolve("success");
// }, 8000);
// });
// };

// const data3 = (info) => {


// return new Promise((resolve, reject) => {
// setTimeout(() => {
// console.log("data display", info);
// resolve("success");
// }, 8000);
// });
// };

// const data4 = (info) => {


// return new Promise((resolve, reject) => {
// setTimeout(() => {
// console.log("data display", info);
// resolve("success");
// }, 8000);
// });
// };

// const data5 = (info) => {


// return new Promise((resolve, reject) => {
// setTimeout(() => {
// console.log("data display", info);
// resolve("success");
// }, 8000);
// });
// };

// console.log("fetching data 1...");


// data("information 1").then((res) => {
// console.log("fetching data 2...");
// data2("information 2").then((res) => {
// console.log("fetching data 3...");
// data3("information 3").then((res) => {
// console.log("fetching data 4...");
// data4("information 4").then((res) => {
// console.log("fetching data 5...");
// data5("information 5").then((res) => {})
// })
// })
// });
// });
// promise chaining..solving callback hell problem by using this promise chain
method

// async function display(){


// console.log("display my message");
// }
//simple async function

// function api(){
// return new Promise((resolve,reject) => {
// setTimeout(() => {
// console.log("just a display");
// resolve("success")
// }, 4000);
// } )
// }

// async function apis(){


// console.log("fetching data 1....")
// await api();
// console.log("fetching data 2....")
// await api();
// }
//second example with data one after the other

// function data(dataId) {
// return new Promise((resolve,reject)=>{
// setTimeout(() => {
// console.log("Data displayed after 5 seconds:", dataId);
// resolve("sucess");//or reject("Sucess error")
// }, 5000);
// })
// }

// async function datas(){


// console.log("fetching data 1")
// await data(1);
// console.log("fetching data 2")
// await data(2);
// console.log("fetching data 3")
// await data(3);
// }
//with the previous example

// (async function () {
// console.log("fetching data 1")
// await data(1);
// console.log("fetching data 2")
// await data(2);
// console.log("fetching data 3")
// await data(3);
// })();
//IIFE: one time use,we can't make changes and need to code again. It is a function
without name, it

//executes immediately
//Async - await
//await - pauses async function until promise is executed
//Async - await is used or promise(.then() and .catch())are used. any one is used
from from both.
//IIFE: Immediately Invoked Function Expression

//fetch API
// API - Application programming interface
//200 - successful request

// let url = "https://cat-fact.herokuapp.com/facts";

// const getFacts = async () => {


// console.log("Getting data....");
// let response = await fetch(url);
// console.log(response); //printed in JSON (AJAJ) format previously it was
XML(AJAX).
// let data = await response.json();
// console.log(data[3].text);
// };

// let url = "https://cat-fact.herokuapp.com/facts";

// const data = async () => {


// console.log("Fetching data.....")
// let pro2 = await fetch(url);
// console.log(pro2);
// let response = await pro2.json();
// console.log(response[0].text);
// };
//fetch api practice code

// let url = "https://cat-fact.herokuapp.com/facts";


// let display = document.querySelector("#fact")
// let button = document.querySelector("#btn")
// const facts = async() => {
// console.log("Fetching data please wait.....")
// const response = await fetch(url);
// console.log(response);
// const convert = await response.json();
// display.innerHTML = convert[4].text;
// }
// button.addEventListener("click",facts)
// fetch api practice code

//Trying options and post

*/

You might also like