Javascript Notes
Javascript Notes
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)
*/
// 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
//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)
*/
/*
var price = 256;
var price = 33;
console.log(price)
*/
/*
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)
*/
/*
{
let a = "hello"
console.log(a)
}
{
let a = "bye"
console.log(a)
}
*/
/*
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"]);
*/
// 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"])
//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
// 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");
// }
// if(mode==="dark-mode")
// {
// color="Black"
// }
// if(mode==="light")
// {
// color="White"
// }
// console.log(color)
// console.log(sunStatus)
// 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")
// }
// 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":
// 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
// if(value%5===0){
// console.log(value,"is multiple by 5")
// }
// else
// {
// console.log(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){
// console.log(a)
// a++;
// }
// let student = {
// Name: "Dheeraj Naik",
// Age: 20,
// Location: "Mumbai",
// Country: "India",
// };
// for(let i in student){
// console.log("Key = ", i,",", "Value = ", student[i])
// }
//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
//string functions/methods:
//
toUpperCase(),toLowerCase(),trim(),slice(),concat(),replace(),replaceAll(),charAt()
// let str = "something"
// console.log(str.toUpperCase())
//or
// 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));
// 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
// 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,
// b.Remove Uber and Add Ola in its place and
// c.Add Amazon at the end
//parameter in function
// function myFunction(x){
// console.log(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);
// console.log(val);
//or
// function myf(){
// console.log("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++;
// }
// }
// console.log(count)
// }
// myf("helloo")
// arrowf("hellooo")
//map function
// let arr = [1,2,3,4,5,6,7]
// 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: 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);
//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
// console.log(head.tagName);
// console.log(head.innerHTML);
// console.log(head.innerText);
// console.log(head.textContent);
// 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 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
// 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.
//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
// 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)
// divi.addEventListener("click",()=>{
// console.log("Sentence2")
// })
// divi.addEventListener("click",()=>{
// console.log("Sentence3")
// })
// exception = ()=>{
// console.log("Sentence4")
// }
// divi.addEventListener("click",exception)
// divi.removeEventListener("click", exception)
// 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);
// });
//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")
// }
// }
// class bus{
// start(){
// console.log("Start the bus");
// }
// stop(){
// console.log("stop the bus")
// }
// setBrand(brand){
// this.brandName = brand;
// }
// }
// 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;
// // }
// }
//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";
// }
// }
//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
// 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");
//nesting
// 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
//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)=>{..})
//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
// confirm.catch((err) => {
// console.log("issue not resolved", err);
// })
//uses of promise: promise.then((res)=>{..}) and promise.catch((err)=>{..})
// function api(){
// return new Promise((resolve,reject) => {
// setTimeout(() => {
// console.log("just a display");
// resolve("success")
// }, 4000);
// } )
// }
// 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 () {
// 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
*/