Javascript Notes
Javascript Notes
// console.log(myage);
// Naming Practice
// var _myName = "vinod";
// var 1myName = "thapa";
// var _1my__Name = "bahadur";
// var $myName = "thapa technical";
// var myNaem% = "thapa technical";
// console.log(myNaem%);
// // **********************************************************************
// // **********************************************************************
// // typeof operator
// console.log(typeof(iAmThapas));
// DataTypes Practice
// console.log( 10 + "20");
// 9 - "5"
// console.log( 9 - "5"); //bug
// "Java" + "Script"
// console.log( "Java "+ "Script");
// " " + " "
// console.log( " " + 0);
// " " + 0
// "vinod" - "thapa"
// true + true
// true + false
// false + true
// false - true
// console.log("vinod" - "thapa");
// Interview Question 1
// Difference between null vs undefined?
// var iAmStandBy;
// console.log(iAmStandBy);
// console.log(typeof(iAmStandBy));
// Interview Question 2
// What is NaN?
// console.log(isNaN(myPhoneNumber));
// console.log(isNaN(myName));
// if(isNaN(myName)){
// console.log("plz enter valid phone no");
// }
// NaN Practice 🤯
// console.log(Number.isNaN(NaN));
// Interview Question 1
// var vs let vs const
// console.log(5+20);
1️⃣Assignment operators
//
// An assignment operator assigns 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;
// console.log(3+3);
// console.log(10-5);
// console.log(20/5);
// console.log(5*6);
// Prefix increment operator means the variable is incremented first and then
// the expression is evaluated using the new value of the variable.
3️⃣Comparison operators
//
// A comparison operator compares its operands and
// returns a logical value based on whether the comparison is true.
// var a = 30;
// var b = 10;
// Equal (==)
// console.log(a == b);
// var a = 30;
// var b = -20;
// Logical OR (||)
// The logical OR (||) operator (logical disjunction) for a set of
// operands is true if and only if one or more of its operands is true.
// console.log(!((a>0) || (b<0)));
// console.log(!true);
// // **********************************************************************
// // **********************************************************************
// console.log("Hello World");
// 😳 4 Challenge Time
// What will be the output of 3**3?
// What will be the output, when we add a number and a string?
// Write a program to swap two numbers?
// Write a program to swap two numbers without using third variable?
// sol 1: ✔
// console.log(9**2); // 9*9
// console.log(10 ** -1); 1/10
// sol 2: ✔
// console.log(5 + "thapa");
// sol 3: ✔
// var a = 5;
// var b = 10;
// var c = b; //c = 10
// b = a; // b = 5;
// a = c;
// sol 4: ✔
// var a = 5;
// var b = 10;
// a = a + b; // a = 15
// b = a - b; // b = 5;
// a = a - b; // a = 10;
// Interview Question 4
// What is the Difference between == vs === ?
// sol
// var num1 = 5;
// var num2 = '5';
// console.log(typeof(num1));
// console.log(typeof(num2));
// console.log(num1 == num2 );
// var num1 = 5;
// var num2 = '5';
// console.log(typeof(num1));
// console.log(typeof(num2));
// console.log(num2);
// ************************************************************
// if raining = raincoat
// else no raincoat
// if(tomr == 'rain'){
// console.log('take a raincoat');
// }else{
// console.log('No need to take a raincoat');
// }
// 🤩Challenge Time
// write a program that works out whether if a given year is a leap year or not?
// A normal year has 365 days, leap years have 366, with an extra day in February.
// if(score = 5){
// console.log("OMG, we loss the game 😭");
// }else{
// console.log("Yay, We won the game 😀");
// }
2️⃣
// Conditional (ternary) operator
// if(area == "circle"){
// console.log("the area of the circle is : " + PI*r**2);
// }else if(area == "triangle"){
// console.log("the area of the triangle is : " + (l*b)/2);
// }else if(area == "rectangle"){
// console.log("the area of the rectangle is : " + (l*b));
// }else{
// console.log("please enter valid data");
// }
// switch(area){
// case 'circle':
// console.log("the area of the circle is : " + PI*r**2);
// break;
// case 'triangle':
// console.log("the area of the triangle is : " + (l*b)/2);
// break;
// case 'rectangle':
// console.log("the area of the 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 to the statement following the terminated statement.
// 🤗continue
// Terminates execution of the statements in the current iteration of the
// current or labeled loop, and continues execution of the loop with the
// next iteration.
// var num=20;
// // block scope
// while(num <= 10){
// console.log(num); //infinte loop
// num++;
// }
5️⃣
// Do-While Loop Statement
6️⃣
// For Loop
// output : 8 * 1 = 8
// 8 * 2 = 16(8*2)
// => 8 * 10 = 80
// ************************************************************
1️⃣
// Function Definition
// var a = 10;
// var b = 20;
// var sum = a+b;
// console.log(sum);
// function sum(){
// var a = 10, b = 40;
// var total = a+b;
// console.log(total);
// }
// //
2️⃣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, b = 40;
// var total = a+b;
// console.log(total);
// }
// sum();
// function sum(a,b){
// var total = a+b;
// console.log(total);
// }
// sum();
// sum(20,30);
// sum(50,50);
// sum(5,6)
// // **********************************************************************
// // **********************************************************************
// Interview Question
// Why Functions?
// You can reuse code: Define the code once, and use it many times.
// You can use the same code many times with different arguments,
// to produce different results.
// OR
// function sum(a,b){
// var total = a+b;
// console.log(total);
// }
// function sum(a,b){
// return total = a+b;
// }
6️⃣
// Anonymous Function
// ************************************************************
1️⃣
// LET VS CONST vs VAR
// function biodata() {
// const myFirstName = "Vinod";
// console.log(myFirstName);
// if(true){
// const myLastName = "thapa";
// }
// console.log(myFirstName);
// biodata();
// output : 8 * 1 = 8
// 8 * 2 = 16(8*2)
// => 8 * 10 = 80
// function mult(a,b=5){
// return a*b;
// }
// console.log(mult(3));
// ➡ Array Destructuring 🏁
5️⃣
// Object Properties
// console.log(myBio);
// console.log(myBio);
6️⃣
// Fat Arror Function
// console.log(sum());
// function sum() {
// let a = 5; b = 6;
// let sum = a+b;
// return `the sum of the two number is ${sum}`;
// }
// console.log(sum());
7️⃣
// Spread Operator
// console.log(MyFavColors);
// ES7 features
// 1: array include
// const colors = ['red', 'green', 'blue', 'white', 'pink'];
// const isPresent = colors.includes('purple');
// console.log(isPresent);
// 2: **
// console.log(2**3);
// ES8 Features
// String padding
// Object.values()
// Object.entries()
// // // console.log( Object.values(person) );
// const arrObj = Object.entries(person);
// console.log(Object.fromEntries(arrObj));
// ES2018
// const person = { name: 'Fred', age: 87, degree : "mcs" };
// const sPerson = { ...person };
// console.log(person);
// console.log(sPerson);
// ES2019
// Array.prototype.{flat,flatMap}
// Object.fromEntries()
// ES2020
// #1: BigInt
// console.log(newNum);
// console.log(typeof newNum);
// ES2014
// "use strict";
// x = 3.14;
// console.log(x);
// ************************************************************
// example 🏁
// var myFriends = ['ramesh',22,male,'arjun',20,male,'vishal',true, 52];
1️⃣
✌
//1️⃣Array Subsection 1 Traversal in array
// navigate through an array
// console.log(myFriends[myFriends.length - 1]);
// console.log(myFriends.length);
// Array.prototype.forEach()
// Calls a function for each element in the array.
// 2️⃣
Array Subsection 2 Searching and Filter in an Array
// Array.prototype.indexOf()
// Returns the first (least) index of an element within the array equal
// to an element, or -1 if none is found. It search the element from the
// 0th index number
// console.log(myFriendNames.indexOf("Thapa", 3));
// Array.prototype.lastIndexOf()
// Returns the last (greatest) index of an element within the array equal
// to an element, or -1 if none is found. It search the element last to first
// console.log(myFriendNames.lastIndexOf("Thapa",3));
// Array.prototype.includes()
// Determines whether the array contains a value,
// returning true or false as appropriate.
// console.log(myFriendNames.includes("thapa"));
// Array.prototype.find()
// // **********************************************************************
// Array.prototype.findIndex()
// Array.prototype.filter()
// 3️⃣
Array Subsection 3 How to sort an Array
// Array.prototype.sort()
// console.log(months.sort());
// 1: How to Sort the numbers in the array in ascending (up) and descending (down)
order?
// compareFunction Optional.
// A function that defines an alternative sort order. The function should return a
negative, zero, or positive value, depending on the arguments, like:
// function(a, b){return a-b}
// //Array.prototype.reverse()
// // The reverse() method reverses an array in place.
// // The first array element becomes the last, and
// // the last array element becomes the first.
// 4️⃣
Array Subsection 4 Perform CRUD
// Array.prototype.push()
// The push() method adds one or more elements to the
// end of an array and returns the new length of the array.
// animals.push('chicken', 'cats','cow');
// console.log(animals);
// Array.prototype.unshift()
// The unshift() method adds one or more elements to the
// beginning of an array and returns the new length of the array.
// animals.unshift('chicken', 'cats','cow');
// console.log(animals);
// 2nd example
// myNumbers.unshift(4,6);
// console.log(myNumbers);
// Array.prototype.pop()
// The pop() method removes the last element from an array and returns
// that element. This method changes the length of the array.
// console.log(plants);
// console.log(plants.pop());
// console.log(plants);
// Array.prototype.shift()
// The shift() method removes the first element from an array and returns
// that removed element. This method changes the length of the array.
// Array.prototype.splice()
// Adds and/or removes elements from an array.
// sol1:
// const newMonth = months.splice(months.length,0,"Dec");
// console.log(months);
// sol2:
// console.log(newMonth);
// sol3:
// const months = ['Jan', 'march', 'April', 'June', 'July'];
// if(indexOfMonth != -1){
// const updateMonth = months.splice(indexOfMonth,1,'june');
// console.log(months);
// }else{
// console.log('No such data found');
// }
// sol3:
// const months = ['Jan', 'march', 'April', 'June', 'July'];
// const indexOfMonth = months.indexOf('April');
// if(indexOfMonth != -1){
// const updateMonth = months.splice(indexOfMonth,2);
// console.log(months);
// console.log(updateMonth);
// }else{
// console.log('No such data found');
// }
// 5️⃣
Array Subsection 4 Map and Reduce Method
// Array.prototype.map()
// // **********************************************************************
// // **********************************************************************
// 😀9: challenge Time 🏁
// sol1:
// let arr = [25, 36, 49, 64, 81];
// sol 2:
// let arr = [2, 3, 4, 6, 8];
// 👉 Reduce Method
// Accumulator
// Current Value
// Current Index
// Source Array
// 4 subj = 1sub= 7
// 3dubj = [5,6,2]
// console.log(arr.flat(Infinity));
// console.log(flatArr);
// console.log(myName);
// console.log((ytName));
// let anySentence = "We are the so-called \"Vikings\" from the north.";
// console.log(anySentence);
// let anySentence = " We are the so-called 'Vikings' from the north. ";
// console.log(anySentence);
// String.prototype.indexOf(searchValue [, fromIndex])
// The indexOf() method returns the index of (the position of) the first
// occurrence of a specified text in a string
// // String.prototype.lastIndexOf(searchValue [, fromIndex])
// // Returns the index within the calling String object of the
// // last occurrence of searchValue, or -1 if not found.
// String.prototype.search(regexp)
// slice(start, end)
// substring(start, end)
// substr(start, length)
// let myTweets = "Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s, when an unknown printer took a galley of type and scrambled it to
make a type specimen book. It has survived not only five centuries, but also the
leap into electronic typesetting, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it?
";
// String.prototype.replace(searchFor, replaceWith)
// Points to remember
// 1: The replace() method does not change the string
// it is called on. It returns a new string.
// 2: By default, the replace() method replaces only
// the first match
// 3:By default, the replace() method is case sensitive.
// Writing VINOD (with upper-case) will not work
// charAt(position)
// charCodeAt(position)
// Property access [ ]
// console.log(str.charAt(9));
// console.log( str.charCodeAt(0) );
// Property Access
// ECMAScript 5 (2009) allows property access [ ] on strings
// console.log(fName + lName );
// console.log(`${fName} ${lName}`);
// console.log(fName.concat(lName));
// console.log(fName.concat(" " ,lName));
// String.trim()
// The trim() method removes whitespace from both
// sides of a string
// new Date()
// new Date(year, month, day, hours, minutes, seconds, milliseconds)
// // it takes 7 arguments
// new Date(milliseconds)
// // we cannot avoid month section
// new Date(date string)
// new Date()
// Date objects are created with the new Date() constructor.
// 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 GMT+0700
(GMT+07:00)
// Date.now()
// Returns 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(dateString)
// new Date(dateString) creates a new date object from a date string
// new Date(milliseconds)
// new Date(milliseconds) creates a new date object as zero time plus milliseconds:
// console.log(curDate.setFullYear(2022));
// // The setFullYear() method can optionally set month and day
// console.log(curDate.setFullYear(2022, 10, 5));
// let setmonth = curDate.setMonth(10); // 0-11 jan to dec
// console.log(setmonth);
// console.log(curDate.setDate(5));
// console.log(curDate.toLocaleString());
//👉 Time Methods
// console.log(curTime.getTime());
// // // The getTime() method returns 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());
// // console.log(curTime.setTime());
// console.log(curTime.setHours(5));
// console.log(curTime.setMinutes(5));
// console.log(curTime.setSeconds(5));
// console.log(curTime.setMilliseconds(5));
// // Practice Time
// new Date().toLocaleTimeString(); // 11:18:48 AM
// //---
// new Date().toLocaleDateString(); // 11/16/2015
// //---
// new Date().toLocaleString(); // 11/16/2015, 11:18:48 PM
// The JavaScript Math object allows you to perform mathematical tasks on numbers.
// console.log(Math.PI);
// console.log(Math.PI);
// Math.round()
// returns the value of x rounded to its nearest integer
// Math.pow()
// Math.pow(x, y) returns the value of x to the power of y
// console.log(Math.pow(2,3));
// console.log(2**3);
// Math.sqrt()
// Math.sqrt(x) returns the square root of x
// console.log(Math.sqrt(25));
// console.log(Math.sqrt(81));
// console.log(Math.sqrt(66));
// 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));
// console.log(Math.abs(4-6));
// Math.ceil()
// Math.ceil(x) returns the value of x rounded up to its nearest integer
// console.log(Math.ceil(4.51));
// console.log(Math.round(4.51));
// console.log(Math.ceil(99.01));
// console.log(Math.round(99.1));
// Math.floor()
// Math.floor(x) returns the value of x rounded down to its nearest integer
// console.log(Math.floor(4.7));
// console.log(Math.floor(99.1));
// Math.min()
// Math.min() can be used to find the lowest value in a list of arguments
// Math.max()
// Math.max() can be used to find the highest value in a list of arguments
// Math.random()
// Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)
// console.log(Math.floor(Math.random()*10));
// console.log(Math.floor(Math.random()*10)); // 0 to 9
// Math.round()
// The Math.round() function returns the value of a number
// rounded to the nearest integer.
// console.log(Math.round(4.6));
// console.log(Math.round(99.1));
// Math.trunc()
// The trunc() method returns the integer part of a number
// console.log(Math.trunc(4.6));
// console.log(Math.trunc(-99.1));
// Practice Time
1️⃣
// whereas the DOM is the child of Window Object
// // **********************************************************************
// // **********************************************************************
// For example
// 👉 window.screen or just screen is a small information
// object about physical screen dimensions.
// 👉 window.location giving the current URL
// 👉 window.document or just document is the main object
// of the potentially visible (or better yet: rendered)
// document object model/DOM.
// Now, I know you have a doubt like we have seen the methods
// and object of the global object that is window. But What about
// the properties of the Window Object 🤔
// 👉 The DOM is the Document Object Model, which deals with the document,
// the HTML elements themselves, e.g. 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 others that vary by browser). OR
// In simple meaning all the Window operations which comes under BOM are performed
// usign BOM
3️⃣
// Section : Navigate through the DOM
// 1: document.documentElement
// returns the Element that is the root element of 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
// 👉 Practice Time
// How to check whether an element has child nodes or not?
// we will use hasChildNodes()
// 👉 Practice Time
// How to find the child in DOM tree
// firstChild vs firstElementChild
// lastChild vs lastElementChild
// const data = document.body.firstElementChild;
// undefined
// data
// data.firstElementChild
// data.firstElementChild.firstElementChild
// data.firstElementChild.firstElementChild.style.color = "red"
// vs
// document.querySelector(".child-two").style.color = "yellow";
// **********************************************************************
// HTML Events
// An HTML event can be something the browser does, or something a user does.
1️⃣
// section 4 ways of writing Events in JavaScript
2️⃣
// section : What is Event Object?
// Event object is the parent object of the event object.
// for Example
// MouseEvent, focusEvent, KeyboardEvent etc
3️⃣
// section ️ MouseEvent in JavaScript
// The MouseEvent Object
// Events that occur when the mouse interacts with the HTML
// document belongs to the MouseEvent Object.
4️⃣
// section ️ KeyboardEvent in JavaScript
// Events that occur when user presses a key on the keyboard,
// belongs to the KeyboardEvent Object.
// https://www.w3schools.com/jsref/obj_keyboardevent.asp
5️⃣
// Section InputEvents in JavaScript
// The onchange event occurs when the value of an element has been changed.
// For radiobuttons and checkboxes, the onchange event occurs when the
// checked state has been changed.
// **********************************************************************
// **********************************************************************
// setTimeout(function, milliseconds)
// Executes a function, after waiting a specified number of milliseconds.
// setInterval(function, milliseconds)
// Same as setTimeout(), but repeats the execution of the function continuously.
1️⃣
// setTimeout()
2️⃣
// clearTimeout()
3️⃣
// setInterval()
4️⃣
// clearInterval()
// **********************************************************************
// **********************************************************************
1️⃣
// What is Object Literal?
// 1st way
// let bioData = {
// myName : "thapatechnical",
// myAge : 26,
// getData : function(){
// console.log(`My name is ${bioData.myName} and my age is $
{bioData.myAge}`);
// }
// }
// bioData.getData();
// let bioData = {
// myName : "thapatechnical",
// myAge : 26,
// getData (){
// console.log(`My name is ${bioData.myName} and my age is ${bioData.myAge}`);
// }
// }
// bioData.getData();
// let bioData = {
// myName : {
// realName : "vinod",
// channelName : "thapa technical"
// },
// myAge : 26,
// getData (){
// console.log(`My name is ${bioData.myName} and my age is ${bioData.myAge}`);
// }
// }
// console.log(bioData.myName.channelName );
2️⃣
// What is this Object?
// The this object can have different values depending on where it is placed.
// // For Example 1
// console.log(this.alert('Awesome'));
// // it refers to the current context and that is window global object
// // ex 2
// function myName() {
// console.log(this);
// }
// myName();
// // ex 3
// // ex 4
// const obj = {
// myAge : 26,
// myName() {
// console.log(this.myAge);
// }
// }
// obj.myName();
// // ex 5
// // this object will not work with arrow function bcz arrow function is bound to
class.
// const obj = {
// myAge : 26,
// myName : () => {
// console.log(this);
// }
// }
// obj.myName();
// // ex 6
// let bioData = {
// myName : {
// realName : "vinod thapa",
// channelName : 'thapa technical'
// },
// // things to remember is that the myName is the key and the object is act
like a value
// myAge : 26,
// getData (){
// console.log(`My name is ${this.myName.channelName} and my age is $
{this.myAge} `);
// }
// }
// bioData.getData();
// // But as per other it is simply the way to use the this keyword or another
object
// // **********************************************************************
// // **********************************************************************
1️⃣
// // : Event Propagation (Event Bubbling and Event Capturing)
2️⃣
// // : Higher Order Function
// // function which takes another function as an arguments is called HOF
// // wo function jo dusre function ko as an argument accept krta 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 argument to
// // another function, to be “called back” at a later time.
// calculator(5,2,subs)
// console.log(calculator(5,2,subs));
// console.log(calculator(5,6,add));
// console.log(calculator(5,6,subs));
// console.log(calculator(5,6,mult));
// // and add, sub and mult are called the callback function bcz they are passed
// // as an argument to another fucntion
// // InterView Question
// // Difference Between Higher Order Function and Callback Function ?
// // 🏁🏁Asynchronous JavaScript
6️⃣
// // : Synchronous JavaScript Prog
// 1work = 10min
// 2work = 5s
2️⃣
// const fun2 = () => {
// console.log(`Function is called`);
// }
// fun1();
2️⃣
// setTimeout(()=> {
// console.log(`Function is called`);
// }, 2000);
// }
// fun1();
5️⃣
// // Hoisting in JavaScript
// For Example 👇
// console.log(myName);
// let myName;
// myName = "thapa";
// //😲 In ES2015 (a.k.a. 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 variable names
// // in JS.
// // 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 functions variables But the vice-versa is not true.
// // For Example 👇
// first();
// // 7️⃣
What is Closures in JavaScript
// // For Example 👇
// "use strict"
// let x = "vinod";
// console.log(x);
// Currying
// sum(5)(3)(8);
// // **********************************************************************
// // **********************************************************************
8️⃣
// // : CallBack Hell
// setTimeout(()=>{
1️⃣
// console.log(` works is done`);
// setTimeout(()=>{
2️⃣
// console.log(` works is done`);
// setTimeout(()=>{
3️⃣
// console.log(` works is done`);
// setTimeout(()=>{
4️⃣
// console.log(` works is done`);
// setTimeout(()=>{
5️⃣
// console.log(` works is done`);
// setTimeout(()=>{
6️⃣
// console.log(` works is done`);
// }, 1000)
// }, 1000)
// }, 1000)
// }, 1000)
// }, 1000)
// }, 1000)
// // **********************************************************************
// // 👉 // 🤩 Bonus JSON 🤩
// // **********************************************************************
// console.log(object_as_string);
// typeof(object_as_string);
// "string"
// typeof(object_as_string_as_object);
// // "object"
7️⃣
// // AJAX Call using XMLHttprequest