0% found this document useful (0 votes)
211 views29 pages

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)
211 views29 pages

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

/*

[Link]("Dheeraj");
[Link]('Naik');
age = 24;
[Link](age);
price = 99.99;
variable = null;
[Link](variable)
y = undefined;
[Link](y)
trueFalse = true;
[Link](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",
[Link](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;

// [Link](a == b); //true


// [Link](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
//[Link] 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";
[Link](fullName)

$hello = "correct";
[Link]($hello)

_good = "better";
[Link](_good)
now_123 = "number";
[Link](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;
[Link](price)
*/

//used before 2015 because value use to redeclare

/*
let age = 25;
age = 55;
[Link](age)
*/
//we can update it but cannot redeclare it, which is good

/*
let value;
[Link](value); // undefined
*/

/*
let empty = null;
[Link](empty);//null
*/

//BigInt
// case 1 :
/*
let num1 = BigInt(123);
[Link](num);
*/

// cas 2:
/*
let num = BigInt("123");
[Link](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");
[Link](bigNum); // 123456789012345678901234567890n
*/

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

/*
const name = "Dheeraj"
[Link](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"
[Link](a)
}

{
let a = "bye"
[Link](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 ([Link] 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,
};

[Link]([Link]);

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

//const key value can be update

// practice questions

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

[Link](penSpec)

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

[Link](profile)

[Link](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;

// [Link]("a + b = ",a+b)
// [Link]("a - b = ",a-b)
// [Link]("a / b = ",a/b)
// [Link]("a * b = ", a*b)
// [Link]("a%b = ", a%b)
// Modulus % basically remainder
// [Link]("a**b = ", a**b)
//exponential

//Unary operator
//++a,a++,--a,a--
// a = 5;
// b =5;
// a++;
// [Link](a)
// //increment basically a++ = a+1, post (a++ value will change on the next print
line) and pre(++a it will change before)
// b--;
// [Link](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;
// [Link]("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){
// [Link]("you are eligible to drive a car");
// }
// if(age<18){
// [Link]("you cannot drive a car");
// }

// let mode = "light";


// let color;

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

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

// [Link](color)

// let temperature = "hot";


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

// [Link](sunStatus)

// let num = 10;

// if(num%2===0){
// [Link](num,"is even number");
// }
// else
// {
// [Link](num,"is odd number");
// }

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

// if(num>100){
// [Link]("Above 100")
// }
// else if(num<100){
// [Link]("Below 100")
// }
// else if(num===100){
// [Link]("Value is equal")
// }
// else{
// [Link](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";


// [Link](result)

// or another method

// let b = 40;

// b<45 ? [Link]("Young") : [Link]("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":
// [Link]("Bravery")
// break;
// case "Green":
// [Link]("Nature")
// break;
// case "White":
// [Link]("Peace")
// break;
// default:
// [Link]("Sorry color is not available")
// }

// Practice question

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


// [Link](value)

// if(value%5===0){
// [Link](value,"is multiple by 5")
// }
// else
// {
// [Link](value,"is not multiple by 5")
// }

// let score = 35

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


// [Link]("A")
// }
// else if(score>=70 && score<=89){
// [Link]("B")
// }
// else if(score>=60 && score<=69){
// [Link]("C")
// }
// else if(score>=50 && score<=59){
// [Link]("D")
// }
// else if(score>=0 && score<=49){
// [Link]("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++){
// [Link]("Dheeraj")
// }

// [Link]("loop has ended")

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

// [Link](sum,"is the sum of all values")


// [Link]("loop has eneded")

//just printing

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


// [Link]("i =",i)
// }

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


// for(i = 0; i >= 0; i++){
// [Link]("i =",i)
// }

//while loop
// let a = 15;
// while(a<=20){
// [Link](a)
// a++;
// }

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


// let i = 1;
// do{
// [Link](i);
// i++;
// }while(i<=12);

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


// let b = "hello"
// let length=0;
// for(let i of b){
// [Link]("i = ", i)
// length++;
// }

// [Link]("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){
// [Link]("Key = ", i,",", "Value = ", student[i])
// }

//Practice question even numbers from 0 to 100


// for(let i =0; i<=100; i++){
// if(i%2===0){
// [Link]("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!");
// }
// [Link]("The guess was correct")

//Strings
// let str = "ok";
// [Link]([Link])//predefined
// [Link](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 = `${[Link]} is in ${[Link]} and the pin no. is $
{[Link]}`
// [Link](specialString)

//also

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


// [Link](specialString)

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


// [Link]("Myself\nDheeraj Naik \t from Borivali")

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


// let str2 = "okk\nbye"; [Link]([Link])

//string functions/methods:
//
toUpperCase(),toLowerCase(),trim(),slice(),concat(),replace(),replaceAll(),charAt()
// let str = "something"
// [Link]([Link]())

//or

// let str1 = "SOMETHING";


// let str2 = [Link]();
// [Link]("Before: ",str1)
// [Link]("After: ",str2)

//trim() removes starting and final spacing

// let str3 = " Start and Final ";


// [Link]([Link]())
// let num = "0123456789";
// let value = "helloworldhelloworld";

// [Link]([Link](0,5))
// [Link]([Link](value))
// [Link]([Link]("world","bye"));//replace only one time
// [Link]([Link]("world","bye"));//replace all similar value
// [Link]([Link](5));

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


// let str2 = [Link];
// let str3 = "@";

// [Link](str3 + [Link]() + str2)


//toLowerCase()..addition

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


// let God = ["Ganpati","Hanuman","Ram","Vishnu","Narayan","Shankar"];
// [Link](God[1]);
// [Link]([Link]);
// God[1] = "Laxmi";
// [Link](God);

//strings are immutable and arrays are mutable

// arrays in loop
// for(i=0; i<[Link]; i++){
// [Link](God[i]);
// }

//for of loop
// for(let i of God){
// [Link](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/[Link];


// [Link](`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;
// [Link](itm[i])
// i++;
// }

//Now in for loop


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

// for(let i=0; i<[Link]; i++){


// let offer = itm[i]/10;
// itm[i] -= offer;
// }
// [Link](itm);

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


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

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


// [Link]("jam","ketchup")
// [Link](vege);
//item added on last

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


// [Link]()
// [Link](vege);
//item deleted from last

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


// [Link]([Link]());

// 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 = [Link](arr2,arr3);
// [Link](join);

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


// [Link]("orange");
// [Link](vege)

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


// [Link]();
// [Link](vege)

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


// [Link]([Link](1,4));

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


// [Link](1,3,1000,1005,100006);
// [Link](God);
//slice(startindx,[Link])

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


// [Link](3);
// [Link](God)

// Practice question :
//a. remove first company from the array,
// [Link] Uber and Add Ola in its place and
// [Link] Amazon at the end

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


// [Link](0,1)
//or shift()
// [Link](companies);
// [Link](1,1,"Ola");
// [Link](companies);
// [Link]("Amazon")
// [Link](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){
// [Link](x);
// }
// myFunction("hello");
//argument in function call

// function adding(a, b){


// [Link](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);
// [Link](val);

//Arrow function: compact way of writing a function


// const arrowMulti = (a, b)=>{
// [Link](a*b)
// }
// arrowMulti(4, 3);

//or

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


// return a*b;
// }
// const val = arrowMulti(4, 3);
// [Link](val);

// function myf(){
// [Link]("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++;
// }
// }
// [Link](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++;
// }
// }
// [Link](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 = [Link]((val)=>{
// [Link](val**2);
// })

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

// let arr2 = [Link]((val)=>{


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

// [Link]("Before: ",arr);
// [Link]("After: ",arr2)

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

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

//Practice question: student that scored marks 90,


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

// let ninty = [Link]((val)=>{


// return val>90;
// })
// [Link](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;
// }
// [Link](arr);

// let sum = [Link]((prev, curr)=>{


// return prev+curr;
// })

// [Link]("Sum of all array values",sum);

// let multi = [Link]((prev,curr)=>{


// return prev*curr;
// })

// [Link]("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.
//[Link]()-> to print anything
//[Link]([Link])= gives all properties and method to print
// [Link]([Link]);
// [Link]([Link]);
// [Link](document);
// DOM Manipulation:
[Link](),[Link](),[Link]
agName(),[Link]("myid/myclass/
tag"),[Link]("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([Link])
// const head = [Link]("header");
// [Link](head);
//for id

// const classes = [Link]("division");


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

// const para = [Link]("p");


// [Link](para);
// [Link](para);
//for tag

// const ele1 = [Link]("p");


// [Link](ele1);
//first tag

// const eleAll = [Link]("p");


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

// [Link]([Link]);
// [Link]([Link]);
// [Link]([Link]);
// [Link]([Link]);

// let tryl = [Link]("#test");


// let try2 = [Link];
// [Link](try2);
//firstChild

// let tryl = [Link]("#test");


// let try2 = [Link];
// [Link](try2);
//lastChild

// let tryl = [Link]("#test");


// let try2 = [Link];
// [Link](try2);
//children

// let tryl = [Link]("#test");


// let try2 = tryl.TEXT_NODE;
// [Link](try2);
//TEXT_NODE(numeric value 3)

// let tryl = [Link]("#test");


// let try2 = tryl.ELEMENT_NODE;
// [Link](try2);
//Element_NODE(numeric value 1)

// let tryl = [Link]("#test");


// let try2 = tryl.COMMENT_NODE;
// [Link](try2);
// COMMENT_NODE(numeric value 8)

// let tryl = [Link]("#test");


// let try2 = [Link];
// [Link](try2);
// mentioned above

// let x = [Link](".fruit");
// let y = [Link];
// [Link](y);
//innerText..we can also change the value in console

// let x = [Link](".fruit");
// let y = [Link];
// [Link](y);
//innerHTML..we can change the value in console and tags also

// let x = [Link]("#header");
// let y = [Link];
// [Link](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 = [Link]("h2");
// let y = [Link] + " Bye Javascript";
// [Link](y);

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

//or
// let x = [Link](".box");
// idx=1;
// for(let div of x){
// [Link]=`division ${idx}`;
// idx++;
// }

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

// let x = [Link]("h1");
// [Link](x);
// let value = [Link]("id");
// [Link](value);
//getattribute

// let x = [Link]("#header");
// let y = [Link]("id","newName")
// [Link](y);
//setattribute ...check in inspector HTML code

// let xyz = [Link]("h2");


// [Link]="white";
// [Link]="purple";
// [Link]="50px";
// [Link]="Changed by Javascript";
//[Link]

// let btn = [Link]("button");


// [Link]="click here";
// [Link]="brown";
// [Link]="white";
// [Link]="30px";
// [Link](btn)
// let b = [Link]("div")
// [Link](btn);
//adds at the end of the node

// let btn = [Link]("button");


// [Link]="click here";
// [Link]="brown";
// [Link]="white";
// [Link]="30px";
// [Link](btn)
// let b = [Link]("div")
// [Link](btn);
//adds at the start of node

// let header = [Link]("h1");


// [Link]="Adding header text before div";
// [Link]="brown";
// [Link]="white";
// [Link]="30px";
// [Link](header)
// let b = [Link]("div")
// [Link](header);

// let header = [Link]("h1");


// [Link]="Adding header text After div";
// [Link]="brown";
// [Link]="white";
// [Link]="30px";
// [Link](header)
// let b = [Link]("div")
// [Link](header);

// let g = [Link]("h1");
// [Link]="<i>Hello people I was added!</i>";
// [Link]("body").prepend(g);
// //To add tag any tag in body
// let para = [Link]("p");
// [Link]();
//[Link](), to remove any tag

//study: appendChild and removechild

// let r = [Link]("h1");
// [Link]="checking append child";
// [Link]("div").appendChild(r);
//appendChild...to append node in parent node at the bottom.

// let para = [Link]("p");


// [Link]("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 = [Link]("Button");


// [Link]="click me";
// [Link]="white";
// [Link]="red";
// [Link]("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 = [Link]("p");


// [Link]("newClass")
// //[Link]...adds attribute of two classes..we can also do [Link]
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 = [Link]("#btn");


// [Link] = (evt)=>{
// [Link]('Mouse was clicked');
// let a = 25;
// a++;
// [Link](a);
// [Link]([Link]);
// [Link]([Link]);
// [Link]([Link]);
// }

// [Link]("click",()=>{
// [Link]("Button was clicked");
// })
//addEventlister(Event,callback)

// [Link]("click",()=>{
// [Link]("handler 1");
// })
//addeventListener(Event,callback)

// handler2 = () => {
// [Link]("handler2")
// }
// [Link]("click",handler2);
// [Link]("click",handler2);
//addEventListener(Event,callback) and removeEventlistener(Event,callback)

// let btn1 = [Link]("#btn");


// [Link] =()=>{
// [Link]('Hello')
// }
//onclick

// let btn1 = [Link]("#btn");


// [Link] =()=>{
// [Link]('Hello')
// }
// ondblclick

// let btn1 = [Link]("#btn");


// [Link] =()=>{
// [Link]('Hello')
// }

// let divi = [Link](".division");


// [Link]=(e)=>{
// [Link]("Hello and Bye");
// [Link]="black";
// [Link]="2px solid green"
// }
// onmouseover

// let divio = [Link](".division");


// [Link]=()=>{
// [Link]="blueviolet";
// }
// onmouseout

// let divi = [Link](".division");


// [Link]("mouseover",()=>{
// [Link]="red";
// })
// let divio = [Link](".division");
// [Link]("mouseout",()=>{
// [Link]="blueviolet";
// })
// addEventListener

// let divi = [Link](".division");


// [Link]("click",()=>{
// [Link]("Sentence1")
// })

// [Link]("click",()=>{
// [Link]("Sentence2")
// })

// [Link]("click",()=>{
// [Link]("Sentence3")
// })

// exception = ()=>{
// [Link]("Sentence4")
// }
// [Link]("click",exception)
// [Link]("click", exception)

// practive question: Create a toggle button that changes


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

// let mB = [Link]("#mode");
// let cM = "light";
// //or// let body = [Link]("body");

// [Link]("click",()=>{
// if(cM==="light"){
// cM = "dark";
// [Link]("body").[Link]="black";
// [Link]("#mode").[Link]="aqua";
// [Link]("body").[Link]="Black";
// //or [Link]("light")//need to mention in css..[Link] or dark
// //also can do [Link]("light")//need to mention in
css..[Link] or dark
// }else{
// cM = "light";
// [Link]("body").[Link]="white";
// [Link]("#mode").[Link]="white";
// [Link]("#mode").[Link]="black";
// //or [Link]("light")//need to mention in css..[Link] or dark
// //also can do [Link]("light")//need to mention in
css..[Link] or dark

// }
// [Link](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() {
// [Link]("my marks =", [Link]);
// }
// };

// [Link](student)

// const num = {
// student(){
// [Link]("100 students");
// }
// }
//defining function inside object
//or other way
// const num = {
// student: function(){
// [Link]("100 students");
// }
// }

// const num = {
// student(){
// [Link]("100 students");
// }
// }
// const num2 = {
// student2(){
// [Link]("200 students");
// }
// }
// const num3 = {
// student3(){
// [Link]("300 students");
// }
// }
// const num4 = {
// student4(){
// [Link]("400 students");
// }
// }
// const num5 = {
// student5(){
// [Link]("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(){
// [Link]("start the car")
// }
// stop(){
// [Link]("stop the car")
// }
// }

// let carName = new carCs();

// class bus{
// start(){
// [Link]("Start the bus");
// }
// stop(){
// [Link]("stop the bus")
// }
// setBrand(brand){
// [Link] = brand;
// }
// }

// const busName = new bus();


// [Link]("force");
//how to define a varibale in a class

// class bus{
// constructor(brand, distance){
// [Link]("printing text with the help of constructor");
// [Link] = brand;
// [Link] = distance;
// }
// start(){
// [Link]("Start the bus");
// }
// stop(){
// [Link]("stop the bus")
// }
// // setBrand(brand){
// // [Link] = brand;
// // }
// }

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


// [Link](busName);
// const carName = new bus("Volvo", 20)//constructor
// [Link](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){
// [Link] = name;
// [Link] = color;
// [Link] = "word";
// [Link] = Dpt;
// this.branch2 = Dpt2;
// }
// fatherSpeak(){
// [Link]("Hello son");
// }
// }
// class son extends father{
// constructor(Dpt,Dpt2){
// super(Dpt,Dpt2);
// [Link] = Dpt;
// this.engineer2 = Dpt2;
// }
// sonSpeak(){
// [Link]("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){
// [Link] = name;
// [Link] = email;
// }
// viewData(){
// [Link]("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@[Link]");


// let userObj2 = new User("Suresh","suresh@[Link]");
// let userObj3 = new User("Jayesh","jayesh@[Link]");
// let admin = new Admin("Admin", "admin@[Link]");

//Error Handling

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

// a = 5;
// b = 5;
// c = 6;
// [Link](a+b);
// try{
// [Link](a+g);
// }
// catch(err){
// [Link](err);
// }
// [Link](a+c);
// [Link](a+b+c);
//error handling

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

// function bye(){
// [Link]("bye")
// }
// setTimeout(bye, 4000)//timeout function , 4s = 4000ms

//or it also works like this


// setTimeout(
// ()=>{
// [Link]("Using setTimeout function to display this");
// }, 5000
// )
//example of setTimeout()

// [Link]("one");
// [Link]("two");
// [Link]("three");
// [Link]("four");
//synchronous example

//asynchronous example
// [Link]("one");
// [Link]("two");
// setTimeout(
// ()=>{
// [Link]("Using setTimeout function to display this");
// }, 5000
// )
// [Link]("three");
// [Link]("four");

// function sum(a, b){


// [Link](a+b);
// }
// function val(a, b, sumcallback){
// sumcallback(a, b);
// }
// val(3, 5, sum)
//synchronous in callback

// const hello = () => {


// [Link]("Hello");
// }
// setTimeout(hello, 5000);
//half synchronous and half asynchronous in some callback

//nesting

// let age = 17;

// if(age>=18){
// if(age>=40){
// [Link]("Senior")
// }
// else
// {
// [Link]("Adult");
// }
// }
// else
// {
// [Link]("Child")
// }
//nesting if-else
//nesting for loop also exist

// function data(dataId){
// setTimeout(() => {
// [Link](`just checking the data ${dataId}`);
// }, 4000);
// }
// data(100);
//just practice

// function data(dataId, nextData) {


// setTimeout(() => {
// [Link]("Data displayed after 2 seconds:", dataId);
// if (nextData) {
// nextData();
// }
// }, 2000);
// }
// data(1, () => {
// [Link]("gatting next data.....")
// data(2, ()=>{
// [Link]("gatting next data.....")
// data(3, ()=>{
// [Link]("gatting next data.....")
// data(4, ()=>{
// [Link]("gatting next data.....")
// data(5, ()=>{
// [Link]("gatting next data.....")
// data(6, ()=>{
// [Link]("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: [Link]((res)=>{..}) and [Link]((err)=>{..})

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


// [Link]("Promise is created");
// reject("Error displayed");
// })

//example
// function data(dataId, nextData) {
// return new Promise((resolve,reject)=>{
// setTimeout(() => {
// [Link]("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)=>{
// [Link]("My promise")
// // resolve("problem resolve");
// reject("problem not resolved");
// })
// }

// let confirm = myPromise();


// [Link]((res) => {
// [Link]("problem resolved", res);
// });

// [Link]((err) => {
// [Link]("issue not resolved", err);
// })
//uses of promise: [Link]((res)=>{..}) and [Link]((err)=>{..})

// const data = (info) => {


// return new Promise((resolve, reject) => {
// setTimeout(() => {
// [Link]("data display", info);
// resolve("success");
// }, 8000);
// });
// };

// const data2 = (info) => {


// return new Promise((resolve, reject) => {
// setTimeout(() => {
// [Link]("data display", info);
// resolve("success");
// }, 8000);
// });
// };

// const data3 = (info) => {


// return new Promise((resolve, reject) => {
// setTimeout(() => {
// [Link]("data display", info);
// resolve("success");
// }, 8000);
// });
// };

// const data4 = (info) => {


// return new Promise((resolve, reject) => {
// setTimeout(() => {
// [Link]("data display", info);
// resolve("success");
// }, 8000);
// });
// };

// const data5 = (info) => {


// return new Promise((resolve, reject) => {
// setTimeout(() => {
// [Link]("data display", info);
// resolve("success");
// }, 8000);
// });
// };

// [Link]("fetching data 1...");


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

// async function display(){


// [Link]("display my message");
// }
//simple async function

// function api(){
// return new Promise((resolve,reject) => {
// setTimeout(() => {
// [Link]("just a display");
// resolve("success")
// }, 4000);
// } )
// }

// async function apis(){


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

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

// async function datas(){


// [Link]("fetching data 1")
// await data(1);
// [Link]("fetching data 2")
// await data(2);
// [Link]("fetching data 3")
// await data(3);
// }
//with the previous example

// (async function () {
// [Link]("fetching data 1")
// await data(1);
// [Link]("fetching data 2")
// await data(2);
// [Link]("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 = "[Link]

// const getFacts = async () => {


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

// let url = "[Link]

// const data = async () => {


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

// let url = "[Link]


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

//Trying options and post

*/

You might also like