THAPA TECHNICAL : JAVASCRIPT NOTES



 Run JS

node script.js

----: Values and variables in javaScript :----

var myName = "Himanshu";
var myAge = 19;
console.log(myName);
console.log(myAge);

----: Data types in JavaScript :----

Six Data types that are primitives.
1. undefined 2. Boolean 3. Number 4. String 5. BigInt 6. Symbol

var myName = "Himanshu";
console.log(myName);
console.log(typeof(myName));

var myAge = 19;
console.log(myAge);
console.log(typeof(myAge));

var iAmBoy = true;
console.log(typeof(iAmBoy));

Data types Practise ***

console.log(10+"20");
console.log(9-"5");
console.log("Java" + "Script");
console.log(""+"");
console.log(""+0);
console.log("Himanshu" - "Tiwari");
console.log(true + true);
console.log(true + false);
console.log(false - true);

Interview Question :-

1. Different between null vs undefined

 var iAmUseless = null;
 console.log(iAmUseless);
 console.log(typeof(iAmUseless)); // This is Bug

 var iAmStandBy;
 console.log(iAmStandBy);
 console.log(typeof(iAmStandBy));

 2. What is NaN?
 NaN is a property of the global object.
 In other wordsit is a variable in global scope.
 The initial value of NaN is not-A-Number

 var myMobileNumber = 9876543210;
 var myName = "Himanshu Kumar Tiwari";
 console.log(isNaN(myMobileNumber));
 console.log(isNaN(myName));

NaN Practise 

NaN === NaN;
console.log(NaN === NaN);

Number.NaN === NaN
console.log(Number.NaN === NaN);

isNaN(NaN);
console.log(isNaN(NaN));

isNaN(Number.NaN);
console.log(isNaN(Number.NaN));

Number.isNaN(NaN);
console.log(Number.isNaN(NaN));

----: Expression And Operators in JavaScript :----

1. Assignment Operators (=)
An assignment Operator assign a value to its left operand based on the value
of its right operand 
The simple assignment operator is equal (=)
var x = 5;
var y = 5;

2. Arithemetic Operators
An Arithemetic Operators takes numerical Values (either literals or variables
as their operands and return a single numberical value.

console.log(3+4);
console.log(2-5);
console.log(40*5);
console.log(40/8);
console.log("Remainder operator : " + 35%2)

Increment & Decrement operator :
Operatorx++ or ++x or x-- or --x 
If used postfix with operator after operand (for example x++),
The Increment operator increments and return the value before increasing.
var num = 15;
var newNum = num++;
console.log(num);
console.log(newNum);

If used prefix with operator before operand (for example ++x),
then the expression is evaluate using the new value of the variable.
var num = 15;
var newNum = ++num;
console.log(num);
console.log(newNum);

3. Comparison Operators
A comparision Operator compares its operand and
returns a logical value based on whether the comparison is true or false

var a = 30;
var b = 10;

Equal (==)
console.log(a==b);

Not equal (!=)
console.log(a!=b);

Greater than (>)
console.log(a>b);

Greater than or equal (>=)
console.log(a>=b);

Less than Operator (<)
console.log(a<b);

Less than or equal (<=)
console.log(a<=b);


4. Logical Operators
Logical operators are typical used with boolean (logicalValues;
when they are , they return a Boolean value.

var a = 30;
var b = -20;

Logical AND (&&)
The Logical AND (&&) operator (logical conjuctionfor a set of 
Operand is true if and only if all of its operand are true.
All expression need to be true otherwise it returns false
var a = 30;
var b = -20;
console.log(a>b && b<0 && a >0);

Logical OR (||) 
The Logical OR (||) operator (logical disjunctionfor a set of
operand is true if and only if one or more of its operand is true.
if only one expression is true it retruns true

var a = 30;
var b = -20;
console.log((a>b) || (b>a) || (a=b));

Logical NOT (!)
The Logical NOT (!) operator (logical complement , negation)
takes truth to falsity and vice versa.
It changes true into false and false into true

var a = 30;
var b = -20;
console.log(!((a>0) || (b<0)));
console.log(!(false));

5. String Concatenation (Operators)
The concatenation operators (+) concatenates two strings values together,
returning another string that is the union of two operand string.

console.log("Hello world");
console.log("Hello " + "world");

6. Conditional Operators


Challenge Time:-

Q1What will be the output of 3**3?
console.log(3**3); // its like power

Q2.  What will be the output when we add a number and a string?
console.log(5 + "Himanshu");

Q3write a program to swap two numbers?
var a = 5;
var b = 10;

output b=5,a=10

var c = b//c=10
b = a// b = 5;
a=c;

console.log("The value of a is " + a);
console.log("The value of b is " + b);

Q4write a program to swap two numbers using third variables?

var a = 5;
var b = 10;

output b=5,a=10

a = a + b;  // a = 15
b = a - b;  // b = 5
a = a - b;  // a = 10

console.log("The value of a is " + a);
console.log("The value of b is " + b);

Interview Question :-
What is the Difference between == vs ===?

(==)
var num1 = 5;
var num2 = "5";
console.log((typeof(num1)));
console.log((typeof(num2)));
console.log(num1 == num2);

(===)
var num1 = 4;
var num2 = "4";
console.log((typeof(num1)));
console.log((typeof(num2)));
console.log(num1 === num2);

{==} check the value of only where as ,
{===} checks value as well as Data types.

:---- Control Statement & Loops :----

If..Else
Switch Statement
While Loop
Do-While Loop
For Loop
For in Loop
For of Loop
Conditional (ternaryoperator

1. If else :-
The if statement executes a statement if a specified condition is truthy.
If the condition is falsyanother statement can be executed.

var tommorow = "sunny";
if(tommorow=="rain"){
    console.log("take an umberalla");
}else{
    console.log("No need to take an umberalla")
}


var area = "triangle";
var PI = 3.14;
var l = 5;
var b = 4;
var r = 3;

if(area =="circle"){
    console.log(PI*r**2);
}else if(area == "triangle"){
    console.log(l*b/2);
}else if(area == "rectangle"){
    console.log(l*b);
}else{
    console.log("Please enter valid Data");
}


Question :- what is truthy and falsy value in JavaScript .
We have total 5 falsy value in javaScript 
0 , "" , undefined , null , NaN , false 

if (true) {
    console.log("We Loss the game");
}else{
    console.log("We won the game");
}

2. Conditional (ternaryoperator
The conditional (ternaryoperator is the only JavaScript 
Operator that takes three operands
This is Short Hand of If else

var age = 31;
console.log((age>=18) ? "you can vote" : "You can't vote") ;

3. Switch Statement :-
Evalutates an expression , matching the expression's value to 
a case clause, and executes statements associated with the case.

var area = "triangle";
var PI = 3.14; l = 5; b = 4; r = 3;

switch(area){
    case "circle":
        console.log("The area of circle is " + PI*r**2)
        break;
    case "triangle":
        console.log("The area of triangle is " + l*b/2);
        break;
    case "rectangle":
        console.log("The area of rectangle is " + l*b);
        break;
    default:
        console.log("Please enter Valid Data");
}

 break
Terminates the current loop, switch or label
statement and transfers
Program control the statement following the terminated statement.

4. While Loop Statement :-
The while Statement creates the loop that execute a specified statement 
as long as the test condition evaluates to true.

var num=0;
while (num<=100) {
    console.log(num); // infinite Loop
    num++;
}

5. Do-While Loop Statement :-

var num = 0;
do {
    console.log(num);
    num++;
} while (num<=10);

6. For Loop Statement :-

for(var num = 0; num<=10 ; num++){
    console.log(num);
}

Challange Time :-

Q. JavaScript program to print table for given number
(8 and 9) using for Loop.

for(var x = 1; x <= 10; x++){
    var tableOf = 8;
    console.log(tableOf + " x " + x + " = " + (tableOf * x));
}

for(var num = 1; num<=10; num++){
    tableOf = 9;
    console.log(tableOf + " x " + num + " = " + tableOf*num);
}

----: Functions In JavaScript :----

Function Definition
Calling a function
Function Parameter
Function Arguments
Function Expression
Return Keyword
Anonymous Function

A javascript function is a block of code design to perform
a perticular task.


Function Defination :-

Before we use a function , we need to define it.

A function defination (also called a function declaration
, or function statement) , consists of the functions keyword , Followed By :

The name of the function
The list of parameter to the function, enclosed in parentheses and separated by commas.
 The javascript statement that defiend the function,enclosed in curly barkets {...}

function sum (){
    var a = 10;
    var b = 20;
    var total = a+b;
    console.log(total);
}

Calling Functions :-
Defining a function does not execute it.
A javaScript function is executed when 'something' invokes it (calls it).

function sum (){
    var a = 10;
    var b = 20;
    var total = a+b;
    console.log(total);
}
sum();

Challenge Time :-

Q. What is difference between function parameter vs function Arguments.

Function parameters are the names listed in the function's defination.
Function arguments are the real values passed to the function.

function sum(a,b) { // (a,b) is parameters
    var total = a+b;
    console.log(total);
}

sum();
sum(8,9// (8,9) is arguments
sum(4,8);


Interview Questions:-

QWhy functions?

You can reuse code : Define the code onceand use it many times.
You can use the same code many times with different arguments,
to produce different results.

OR

A function os a group of reusable code which can be called anywhere
in your programThis eliminates the need of writing the same code 
again and again.


DRY => Do Not Repeat Yourself.


Function Expression :-

Function expression simply means
Create a function and put it into variables


function sum(a,b) {
    var total = a+b;
    console.log(total);
}

var funExp = sum(5,10);


Return Keyword :-

When JavaScript reaches a return statement,
the function will stop executing.
Function often compute a return value.
The return value is "returned" back to the "caller"

ex.

function sum(a,b) {
   return total = a+b;
}

var funExp = sum(10,4);
console.log("The sum of 10 and 4 are " + funExp);

ex.

function sum (a,b){
    return total = a+b;
}

var funExp = sum(2,2);
console.log("The sum of 2 and 2 are " + funExp);


Anonymous Function :-

A function expression is similar to and has the same syntax
as a function declaration one can defined "named"
function expression (where the name of the expression might
be used in the call stack for example )
or "anonymous" function expressions.

Function without name is called anonymous function.

var funExp = function(a,b){
    return total = a+b;
}

var sum = funExp(15,15);
var sum1 = funExp(13,15);
console.log("The sum of two no. is" + sum);


******* ECMA Script ********

Features of ECMAScript 2015 also known as ES6

LET and CONST
Template String
Default Arguments
Rest Operators
Destructuring
Object properties
Arrow Function
Spread Operator

1. LET VS CONST VS VAR


let myName = "Himanshu Tiwari";
console.log(myName);


myName = "Aditya Tiwari"
console.log(myName);

const

const myName = "Himanshu Kumar";
console.log(myName);

myName = "Aditya Tiwari"
console.log(myName);


function bioData(){
    let myFirstName = "Himanshu";
    console.log(myFirstName);

    if(true){
        let myLastName = "Tiwari";
        console.log("inner " + myLastName);
        console.log("inner " + myFirstName);
    }

    console.log("innerOuter " + myLastName);
}

bioData();

var => function scope.
let and const => block scope.


2. Template Literals (Template strings)

JavaScript program to print table for given number(8).


for(let num = 1num<=10num++){
    let tableOf = 8;
    console.log(`${tableOf} * ${num} = ${tableOf * num}`);
}


3. Default parameters 

Default function parameters allow named parameters to be 
initialized with default values if no value or undefined is passed.

function mult(a,b=5){
    return total = a*b;
}

console.log(mult(4));

4. Destructuring In ES6

THe destructuring assignment syntax is a javascript expression
that makes it possible to unpack the values from arrays,
or properties from objectsinto distinct variables.

ARRAY DESTRUCTURING 

const myBioData = ['himanshu','kumar',19];

👎
let myFName = myBioData[0];
let myFName = myBioData[1];
let myFName = myBioData[2];
console.log(myAge);

👍
let [myFName,myLName,MyAge] = myBioData;
console.log(myFName);

OBJECT DESSTRUCTURING 

👎
const myBioData = {
    myFName : "Himanshu",
    myLName : "Tiwari",
    myAge : 19,
}
    let myAge = myBioData.myAge;
    console.log(myAge);

    👍
    let {myFName,myLName,myAge} = myBioData;
    console.log(myLName);

5. Object properties :-

we can now use dynamic proeprties

    let myName = "HK";
    let myBio = {
       [myName]: "is my name ",
       26 : "is my age"

    }
console.log(myBio);


If key and value both are same then no need to write key and value.

let myName = "Hk";
let myAge = 19;

const myBio = {myName,myAge};
console.log(myBio);


6. Fat Arrow Function

Normal way to writing Function

function sum(){
    let a = 5;
    let b = 6;
    let sum = a+b;
    return `The sum of two numbers is ${sum}`;
}

console.log(sum());

How to convert into Fat Arrow Function

const sum = () => {
    let a = 5;
    let b = 6;
    let sum = a+b;
    return `The sum of two numbers is ${sum}`;
}
console.log(sum());

one line solution

const sum = () => `The sum of two number are ${(a=5)+(b=4)}`
console.log(sum());


7. Spread Operator :-

const colors = ['red','green','yellow','blue'];
const myColors = ['red','green','yellow','blue','white','black'];

const myFavColor = [...colors , 'white','black'];
console.log(myFavColor);

----: Arrays In JavaScript :----

When we use var we can stored only one value at a time.
When we feel like storing multiple values in one variables then
instead of varwe will use an Array.
In JavaScriptwe have an Array classand arrays are the prototype
of this class.
eg.
var myFriends =["Ankit" , "Ankur" , "Dheeraj" , "Santosh"];

1. Traversal of an Array
2. Searching and filter in an Array
3. How to sort and compare an Array
4. How to insert,Add,Replace and delete elements in Array (CRUD)
5. Map(), Reduce(), Filter()

🌟 Traversal In Array (Navigate through Array) :-

if we want to get the single data at a time and also 
if we want to change the data

   var myFriends = ["Rames" , "Suresh" , "Mahesh"]
   console.log(myFriends[2]);

if we want to check the length of elements of an array.

   console.log(myFriends.length);

we use for loop to navigate

var myFriends = ["Ram" , "Shyam" , "Mohan" , "Gita"]


for(var i=0i<myFriends.lengthi++){
    console.log(myFriends[i]);
}

After ES6 we have for..in and for..of loop too


for in (It prints the numbers of the values)

var myFriends = ["Ram" , "Shyam" , "Mohan" , "Gita"]
for(let elements in myFriends){
    console.log(elements);
}

for off (it prints the value)

var myFriends = ["Ram" , "shyam" , "Mohan" , "Gita"]
for(let elements of myFriends){
    console.log(elements);
}

Array.prototype.forEach()
Calls a function for each element in the array.

var myFriends = ['Ram','shyam','gita','sita']

myFriends.forEach(function (element,index,array){
    console.log(element + " index : " + index + " " + array);
})

Fat arrow function 

myFriends.forEach((element,index,array=> {
    console.log(element + " index : " + index + " " + array);
})

🌟 Searching and filter in an Array 

Array.prototype.indexOf()
Return the first (leastindex of an element within the array equal
to an elementor -1 if none is foundIt search the element from the 
0th index number

var myFriends = ["Ram" , "shyam" , "Mohan" , "Gita"]
console.log(myFriends.indexOf("Mohan"2));


Array.prototype.lastIndexOf()
Return the last(greatestindex of an element within the array equal
to an elementor -1 if none is foundIt search the element last to 
First.


var myFriends = ["Ram" , "shyam" , "Mohan" , "Gita"]
console.log(myFriends.lastIndexOf("Mohan"2));

Array.prototype.includes()
Determines whether the arrays contains a value,
returning true or false as appropriate.


var myFriends = ["Ram" , "shyam" , "Mohan" , "Gita"]
console.log(myFriends.includes("shyam"));


Array.prototype.find()
arr.find(callback(element[, index[, array]])[, thisArg])
Returns the found element in the arrayif some element in the 
array satisfies the testing functionor indefined if not found.
only problem is that it return only one element.

const prices = [200,250,300,350,400,500]

const findElem = prices.find((currVal)=>{
    return currVal < 400
})

console.log(findElem);


Array.prototype.findIndex()
Return the found index in the arrayif an element in the 
array satisfies the testing function or -1 if not found.

const prices = [200,250,300,350,400,500]
console.log(prices.findIndex((currVal)=> currVal < 400));


Array.prototype.filter()
Return a new array containing all elements of the calling
array for which the provided filtering function returns true.


 const prices = [200,250,300,350,400,500]

 const newPriceTag = prices.filter((elem,index=> {
     return elem < 400;
 })

 console.log(newPriceTag);

🌟 How to short an Array

Array.prototype.sort()

The sort() method sorts the elements of an array in place and
return the sorted arrayThe default sort order is ascendingbuilt
upon converting the elements into strings,
then comparing there sequence of UTF-16 code units values.


const months = ["Feb" , "Dec" , "May" , "Oct"];
console.log(months.sort());

const array1 = [1,23,7,89,786,5675,5,65,];
console.log(array1.sort());

Howeverif number are sorted as strings,
"25" is bigger than 100because "2" is bigger than "1".

Because of thisthe sort() method will produce an incorrect
result when sorting numbers.


🌟 Perform CRUD [Insert/add]

Array.protoype.push()
The push() method adds one or more element to the 
end of an array and return the new length of the array.

const animals = ["Pigs" , "goat" , "Sheep"];
animals.push("chicken","Cow");
console.log(animals);

Array.prototype.unshift() 
The unshift() method adds one or more elements to the 
begining of an array and return the new length of the array.

 const animals = ["Pigs" , "goat" , "Sheep"];
 animals.unshift("chicken","Cow");
 console.log(animals);

Array.prototype.pop() [delete/remove last one]
The pop() method removes the last element from an array and return 
that elementThis method changes the length of the array.

const vegetables = ["Tomato" , "Potato" , "Bringal" , "cauliflower" ];
console.log(vegetables);
console.log(vegetables.pop());
console.log(vegetables);


Array.prototype.shift()
The shift() method removes the first element from an array and
returns that removes elementThis method changes the length of the
array.


const vegetables = ["Tomato" , "Potato" , "Bringal" , "cauliflower" ];
console.log(vegetables);
console.log(vegetables.shift());
console.log(vegetables);


Challenge Time :-

Array.prototype.splice()
Adds and/or removes element from an array.

Q1Add Dec at the end of an array.
Q2What is the return value of splice method?
Q3update march to March (update).
Q4Delete june from an array.


const months = ['jan','march','April','June','July']

sol1:
const newMonth = months.splice(5,0,"Dec");
console.log(months);

sol2:
console.log(newMonth);

sol3:

a.
const months = ['jan','march','April','June','July']
const updateMonth = months.splice(1,1,'March');
console.log(months);


b.
const months = ['jan','march','April','June','July']

const indexOfMonth = months.indexOf("march");

if(indexOfMonth != -1){
    const updateMonth = months.splice(indexOfMonth,1,"March");
    console.log(months);
}else{
    console.log("No such data found");
}


sol4:

 const months = ['jan','march','April','June','July']

const indexOfMonth = months.indexOf("June");

if(indexOfMonth != -1){
    const updateMonth = months.splice(indexOfMonth,1);
    console.log(months);
}else{
    console.log("No such data found");
}


🌟 Array subsection (Map and Reduce Method)
Array.prototype.map()

let newArray = arr.map(callback(currentValue[,index[, array]]){
return element for newArray, after executing something
}[,thisArg]);

Return a new array containing the result of calling a 
function on every element in this array.

const array1=[1,4,9,16,25];

// num > 9

let newArr = array1.map((curElement,index,arr)=>{
    return curElement > 9;
})

console.log(array1);
console.log(newArr);


const array1=[1,4,9,16,25];
 
let newArr = array1.map((currElem,index,arr)=>{
    return ` Index no = ${index} and the value is ${currElem} belongs to ${arr}` 
})

console.log(newArr);

it return new array without mutating the original array.

Challenge time 

Q1. Find the square root of each element in an array?
Q2. Multiply each element by 2 and return only those 
    element which are greater than 10?

sol1.

let arr = [25,36,49,64,81];

    let arrSquare = arr.map((currElem)=>{
        return Math.sqrt(currElem);
    })

    console.log(arrSquare);


sol2.

let arr = [2,3,4,6,8];

let arr2 = arr.map((currElem)=>{
    return currElem * 2;
}).filter((currentValue)=>{
    return currentValue>10;
})

console.log(arr2);

we can ue channing too


REDUCE METHOD :-

Flatten an array means to convert the 3d array into a single 
dimensional array

The reduce() method executes a reducer function( that you provide)
on each element of the array,resulting in the single output values.

The reducer function takes four arguments:

 Accumulator 
 Current Value
 Current Index
 Source Array
 
let arr = [5,9,4,7];

let sum = arr.reduce((accumulator , curElem,index,arr)=>{
    return accumulator += curElem;
},7)

console.log(sum);

How to fatten an array
converting 2d and 3d array into one dimensional array 

const arr = [
       ['zone_1' , 'zone_2'],
       ['zone_3' , 'zone_4'],
       ['zone_5' , 'zone_6'],
       ['zone_7' , 'zone_8']
     ];

     let flatArr = arr.reduce((accumulator,currVal)=>{
        return accumulator.concat(currVal);
     })

     console.log(flatArr);


flat() Mehthod :-

const arr = [
           ['zone_1' , 'zone_2'],
           ['zone_3' , 'zone_4'],
           ['zone_5' , 'zone_6'],
           ['zone_7' , 'zone_8']
         ];

         console.log(arr.flat(Infinity));

----: Strings In JavaScript :----

1. Escape Character.
2. Finding a string in a String.
3. Searching for a String in a String.
4. Extracting String Parts.
5. Replace String Content.
6. Extracting String Characters.
7. Other useful methods.

A JavaScript string is zero or more characters written inside quotes.
JavaScript string are used for storing and manipulatiing text.
You can use single or double quotes.
Strings can be created as primitives,
from string literals,or as objects, using the String() constructer


let myName = "Himanshu Tiwari";
let myChannelName = "Himanshu Tiwari";
console.log(myName);


How to find length of a string.

String.prototype.length
Reflects the length of the string

let myName = "Himanshu";
console.log(myName.length); 


🌟Escape Character :-

let anySentence = "We are so-called \"Vikings\" from the north";
console.log(anySentence);

If you don't want to mess, simply use the alternate quotes


let anySentence2 = `We are so-called "Vikings" from the north`;
console.log(anySentence2);


🌟Finding a string in a String :-

String.prototype.indexOf(searchValue[, fromIndex])

he indexOf() method returns the index of (the postion of) the first
occurence of a specified text in a string.

const aboutMe = "Hey myself himanshu kumar tiwari ";
console.log(aboutMe.indexOf("h",13));

Js counts position from zero.
0 is the first position in a string, is is the second .........

*******

String.prototype.lastIndexOf(searchValue[, fromIndex])
Returns the index whithin the calling string object of the
last occurence of searchValue, or -1 if not found.

const aboutMe = "Hey myself himanshu kumar tiwari ";
console.log(aboutMe.lastIndexOf("r"));


🌟Searching for a String in a String :-

String.prototype.search(regexp)

The search() method search a string for a specified
value and return the postion of the match.

const aboutMe = "I am himanshu kumar tiwari";
1.
let searchData = aboutMe.search("kumar");
console.log(searchData);
2.
console.log(aboutMe.search("kumar"));

The search() method cannot take a second start position argument.


🌟Extracting String Parts :-

There are 3 methods for extracting a part of a string.

1. slice(start,end)
2. substring(start,end)
3. substr(start,length)

1. The slice() method 
slice() extrats a part of a string and returns the extracted part
in a new string.

The method takes 2 parameters : the start postiton,
and the end position(end not included).

var str = 'Apple , Banana , Kiwi';
let res = str.slice(7,-4);
console.log(res);

The slice() method selects the element starting at the given
start argument, and ends at, but does not include the given 
end argument.

⚠ Note :- The original array will not be changed.
Remember :- javaScript counts positions from zero. First position is 0

Challenge Time :-

Q. Display only 2 characters of a string like the one 
used in twitter ?

let myTweet = "lorem ipsum"

let myActualTweet = myTweet.slice(0,2);
console.log(myActualTweet);

2. The substring() Method
substring() is simiar to slice()
The difference is that substring() can't accept
negative indexes.

var str = "Apple,Banana,Kiwi";
let res = str.substring(0,4);
console.log(res);

3. The substr() method
substr() is similar to slice().

The difference is that the second parameter specifies the 
length of the extracted part.

var str = 'apple,banana,kiwi';
let res = str.substr(-4);
console.log(res);

🌟 Replace String Content:-

String.prototype.replace(searchFor, replaceWith)

The replace() method replaces a specific value with
another value in a string.

let myBioData = "Myself Himanshu tiwari";
let res = myBioData.replace("himanshu","Aditya");
console.log(res);


Points to remember :-
1. The replace() method doesn't change the string
   it is called on. It returns a new string.
2. By default, the replace() method replace only 
   the first match.
3. By default, replace() method is case sensitive.
   writing HIMANSHU (with upper-case) will not work.


🌟 Extracting String Characters :-

There are three methods for extracting string characters.

➡ charAt(position)
➡ charCodeAt(position)
➡ property access [ ]

➡ ➡ The charAt() method
The charAt() method returns the character at a 
specified index (positoin) in a string.

let str = 'HELLO WORLD';
let res = str.charAt(6);
console.log(res);

➡ ➡ The charCodeAt() method
The charCodeAt() method returns the unicode of the 
character at a specified index in a string:
The method return a UTF-16 code
(an integer between 0 and 65535)

The Unicode Standard provides a unique number for every
character, no matter the platform, device, application,
or language. UTF-8 is a popular Unicode encoding which 
has 88-bit code units. 

let str = "HELLO WORLD";
let res = str.charCodeAt(0);
console.log(res);


Challenge Time :-
Return the unicode of the last character in a string

let str = "HELLO WORLD";
let lastChar = str.charCodeAt(10);
console.log(lastChar);

➡ ➡ Property Access
ECMAScript 5 (2009) allows property access [ ] on strings

var str = "Hello world";
console.log(str[0]);


🌟 Other useful Methods :-

UpperCase / LowerCase 

let myName = "Himanshu Tiwari";
console.log(myName.toUpperCase());
console.log(myName.toLowerCase());


CONCAT 

The concat() method
concat() joins two or more strings.

let fName = "Himanshu"
let lName = "Tiwari"

console.log(fName + lName);
console.log(fName.concat(lName));
console.log(fName.concat(" ",lName));


TRIM 

String.trim()
The trim() method removes whitespace from both sides 
of a string

var str = "    Hello world";
console.log(str.trim());


CONVERTING STRING INTO AN ARRAY

A string can be coverted to an array with the 
split() method.

var txt = 'a,b,c,d,e';        // string
console.log(txt.split(","));  // split on commas
console.log(txt.split(" "));  // split on spaces
console.log(txt.split("|"));  // split on pipes\


<<----: Date & Time in JavaScript :---->>

1. Date Methods(get and set)
2. Time Method(get and set)

JavaScript Date object represent a single moment in time in a 
platform-independent format. Data onjects contain a number 
that represent milli-seconds since 1 january 1970 UTC.

❄ Creating Object
There are 4 way to create a new data object:

a. new Date()
b. new Date(year,month,day,hours,minutes,seconds,milliseconds)
it takes 7 arguments
c. new Date(milliseconds)
we cannot avoid month section
new Date(date string)



👉new Date()
Date object are created with the new Data() constructer

let currDate = new Date();
console.log(currDate);

console.log(new Date());
console.log(new Date().toLocaleString()); // 9/11/2019, 1;25:01 Pm
console.log(new Date().toString()); // Wed Sep 11 2019 13:25:01

👉Date.now()
Return the numeric value corresponding to the current time-the Number 
of milliseconds elapsed since january 1, 1970 00:00:00 UTC

console.log(Date.now());

👉new Date(year, month,...)
7 number specify year,month,day,hour,minutes,second and mil-sec (in that order)
Note: JavaScript counts months from 0 to 11.
januay is 0 and Dec is 11.
Month argument is must

var d = new Date(2021,7,27,20,20,0);
console.log(d.toLocaleString());


👉new Date(dateString)
new Date(dateString) creates a new object from a date string

var d = new Date("october 13, 2014 11:13:00");
console.log(d.toLocaleString());

Date Methods :-

const currDate = new Date();

How to get the invisible date.

console.log(currDate.toLocaleString())
console.log(currDate.getFullYear());
console.log(currDate.getMonth()); // 0 to 11 jan to dec
console.log(currDate.getDate());
console.log(currDate.getDay());

How to set the individual date.

console.log(currDate.setFullYear(2022));
console.log(currDate.setFullYear(2022,10,5));
console.log(currDate.setMonth(10));
console.log(currDate.setDate(5));
console.log(currDate.toLocaleString());


Time Methods :-

const curTime = new Date();

how to get the indivdual time 

console.log(curTime.getTime());
// The getTime() method return the number of milliseconds
// since january 1,1970
console.log(curTime.getHours());
// The getHours() method returns the hours of a date as a 
// number (0-23)
console.log(curTime.getMinutes());
console.log(curTime.getSeconds());
console.log(curTime.getMilliseconds());

How to get the invisible date.

let curTime = new Date();

console.log(curTime.setHours(5));
console.log(curTime.setMinutes(5));
console.log(curTime.setSeconds(5));
console.log(curTime.setMilliseconds(5));

Practise Time :-
new Date().toLocaleTimeString(); // 11:18:48 AM
new Date().toLocaleDateString(); // 11/16/2015
new Date().toLocaleString();     // 11/16/2015,11:18:48 PM




<<-----: JavaScript Math Object :----->>
The JavaScript Math object allows you to perform mathematical task on numbers.


👉console.log(Math.PI);
console.log(Math.PI);

👉Math.round()
returns the value of x rounded to its nearest integer

let num = 10.44857;
console.log(Math.round(num));

👉Math.pow()
Math.pow(x,y) return the value of x to the power of y

console.log(Math.pow(2,3));
console.log(2**3);

👉Math.squr()
Math.sqrt() returns the square root of x

console.log(Math.sqrt(25));
console.log(Math.sqrt(36));
console.log(Math.sqrt(47));
console.log(Math.sqrt(58));

👉 Math.abs()
Math.abs(x) returns the absolute (positive) value of x


console.log(Math.abs(-55));
console.log(Math.abs(-55.5));
console.log(Math.abs(-955));

👉Math.ceil()
Math.ceil() returns the value of x rounded up to its nearest integer
It always increment your number if u add something after point(.).

console.log(Math.ceil(4.51));
console.log(Math.ceil(99.11));


👉Math.floor()
Math.floor() returns the value of x rounded down to its nearest integer
It always decrement your number if u add something after point(.).

console.log(Math.floor(4.67));
console.log(Math.floor(8.9));

👉Math.min()
Math.min() can be used to find the lowest value in a list of arguments

console.log(Math.min(45,67,324,345));


👉Math.max()
Math.max() can be used to find the higest value in a list of arguments

console.log(Math.max(45,67,324,345));

👉Math.random()
Math.random() returns a random numbre between 0 (inclusive), and 1

console.log(Math.floor(Math.random()*10)); // 0 to 9

👉Math.trunc()
The trunc() method returns the integer part of a number

console.log(Math.trunc(4.6));
console.log(Math.trunc(-9.1));


🏁 Practise Time :-
If the argument is a positive number, Math.trunc() is equivalent to
Math.floor(),
otherwise Math.trunc() is equivalent to Math.ceil().

<<----: DOM IN JAVASCRIPT :---->>

1. Window Vs Document
2. DOM Vs BOM
3. DOM Navigation
4. Searching and getting Element Reference

🟠Window :-

🟢Window is the main container or we can say the global object and 
any operation to entire browser window can be part of window obj.

🟢All the members like object,methods or properies. If they are the 
part of window obj then we do not refer the window object.

🟢Window has methods,properties and object. ex. setTimeout() or setInterval()
are the methods, where as Documents is the object of the window and it also has
a screen object with properties describing the physical display 

🟠Document :-

🟢Where the DOM is the child of window obj.

🟢Where in the DOM we need to refer the document,if we want to use the
document obj, method or properties.

🟢Document is just the object of the global object that is window, which deals
with the document,the HTML elements themselves.

DOM vs BOM :-

👉 The DOM is the Document Object Model, which deals with the document,
the HTML element themselves, eg. document and all traversal you 
would do in it, events,etc.

For Ex:
change the background color to red
document.body.style.background = "red";

👉 The BOM is the Browser Object Model, which deals with browser components
aside from the document, like history, location, navigator and screen 
(as well as some other that vary by browser) . OR
In simple meaning all the Window operation which comes under BOM are performed 
Using BOM


Navigation Through the DOM :-

1: document.documentElement
     return the Element that is the root element to the document.
2: document.head
3: document.body
4: document.body.childNodes (include tab,enter and whiteSpace)
     list of the direct children only
5: document.children (without text nodes, only regular Elements)
6: document.childNodes.length


Searching and getting Element Reference :-
Image is uploaded on website


Interview Questions :-
Q. Difference Between getElementById And querySelectot? 

🔹 What is getElementById()?
Syntax :-
elemet = document.getElementById(id);

returns a reference to the element by its ID.
If the element with the specific ID is not in the document,
it will return null.

🔹 What is querySelector()?
Syntax:
element = document.querySelector(selectors);
Return the first element with the document 
that matchs the specified group of selectors,
or null if no matches found..

<---- Event In JavaScript ---->

4 way to write events in javascript 
What is event Object?
Mouse events in JavaScript
Keyboard events in JavaScript
InputEvents in JavaScript

What is Events?
HTML Events are "Things" that happen to HTML elements.
When JavaScript is used in HTML pages,JavaScript can "react" on these events.

HTML Events
An HTML Events can be something the browser does,or something a user does.

Here are some examples of HTML events:

An HTML web page has finished loading
An HTML input field was changed 
An HTML button was clicked 
Often, when events happen, you may want to do something.


javaScript lets you execute code when wvents are detected.

HTML allows event handler attributes, with JavaScript code,
to be added to HTML Elements.


👉 Four ways to writing Events in JavaScript:-
1. using Inline events alert();
2. By calling a function (we already seen and most common way of writing).
3. using Inline events (HTML onClick="" property and element.onClick)
4. using Event Listeners (addEventListeners and IE's attachEvent)

a.
   onClikc="alert"("Hello")

b. 
   const funcName = () => {
   alert("Hello");
   }

c.
   const thirdway = document.getElementById("idName");
   thirdway.onClick = function(){
   alert("Hello");
   }

d. we can use addEventListners multiple times , no override issue.

   const fourthway = document.querySelector(#idName);
   fourthway.addEventListner('click',() => {
     alert("Hello");
   })


👉 What is Event Object ?
   Event object is the parent object of the event object.
   for example
   MouseEvent, FocusEvent, KeyboardEvent etc.


👉 Mouse Event In JavaScript :-

   The MouseEvent Object
   Events that occur when the mouse interacts with the HTML
   document belongs to the MouseEvent Object.

👉 Keyboard Event in JavaScript :-

   Event that occur when user pressed a key on the keyboard,
   belongs to the KeyboardEvent object.

👉 Input Events in JavaScript:-

   The onChange event occurs when the value of an element has been changed.

   For radiobutton  and checkboxes, the onChange event occurs when the 
   checked state has been changed.

HTML EXAMPLE 

<html>>
<body>
    <label for="">your name</label>
    <input type="text" name="" id="ice">
    <br>    
    <label>Choose an Ice Cream Flavor
        <select name="icecreams" id="iceCreams" onchange="selectElement()">
            <option value="">choose ice cream</option>
            <option value="chocolate">Chocolate</option>
            <option value="sardine">Sardine</option>
            <option value="vanilla">Vanilla</option>
        </select>
    </label>
    <br>
    <div id="result"></div>

    <script>
        const selectElement = ()=>{
            const inputChange = document.getElementById('ice').value;
            const iceCreams = document.getElementById('iceCreams').value;  
            const result = document.getElementById('result');
            result.innerHTML = `Mr ${inputChange} select ${iceCreams} ice-cream flavour`;
            console.log(`${inputChange} and ${iceCreams}`);
        }


        second method without inline code
        const iceCreams = document.getElementById('iceCreams');
        
        iceCreams.addEventListener('change', ()=>{
            const inputChange = document.getElementById('ice').value;
            const iceCreams = document.getElementById('iceCreams').value;
            const result = document.getElementById('result');

            result.innerHTML = `Mr ${inputChange} select ${iceCreams} ice-cream flavour`;
        })


    </script>
</body>
</html>


Interview Q :-

what is difference between addEventListner and onClick ?

addEventListner doesnot overwrtie existing event handler,
whereas onclikc overrides the existing onclick = fn event handlers.

onClick will work everywhere , whereas addEventListner doesn't work in Internet 
explorer before version 9.

<----- Timing Based Events In JavaScript ----->

The Window object allows execution of code at specified time intervals.
These time intervals are called timing events.
The two key methods to use with JavaScript are:

setTimeout(function,milliseconds)
execute a function, after waiting a specified number of milliseconds.

setInterval(function,milliseconds)
same as setTimeOut(), but the executio of the fucnction continuously.



1. setTimeout()
2. setInterval()
3. clarTimeOut()
4. clearInterval()

SEE IN HTML 


<---- OOPS IN JAVASCRIPT ---->

What is object literals ?
What is "this" object ?

What is object Literal?
Object literal is simply a key:value pair data structure.

storing variables and functions together in one container,
we can refer this as an objects.

Object = school bag.

How to create an object?

1st way :-

let bioData  = {
    myName : "Himanshu Kumar Tiwari",
    myAge : 19,
    myAddress : "Shahpur Daltonganj",
    getData : function () {
        console.log(" My Name is " + bioData.myName + "and my age is " + bioData.myAge);
    }
}

console.log(bioData.getData());

2nd way :-
no need to write function keyword 

let bioData  = {
    myName : "Himanshu Kumar Tiwari",
    myAge : 19,
    myAddress : "Shahpur Daltonganj",
    getData () {
        console.log(" My Name is " + bioData.myName + "and my age is " + bioData.myAge);
    }
}

bioData.getData();


what if we want object as a value inside an Object.

let bioData  = {

    myName : {
        firstName : "Himanshu",
        lastName : "Tiwari",
        myCollege : {
            college : "GLA COLLEGE",
        },
    },
    myAge : 19,
    myAddress : "Shahpur Daltonganj",
    getData () {
        console.log(" My Name is " + bioData.myName + "and my age is " + bioData.myAge);
    }
}

console.log(bioData.myName.myCollege.college )


What is this Object?

The defination of 'this' object is that it contain the current context.
The this object can have different value depending on where it is placed.

for example 1
console.log(this.alert("Namaste World"));
it returns to the current vontext and that is window global object.

example 2

function myName(){
    console.log(this);
}

myName();

example 3 

let myNames = "Himanshu"
function myName(){
    console.log(this.myName);
}

myName();

example 4

const obj = {
    myAge : 19,
    myName(){
        console.log(this.myAge);
    }
}
obj.myName();

❗❗❗ this object not work with Fat arrow function ❗❗❗

<---- ES7 Features :---->

1. Array.prototype.includes
2. Exponentiation Operator

<---- ES8 Features :---->

1. String padding
2. Object.values()
3. Object.entries()

<---- ES18 ---->

const person = {name : "fred" , age : 19};
const sPerson = {...person};
console.log(person);
console.log(sPerson);

<---- ES20 ---->
BIG INT


<--- ES2014 --->
use strict mode


<---- Advance JavaScript ---->

What we will see 

Event Propagation (Event bubbling and Event Capturing)
Higher Order Function
Callback Function
Function Currying (we will see after Async JS section)
CallBack Hell
AJAX call using XMLHttprequest
BONUS Section JSON
Fetch API
Promise
Async-Await
Error Handling in jS

1️⃣ What is Event Propagation ?
 The Event Propagation mode determines in which order the elements
 receive the event 

 Event bubbling and capuring are two ways of event propagation in the 
 HTML DOM API, when an event occurs in an element, and both elements 
 have registered a handle for that event.


The Event propagation mide determines in which order the elements recieve 
the event.

🟢 What is Event Bubbling?
With Event Bubbling, the event is first captured and handel by the 
innermost element and then propagated to outer elements.

🟢 What is Event Caputing?
With event capturing, the event first captured by the outermost 
element and propagated to the inner elements.

Capturing is also called 'trickling', which helps remember the 
propagation order.


2️⃣ What is higher order function?

Function which takes another function as an arguments is called HOF
Wo function jo dusre functions ko as an arguments accept karta hai use HOF

3️⃣ Callback Function
Function which get passed as an argument to another function is called CBF

A callback function is a function that is passed as an arguments to 
another function, to be "called back" at a later time.

Jis bhi function ko hum kisi or function ke under as an arguments passed 
karte hai then usko hum callback function bolte hai !

we need to create a calculator

const add = (a,b) => {
    return a+b;
    
}
const sub = (a,b) => {
    return a-b;
}
const mul = (a,b) => {
    return a*b;
}

const calculator = (num1,num2,operator) => {
    return operator(num1,num2);
}

console.log(calculator(2,4,add));


Asynchronus Javascript program :-

const fun2 = () => {
    setTimeout(()=>{
        console.log("function2 is calling");
    },2000);
}

    const fun1 = () => {
        console.log("function 1 is calling");
        fun2();
        console.log("function 1 is calling");
    }

    fun1();


4️⃣ event loop

<---- HOW JAVASCRIPT WORKS AND ASYNCHRONOUS JAVASCRIPT ---->

Hoisting in JavaScript 
Scope Chain
Lexical Scoping in JavaScript 
Use Strict Mode 
This Keyword
Closures in JavaScript
What is Asynchronous JavaScript Programming?
What is Event Loop?

5️⃣5 Hoisting in javascript :-

we have creation phase and ececution phase.

Hoisting in javascript is a mechanism where variables and
functions declearation are moved to the top of their scope 
before the code executed.

for ex.

console.log(myName);
var myName;
myName = "Himanshu";

How it will output during creation phase.

1: var myName;
2: console.log(myName);
3: myName = "Himanshu";

In ES2015 (aka ES6), hoisting is avoided by using the let keyword
instead of var. (The other difference is that variables declared
with let are local to the surrounding block, not the entire function)

6️⃣ What is Scope chain and Lexical Scoping in JavaScript :-

The scope chain is used to resolve the value of variables names in JS

Scope chain in js is lexically defined, which means that we can see
what the scope chain will be by looking at the code.

At the top, we have the Global Scope, which is the window object in
the browser.

Lexical Scoping means now,the inner function can get access to their
parent function variables But the vice-versa is not true

for ex.

let a = "hello guys "; // global scope
 const first = () => {
     let b = "How are you all? "

     const second = () => {
         let c = "i am fine thank u ";
         console.log(a+b+c);
     }
     second();
    //  console.log(a+b+c); // It can't use c
 }

 first();

7️⃣ What is Closures in JavaScript ;-

A closure is the combination of a function bundled together (elclosed)
with references to its surrounfing state (the lexical environment).

In other words, a closure gives you access to an 
outer function's scope from an inner function.

In JavaScript, closure are created every time a function is created,
at function creation time.

for example 


back to advance js ;-

curring

sum(5)(3)(8)

function sum (num1,num2,num3){
    // console.log(num1);
    return function (num2){
        // console.log(num1,num2);
        return function (num3){
            console.log(num1+num2+num3);
        }
    }
}

OR

const sum = (num1) => (num2) => (num3) => console.log(num1+num2+num3);

sum(5)(3)(8);



8️⃣ CallBack Hell :-

setTimeout(() => {
    console.log("Work 1 is done");
    setTimeout(() => {
        console.log("work 2 is done");
        setTimeout(() => {
            console.log("work 3 is done");
            setTimeout(() => {
                console.log("work 4 is done");
                setTimeout(() => {
                    console.log("work 5 is done");
                    setTimeout(() => {
                        console.log("work 6 is done");
                        setTimeout(() => {
                            console.log("work 7 is done");
                            setTimeout(() => {
                                console.log("work 8 is done");
                                setTimeout(() => {
                                    console.log("work 9 is done");
                                    setTimeout(() => {
                                        console.log("work 10 is done");
                                    }, 1000);
                                }, 1000);
                            }, 1000);
                        }, 1000);
                    }, 1000);
                }, 1000);
            }, 1000);
        }, 1000);
    }, 1000);
}, 1000);


9️⃣ AJAX call using XMLHttprequest :-

1️⃣0️⃣ Bonus JSON :-

jSON.stringify turns a javascript object into json text and 
stores that json in a string , eg:

var my_obj = {key_1 : "some Text" , key_2 : true , key_3 : 5};

var object_as_string = JSON.stringify(my_obj);

console.log(object_as_string);

typeof(object_as_string);


JSON.parse turns a string of JSON text into a javascript objecteg :

var object_as_string = JSON.parse(object_as_string);

typeof(object_as_string);