Javascript Notes
Javascript Notes
[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)
*/
// let a = 5;
// let b = "5";
// let c = 5;
// 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)
*/
/*
var price = 256;
var price = 33;
[Link](price)
*/
/*
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)
*/
/*
{
let a = "hello"
[Link](a)
}
{
let a = "bye"
[Link](a)
}
*/
/*
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"]);
*/
// 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"])
//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
// let age = 15
// if(age>=18){
// [Link]("you are eligible to drive a car");
// }
// if(age<18){
// [Link]("you cannot drive a car");
// }
// if(mode==="dark-mode")
// {
// color="Black"
// }
// if(mode==="light")
// {
// color="White"
// }
// [Link](color)
// [Link](sunStatus)
// 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")
// }
// or another method
// let b = 40;
//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
// if(value%5===0){
// [Link](value,"is multiple by 5")
// }
// else
// {
// [Link](value,"is not multiple by 5")
// }
// let score = 35
//loops: for loop, infinite loop, while loop, do while loop, for-of loop, for-in
loop
//sum of calculator
// let n = 100;
// sum = 0;
// for(i=1;i<=n;i++){
// sum += i;
// }
//just printing
//while loop
// let a = 15;
// while(a<=20){
// [Link](a)
// a++;
// }
// let student = {
// Name: "Dheeraj Naik",
// Age: 20,
// Location: "Mumbai",
// Country: "India",
// };
// for(let i in student){
// [Link]("Key = ", i,",", "Value = ", student[i])
// }
//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
//string functions/methods:
//
toUpperCase(),toLowerCase(),trim(),slice(),concat(),replace(),replaceAll(),charAt()
// let str = "something"
// [Link]([Link]())
//or
// [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));
// 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
// for(let i of marks){
// sum += i;
// }
//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;
// Practice question :
//a. remove first company from the array,
// [Link] Uber and Add Ola in its place and
// [Link] Amazon at the end
//parameter in function
// function myFunction(x){
// [Link](x);
// }
// myFunction("hello");
//argument in function call
//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);
//or
// function myf(){
// [Link]("hello");
// }
// myf();
// 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")
// arrowf("hellooo")
//map function
// let arr = [1,2,3,4,5,6,7]
// [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: 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);
//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
// [Link]([Link]);
// [Link]([Link]);
// [Link]([Link]);
// [Link]([Link]);
// 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 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
// let r = [Link]("h1");
// [Link]="checking append child";
// [Link]("div").appendChild(r);
//appendChild...to append node in parent node at the bottom.
//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.
// 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.
//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
// [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)
// [Link]("click",()=>{
// [Link]("Sentence2")
// })
// [Link]("click",()=>{
// [Link]("Sentence3")
// })
// exception = ()=>{
// [Link]("Sentence4")
// }
// [Link]("click",exception)
// [Link]("click", exception)
// 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);
// });
//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")
// }
// }
// class bus{
// start(){
// [Link]("Start the bus");
// }
// stop(){
// [Link]("stop the bus")
// }
// setBrand(brand){
// [Link] = brand;
// }
// }
// 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;
// // }
// }
//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";
// }
// }
//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
// [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");
//nesting
// 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
//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)=>{..})
//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
// [Link]((err) => {
// [Link]("issue not resolved", err);
// })
//uses of promise: [Link]((res)=>{..}) and [Link]((err)=>{..})
// function api(){
// return new Promise((resolve,reject) => {
// setTimeout(() => {
// [Link]("just a display");
// resolve("success")
// }, 4000);
// } )
// }
// 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 () {
// [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
*/