notes Available at :
Column1
Console.log():-
Console.table ():-
Console.assert():-
Console.warn():-
Console.clear():-
Console.time() and
Console.timeEnd():-
Console.error():-
Console.count():
Console.group() and
Console.groupEnd():-
https://www.codewithharry.com/videos/javascript-tutorials-in-hindi-2
Column2
console.time('Your code Took');
console.log('Hello console');
console.log(4+34);
console.log(34);
console.log(true);
console.log([34,2,1,2]);
console.log({harry: 'this', marks:34});
console.table({harry: 'this', marks:34});
console.warn('This is a warning');
// console.clear();
console.timeEnd('Your code Took');
// console.assert(566<189, 'Age >189 is not possible')
// console.error('This is an error'
https://www.w3schools.com/Jsref/tryit.asp?filename=tryjsref_namednodemap_getnameditem
Access Attribute value of button
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get the value of the onclick attribute of the button element.</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> Internet Explorer 8 and earlier does not support the getNamedItem
method.</p>
<p id="demo"></p>
<script>
function myFunction() {
var a = document.getElementsByTagName("BUTTON")[0];
var x = a.attributes.getNamedItem("onclick").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Column1
here it will return myFunction which is the value of
onlick attribute of BUTTON[0]
Creating , Removing , replacing element
Differenc
e
between
append
append and
append
child
https://de
v.to/ibn_
abubakre
/append-
vs-
appendch
ild-a4m
appendChild
createElement('li')
element.id=
element.className=
element.setattribute()
parent.appendChild(element)
parent.append(element)
createTextNode('mytext')
element1.replaceWith(element2)
parent.replaceChild(child1, child2)
parent.removeChild(childNode)
element.hasAttribute('href')
console.log(parent.childNodes)
console.log(element.textContent) // "Some text"
.childnodes[0].childnodes[1]
in Body tag, \n(enter) is a text node under an element
https://www.codewithharry.com/videos/javascript-tutorials-in-hindi-16
Removing , replacing element
Column1 Column2
console.log('this is tut 16');
let element = document.createElement('li');
let text = document.createTextNode('I am a text node');
element.appendChild(text)
// Add a class name to the li element
element.className = 'childul';
element.id = 'createdLi';
element.setAttribute('title', 'mytitle');
// element.innerText = '<b>Hello this is created by harry</b>';
// element.innerHTML = '<b>Hello this is created by harry</b>';
let ul = document.querySelector('ul.this');
ul.appendChild(element);
// console.log(ul)
// console.log(element)
let elem2 = document.createElement('h3');
elem2.id = 'elem2';
elem2.className = 'elem2';
let tnode = document.createTextNode('This is a created node for elem2');
elem2.appendChild(tnode);
element.replaceWith(elem2);
let myul = document.getElementById('myul');
myul.replaceChild(element, document.getElementById('fui'));
myul.removeChild(document.getElementById('lui'));
let pr = elem2.hasAttribute('href');
elem2.removeAttribute('id');
elem2.setAttribute('title', 'myelem2title');
console.log(elem2, pr);
// quick quiz
// create a heading element with text as "Go to CodeWithHarry" and create an a tag o
initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="container">
<h1 id="heading"> Welcome to Code With Harry</h1>
<div id="myfirst" class="child red good"
id="first">child 1
<ul class="this">
<li class="childul">this</li>
<li class="childul">is</li>
<li class="childul">a</li>
<li class="childul">list </li>
<li class="childul">of my dreams</li>
</ul>
</div>
<div class="child">child 2</div>
<div class="child red">child 3</div>
<div class="child">child 4</div>
<form action="none.html" method="post">
<a href="//codewithharry.com">Go to Code With
Harry</a>
<br>
<br>
Search this website: <input type="text"
name="Hello" id="">
<input type="button" value="submit">
</form>
</div>
<br>
<div class="no">this is a dummy div1</div>
<div class="no">this is a dummy div2</div>
<div class="no">this is a dummy div3</div>
</body>
Column3 Column4 Column5
or elem2');
" and create an a tag outside it with href = "https://www.codewithharry.com"
Column1
Difference between append() and appendChild()
Difference between for-in and for-of and for-each?
difference between es5 and es6 in javascript
What is Constructor
Difference between map ,filter and reduce
Difference between map() and foreach()
Column2
https://dev.to/ibn_abubakre/append-vs-appendchild-a4m
for-in is used to get the index of each element of array, and for -of
is used to get the elements of array
https://www.geeksforgeeks.org/difference-between-es5-and-es6/
Constructor is a function to create an object,
ex. When we declare an array and iitialise it. It call a function
function Array()
If try filter using map, will return using true or false for each
element of array
on the other hand we can filter out data using filter function
Column3 Column4 Column5
https://www.w3schools.com/jsref/jsref_constructor_array.asp
https://www.javatpoint.com/javascript-array
concat
constructor
copyWithIn
entries
every
some
fill
filter
First index satisfying condition of find find
findIndex
Joins the elements of
indexof each element
reduceRight()
https://www.w3schools.com/jsref/jsref_length_array.asp
Column1
arr3 = arr1.concat(arr2)
arrayName.constructor
array.copyWithIn(target,start,end)
The array.entries() method returns an Array Iterator object with key/value pairs.
array.every(myfun)
myfun(value){return value>18 }
some elements of array must fullfil condition
array.fill('myvalue')
array.filter(()=>)
array.find(()=> )
array.findIndex((n)=>n>4)
array.forEach(()=>{} )
Array.from(arr1).filter(n=>n>7)
array.includes(myvalue)
array.indexOf('apple')
Array.isArray(ArrayName)
array.join('And')
array.keys()
array.length
array.lastIndexOf('mystring')
array.pop()
prototype
array.reduce((accumulator, currentvalue)=> accumulator +currentvalue)
array.reduceRight((acc,currentVal )= >currentVal -acc}
array.reverse()
removes the first element of the array
array.slice(start, end)
array.sort((a,b)=>a-b)
array.splice(index, howmany_toRemove, item1, ....., itemX)
array.toString()
array.unshift('item1','item2')
Arr = []
Str = 'mynameis rakesh'
for (i in Str) {
Arr.push(Str[i])
}
console.log(Arr)
<script>
var array = [1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8];
console.log("Before filtering non unique values: " + array);
var unique = array.filter((value, index) => {
return array.indexOf(value) === array.lastIndexOf(value);
});
console.log("After filtering non unique values: " + unique);
</script>
var array = [1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8];
arr2 = new Set(array) // new Set
arr3 = (Array.from(arr2)) // create an array from Set
arr=[5,10,15,20,25,30]
console.log(Math.max(…arr))
arr=[5,10,15,20,25,30]
console.log(arr.sort((a,b)=>{return b-a}))
Column2 Column3
arr3 = arr1.concat(arr2)
function Array() { [native code] }
arr = ['ab', 'cd', 'ef']
for (i in arr) console.log(arr.entries().next().value)
const ages = [32, 33, 16, 40];
ages.every(checkAge) // Returns false
function checkAge(age) {
return age > 18;
}
ages.some((el,indx)-> el>30} 1
each element is replaced with myvalue
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr2 = []
arr2 = arr.filter((num) => num > 4)
console.log(arr2)
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr2 = []
arr2 = arr.find((n) => n > 3.2)
console.log(arr2)
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr2 = []
arr2 = arr.findIndex((n) => n > 4)
console.log(arr2)
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr2 = []
arr2 = Array.from(arr).filter((n) => n > 7)
console.log(arr2)
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(arr.includes(8)) //true
console.log(arr.includes(12)) //false
returns index of first occurance
const fruits = ["Banana", "Orange", "Apple", "Mango"];
Array.isArray(fruits) // Returns true
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.join(" and ");
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();
for (let i of keys) console.log(i)
returns lngth of array
returns index of last occurance of cretaria meet
https://www.w3schools.com/jsref/jsref_prototype_array.asp
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
console.log(array.reduce((accumulator, currentvalue) =>
accumulator + currentvalue))
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
var array = [1, 2, 2, 3, 4, 5, 46, 16,
27, 8, 18, 8];
array.sort((a, b) => a - b)
console.log(array)
replace original array
at index position, will remove(if any) and add items
The Array.toString() method returns a string with all
array values separated by commas:
push at the beginning of array
String is an array of characters
to get Unique values seprately
Get Unique values from array
Get Maximum of array
using Math.max and spread array
Get Maximum of array using sort
typeof and instance of
constructor
type of is for primitive data type
instanceof is for object data type
Column1
function fun(a, b, c) {
this.name = a;
this.id = b;
this.position = c;
}
obj = new fun('rakesh', 96643, 'developer')
console.log(obj instanceof fun)
console.log(obj instanceof Object)
typeOf('rakesh')
ect data type
Column2 Column3 Column4 Column5
returns true
returns true
String
Column1
Create Object Method 1
Create Object Method2
Create Object Method 3
Create Object method4
method 5
Singleton
Create Object pattern:
Get number of Keys of object
traversing of entries of Object
arguments object
Make first character capital
Column2 Column3
var myobj ={}
var myobj = new Object()
Function myobj(a,b) {this.name=a,this.id=b}
obj1 = new myobj('rakesh',96643)
console.log(obj1.name)
console.log(obj1.id)
class myobj {
constructor(a, b) {
this.name = a;
this.id = b
}
get nm() { return this.name }
}
obj2 = new myobj('rakesh', 96643)
console.log(obj2.name)
var obj = new function(){
this.name='rakesh'
}
console.log(Object.entries(obj).length)
for(key in obj) console.log(obj[key])
function fun() {
for (key in arguments) console.log(arguments[key])
}
fun(1, 2, 3, 'a')
console.log(str.charAt(0).toUpperCase() + str.slice(1))
Column4
onstorage event
window.onstorage = function(e) {
console.log('The ' + e.key +
' key has been changed from ' + e.oldValue +
' to ' + e.newValue + '.');
};
OR
window.addEventListner('storage',function(e) {console.log(e.key, e.oldValue, e.ne
ole.log(e.key, e.oldValue, e.newValue)}
Get width and height of image in JS
and height of image in JS
HTML
<div class="container">
<img
src="https://i.pcmag.com/imagery/reviews/03aizylUVApdyLAIku1AvRV-
39.1605559903.fit_scale.size_760x427.png" alt="" srcset="">
</div>
JS CONSOLE
function myfun() {
console.log("hello2")
var mycont = document.getElementsByClassName('container')
var myimage = mycont[0].getElementsByTagName('IMG')
console.log(myimage[0])
var width_ = myimage[0].clientWidth
var height_ = myimage[0].clientHeight
console.log(width_)
}
Column4 Column5
Column1
String to Title case
first character to upp
Column2
var str = "foo bar baz"
console.log(
str.split(' ')
.map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
.join(' ')
)
console.log(str.charAt(0).toUpperCase() + str.slice(1))
Column3 Column4 Column5
var str = 'rakesh ahuja'
console.log(str.split(' ').map((el, inx, arr) => el.charAt(0).toUpperCase() +
el.slice(1).toLowerCase()).join(' '))
Column6
function sum(...args) {
let accum = 0;
for (i in args) {
accum += args[i];
}
return accum;
}
console.log(sum(1, 2, 3))
console.log(sum(1, 2, 3, 4))
console.log(sum(1, 2, 3, 4, 5))
When Numbers of arguments are not fixed, then we use rest parameters with … (dot dot dot)
or another syntax below
function sum(...args) {
return args.reduce((acc, el, ind, arr) => { return acc + el }, 0)
}
console.log(sum(1, 2, 3))
console.log(sum(1, 2, 3, 4))
console.log(sum(1, 2, 3, 4, 5))
var url = new URL('https://reqres.in/api/products/3?a=3&b=2&c=8&a=9')
var params = new URLSearchParams(url.search)
console.log(params.get('b')) //2
console.table(params.getAll('a')) //["3","9"]
console.log(params.has('c')) //true
console.log(params.append('d', 5))
console.log(params.get('d'))
console.log(...params.keys())
console.log(...params.values())
<div id="outer" style="border: 1px solid
#ff0000;padding:14px">
<ul id="ulid">
<li id="liid1">1</li>
<li id="liid2">2</li>
<li id="liid3">3</li>
<li id="liid4">4</li>
<li id="liid5">5</li>
<li id="liid6">6</li>
<li id="liid7">7</li>
<li id="liid8">8</li>
<li id="liid9">9</li>
</ul>
</div>
var outer = document.getElementById('outer')
outer.addEventListener('click', (e) => {
var target = (e.target.id)
window.location.href = '/' + target
})
var mypromise = new Promise((resolve, reject) => {
let error = false great
if (!error) {
resolve('great');
} else { reject('error'); }
});
mypromise.then((msg) => console.log(msg)).catch((err) => { console.log(err) })
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'One'); (3) ["One", "two", "three"]
});
const promise2 = new Promise((resolve, reject) => { Promise is fullfilled when all the pomises are resolved, then values
setTimeout(resolve, 100, 'two'); are accumulated in value of then
});
const promise3 = new Promise((resolve, reject) => { If any one promise is rejected , then overall it is not fullfilled
setTimeout(resolve, 100, 'three');
});
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values);
});
const promise1 = new Promise((resolve, reject) => setTimeout(resolve, 100,
'quick'));
const promise2 = new Promise((resolve, reject) => setTimeout(resolve, 200, 'ok'));
const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 500, 'slow'));
const promises = [promise1, promise2, promise3];
Promise.any(promises).then((value) => console.log(value)).catch(err=>) all are resolved with 'any'
const promise1 = new Promise((resolve, reject) => setTimeout(reject, 100, 'quick'));
const promise2 = new Promise((resolve, reject) => setTimeout(resolve, 200, 'ok'));
const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 500, 'slow'));
const promises = [promise1, promise2, promise3];
one promise is reject with 'any'
Promise.any(promises).then((value) => console.log(value)); still Promise is fullfilled.
let x = 8
function fun(x) {
var element = 0
Prime factors label1: for (let i = 2; i < x; i++) {
element = (x % i)
if (element == 0) return ('not prime')
}
return ('prime')
}
function factors(x) {
const arr = []
arr.push(0, 1, 1)
console.log(arr)
for (let i = 0; i < 5; i++) {
Fibonacci series let a;
let b;
a = Number(arr.slice(arr.length - 2, arr.length - 1))
b = Number(arr.slice(arr.length - 1, arr.length))
let c = a + b
console.log(c)
arr.push(c)
}
console.log(arr)
let a = 32
let b = 28;
let m = Math.min(a, b)
HCF
const arr = []
for (let i = 2; i <= m/2; i++) {
if ((!(a % i)) && (!(b % i))) arr.push(i)
}
console.log(Math.max(...arr))
arr1 = [3, 5, 1, 2, 8, 9, 7, 1]
Merge and Sort array arr2 = [13, 25, 11, 12, 18, 19, 27, 11]
let arr3 = arr1.concat(arr2)
arr3.sort((a, b) => a - b)
console.log(arr3)
let x = 5;
let y = 7;
Swap two numbers without using third number x = x + y;
y = x - y;
x = x - y;
console.log(x, y)
reverse a string STR = 'rakesh'
console.log((Array.from(STR).reverse()).join(''))
reverse the words in string myword = 'My name is rakesh'
console.log(myword.split(' ').reverse().join(' '))
str = 'rakeshahuja'
get unique characters from a string let set1 = new Set(Array.from(str))
console.log(Array.from(set1).join(''))
check if string is palindrom str = 'momom'
console.log((str.split('')).reverse().join('') === str)
let a = 5;
random number between 5 and 7 let b = 7;
console.log(Math.round(a + (b - a) * Math.random()))
arr = [4, 2, 5, 7, 8, 9, 11, 12]
arr.sort((a, b) => a - b)
const arr2 = []
for (let i = 1; i <= arr[arr.length - 1]; i++) {
if (arr.includes(i)) continue
else arr2.push(i)
}
console.log(arr2)
check missing numbers in an array
arr = [1, 2, 3, 4, 5, 0]
get sum of largest two numbers of array let largest = Math.max(...arr)
let second = (arr.sort((a, b) => b - a))[1]
console.log(largest + second)
n = 1000
arr = []
for (let i = 1; i <= n; i++) {
count number of zeroes from 1 to n let x = ((i.toString()).split('')).filter((el, indx) => el == "0")
// console.log(x)
if (x.includes("0")) arr.push(x)
}
console.log(arr.length)