Variables in JS :-
var a = 4;
var b = 3;
var z = a + b;
console.log(z);
operators in JS:-
let x = 4;
let y = 4;
let yes = "not equal";
let no = "equal";
if (x!=y) {
console.log(yes);
}else{
console.log(no);
}
Data Types :-
let x = 5 + "5";
console.log(x);
PROMT,CONFIRM AND ALERT :-
pompt :-
let age = prompt("Enter your age" , 20);
if(age!= null){
document.write("your age is " + age );
}else{
document.write("age filled was blanked")
}
confirm :-
let response = confirm("Are you sure , you want to delete?")
if(response == true){
document.write("deleted")
}else{
document.write("not deleted")
}
TYPE CONVERSION :-
let a = 5;
console.log(typeof(a));
1: String()
2: Number()
3: Boolean()
1
let type = 4;
console.log(typeof(4));
let newType = String(type);
console.log(typeof(newType));
2
let bool = true;
console.log(typeof(bool));
let newBool = String(bool);
console.log(typeof(newBool));
STRING MANUPULATION :-
let str = "himanshu kumar tiwari";
if("Himanhu" == str){
console.log("equal");
}else{
console.log("not equal");
}
ARRAY :-
let subject = ["Math","English"]
add element in last then use push() Methode :-
subject.push("Hindi");
console.log("Hindi is added at last");
console.log(subject);
add element in first then use unshift Method() :-
subject.unshift("Physics");
console.log("Physics is added at first")
console.log(subject);
remove element from last then use pop() Method :-
subject.pop();
console.log("Hindi is removed")
console.log(subject);
remove element from first shift() Method() :-
subject.shift();
console.log("Physics is removed");
console.log(subject);
If you want to remove specific element then use Splice()
Mehtod :-
let someNames = ["Himanshu" , "Aditya" , "Sohan" , "Mohan"];
someNames.splice(1,1);
console.log(someNames);
If you want to find element in array then use
indexOf() method :-
if it find something then it returns that index number
otherwise it return -1
let color = ['green','black','red','yellow'];
let position = color.indexOf("red");
console.log(position);
Check array or not then use Array.isArray() Method:-
if it right it returns True otherwise false .
ex.
let word1 = "Car";
console.log(Array.isArray(word1));
let word2 = ["car",'Bike'];
console.log(Array.isArray(word2));
If you want to change any sentence in Array then use split() Method :-
let text = "This is a simple text";
let wordArray = text.split(' ')
console.log(wordArray);
If you want to join any array like a sentence the use join() Method :-
let color = ['green','black','red','yellow'];
let joinWord = color.join(' ');
console.log(joinWord);
How to add two or more than array into eachother?
use concate() Method :-
let color1 = ['green','black','red','yellow'];
let color2 = ['orange','purple','white','pink'];
let car1 = ['Harrier','Safari','Creta','Seltos'];
let car2 = ['altroz','City','nexon','Fortuner'];
let newColorAndCar = color1.concat(color2,car1,car2);
console.log(newColorAndCar);
<----:Multi-Dimensional Array :---->
Normal Array :-
let book = ['Math','Physics','Bio'];
console.log(book);
Multi-Dimensional Array :-
let bookWithPages = [
['Maths','200'],
['Physics','500'],
['Biology','800']
];
console.log(bookWithPages);
If you want perticular array output then u can use
indexes of multi-Dimensional arrays
ex.
let fetch = bookWithPages[1][0];
console.log(fetch);
<----: LOOP THROUGH AN ARRAY :---->
navigatate trough Loops in Arrays :-
ex 1
let friendName = ["Himanshu","Vivek","Aman","Rohit","Sanju"];
let findLength = friendName.length;
console.log(findLength);
for(i=0; i<findLength; i++){
console.log(`Element ${i} is ${friendName[i]}\n`);
}
eg 2.
let number = [1,2,4,5,767,45,6,435,45,345,34,534,5,456,34,64,7,6,3467,456,467,567,567,567,3467,457,3467,4567,45,745,745,7,];
let lengthOfNumbers = number.length;
for(let i=0; i < lengthOfNumbers; i++){
console.log(`Number ${i} is ${number[i]}`)
}
Q. print the table of 2 using for loop ;-
for(let i = 1; i <= 10 ; i++){
tableOf = 2;
console.log(`${tableOf} x ${i} = ${tableOf * i} `);
}
for each ()
let book = ["Math","Science","Chemistry"];
book.forEach(myFun);
function myFun(value){
console.log(value);
}
<----: FUNCTION :---->
function myName (namee,message){
return `My name is ${namee} and i want to ask that ${message}`
}
console.log(myName("Himanshu"," How are you?"));
function mulTable (){
for(let i = 1 ; i <=10; i++){
console.log(`2 x ${i} = ${2*i}`);
}
}
console.log(mulTable());
Parameter , Arguments in function :-
make a program for multiple tables !!
function tableMul (number){
for(let i = 1; i <= 10; i++){
console.log(`${number} x ${i} = ${number * i}`);
}
}
tableMul(5);
Made by me !!
function tableOf (num){
for(let i = 1; i<=10;i++){
console.log(`${num} x ${i} = ${num*i} `);
}
}
tableOf(window.prompt(document.write(tableOf())));
add two number
function sum (num1 , num2){
console.log(num1+num2);
}
sum(12,12)
Add, sub,mul any number with so many arguments .
function add() {
if (arguments.length == 0) {
console.log("Paramenter is empty");
} else {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum = sum + arguments[i];
}
console.log(sum);
}
}
add(-12,1)
make a function that can add any number (not specific parameter num) :-
function addition () {
if(arguments.length==0){
console.log("Please enter any number ");
}else{
let sum = 0;
for (let i = 0; i < arguments.length; i++){
sum = sum + arguments[i]
}
console.log(sum);
}
}
console.log(addition(12,3));
// insert number here :-
addition(1,2,3,4,5,6,7,8,9,10);
return in function :-
function add (a,b){
return a+b;
}
console.log(add(12,1));
GLOBAL VARIABLE AND LOCAL VARIABLE :-
we can't use local variable in outside of its parent.
but we can use global variable anywhere.
let car = "audi" // Global Variable
function add (){
let result = 33; // Local Variable
console.log(car); // This is right
}
console.log(result); // this is wrong
add();
Anonymous Function :-
Function expression
let myName = function (){
console.log("Hello world");
}
myName()
function message (){
console.log("Hello world");
}
setTimeout(message, 3000);
anonymous function is used when u need to call soemthing only once.
eg
setTimeout(function (){
console.log("Hello World");
},3000)
Immediately invoked function
WE can use it if we want to avoide by error with same name
for other code !
(function (){
console.log("Hello world !");
})();
<----: OBJECT :---->
let person = {
firstName : "Himanshu",
lastName : "Tiwari",
myAge : 19
};
✳ we can acces object by using dot(.) notation or array notation .
Note! if we use array notation then we need to use ("") .
console.log(person.firstName);
console.log(person['lastName']);
✳ how to change property in object?
person.firstName = "Aditya"
console.log(person.firstName);
✳ how to delete property from object ?
delete person.myAge
console.log(person);
✳ how to find any property in object?
there are two methods to find any peroperty in obj
1.
console.log(person.height);
if it return undefined then it means that property isn't
aviablable in object.
2. //in
console.log('height' in person);
If your property aviablable in that property or not.
it always returns you in true or in false value.
✳ how to iterate(ghumna) property of an object?
we can iterate every property of an object using for in loop.
eg.
for (let key in person){
console.log(`${key} : ${person[key]}`);
}
Methods :-
let person = {
firstName : "Himanshu",
lastName : "Tiwari"
}
1st method
person.sayHello = function(){
console.log("Hello world");
}
person.sayHello();
2nd mehtod.
function greet (){
console.log("Hello");
}
person.sayHello = greet;
person.sayHello();
<----: This Keyword :---->
let person = {
firstName : "Himanshu",
secondName: "Kumar",
lastName: "Tiwari",
sayHello(){
console.log("Hello ! i am " + this.firstName + " and i have a " + car.brand + " car ");
}
};
let car = {
brand : "Tata",
model : "Safari"
}
person.sayHello();
<----: MATH OBJECT :---->
var x =10;
console.log(Math.random(x)*10)
<----: new Keyword :---->
var person = {
name : "Himanshu",
age : 19
}
<----: NEW :---->
var person = new Object();
person.name = "Himanshu kumar";
console.log(person.name);
<----: OBJECT CONSTRUCTER :---->
function Student (first , last , age , cls){
this.firstName = first;
this.lastName = last;
this.age = age;
this.class = cls;
}
var student1 = new Student("Himanshu","Tiwari",19,12);
var student2 = new Student("Priyanshu","Tiwari",29,12);
var student3 = new Student("Sriyanshu","Jaiswal",19,12);
var student4 = new Student("Mahesh","Tiwari",19,12);
add something after :-
student1.nationality = "Indian"
console.log(student1);
<----: Nested object :---->
object inside an object
let user = {
id: 123,
email: "abc@gmail.com",
personalInfo: {
name: "abc",
address: {
street : "abc",
city : "Delhi",
country : "india",
}
}
}
console.log(user.personalInfo.address.city);
<----: HOISTING :---->
hello();
function hello (){
console.log("Hello world");
}
<----: DOCUMENT OBJECT MODEL (DOM) :---->
<----: Select an element by "ID,CLASS,QUERY,TAG" :---->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- <ul>
<li class="list">List 1</li>
<li id="second">List 2</li>
<li class="list">List 3</li>
</ul>
<h2 class="heading">Heading 1</h2>
<p>Paragraph 1</p>
<h2 class="heading">Heading 2</h2>
<p>Paragraph 2</p>
<h2 class="heading">Heading 3</h2>
<p>Paragraph 3</p> -->
<h2>Heading</h2>
<ul>
<li id="first">List 1</li>
<li>List 2</li>
<li>List 3</li>
<li>List 4</li>
</ul>
<ul id="parent">
<li>List 5</li>
<li id="sibling">List 6</li>
<li>List 7</li>
<li>List 8</li>
</ul>
<script>
// ID selector
// let elm = document.getElementById("second");
// elm.innerHTML = "List Changed";
// Class selector
// let elm = document.getElementsByClassName("list");
// console.log(elm.length);
// for(let i = 0 ; i <elm.length; i++){
// elm[0].innerHTML = "Hello"
// }
// Tag selector.
// let elm = document.getElementsByTagName("h2");
// for(let i = 0 ; i <elm.length; i++){
// elm[i].innerHTML = "Hello"
// }
// Query selector.
// let elm = document.querySelector("h2.heading");
// elm.innerHTML = "Hello"
// Traversing element
// (parent selector)
// let elm = document.getElementById("first");
// let parentSelect = elm.parentElement.innerHTML= "Hello";
// console.log(parentSelect);
//(children Selector)
// let elm = document.getElementById("parent");
// let childrenSelect = elm.firstElementChild;
// console.log(childrenSelect);
//(select all children )
// then use children only
// (sibling selector)
// let elm = document.getElementById("sibling");
// let sibling = elm.previousElementSibling.innerHTML="Hello";
// console.log(sibling);
</script>
</body>
</html>
// ----> APPEND <----
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
</head>
<body>
<!-- <div class="intro">
<p id="txt">This is a p Tag</p>
</div> -->
<ul id="list">
<li>List 1</li>
<li>List 2</li>
<li>List 3</li>
<li>List 4</li>
</ul>
<script>
// Append means kisi bhi element ke niche add karna !
// Change or add content using method :-
// let elm = document.querySelector(".intro");
// let newh1 = document.createElement('h1');
// adding class
// newh1.className = 'tryclass';
// adding id
// newh1.id = 'tryid'
// create text using createTextNode() Method
// let text = document.createTextNode("Hello this is h1 tag");
// newh1.appendChild(text);
// finally adding
// elm.appendChild(h1)
// appending in body
// document.body.appendChild(h1);
// Change or add content using proerties :-
// let elem = document.querySelector(".intro");
// let h1 = document.createElement('h3');
// h1.textContent = "Hello i am added to h1"
// elem.appendChild(h1);
// we can read content of any element using properties.
// eg
// let read = document.getElementById('txt');
// console.log(read.textContent);
// How to add 5th list ?
let list1 = document.getElementById('list')
let item = document.createElement('li');
item.textContent = " new List 5"
list1.appendChild(item);
</script>
</body>
</html>
// ----> INSERT <----
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>InsertBefore</title>
</head>
<body>
<ul id="list">
<!-- 1 -->
<li>List 1</li>
<!-- 2 -->
<li>List 2</li>
<!-- 3 -->
<li>List 3</li>
<!-- 4 -->
<li>List 4</li>
<!-- 5 -->
<li>List 5</li>
</ul>
<script>
let list = document.getElementById('list'); // parent selected
let item = document.createElement('li');
item.textContent = "New List 6";
// list.appendChild(item); // this use for append
// let position = list.firstElementChild; // li is selected
// list.insertBefore(item,position);
// let position = list.firstElementChild.nextElementSibling; // li2 is selected
// list.insertBefore(item,position);
// let position = list.firstElementChild.nextElementSibling.nextElementSibling; // li3 is selected
// list.insertBefore(item,position);
</script>
</body>
</html>
// <----: REMOVE CHILD ELEMENT :---->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
<script>
// how to remove child ?
let par = document.getElementById('menu'); // parent selcted
let elm = par.firstElementChild.nextElementSibling;
par.removeChild(elm);
// how to remove all ul?
document.body.removeChild(par);
</script>
</body>
</html>
// <----: CLONE ELEMENT :---->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clone elements</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Contact</li>
<li>Services</li>
</ul>
<script>
// How to clone elements
let menu = document.getElementById('menu');
let clone = menu.cloneNode(true);
// child ke sath clone banana hai to true otherwise false
clone.id="moblileMenu";
document.body.appendChild(clone);
</script>
</body>
</html>
// <----: REPLACE ELEMENT :---->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Replace</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Services</li>
</ul>
<script>
let parent = document.getElementById('menu');
let newItem = document.createElement('li');
newItem.textContent = "Product";
let rplc = parent.firstElementChild.nextElementSibling;
parent.replaceChild(newItem,rplc);
</script>
</body>
</html>
// <----: INSERT ADJUCENT :----->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>InsertAdjucent</title>
</head>
<body>
<!-- beforebegin -->
<div id="intro"> <!-- selected -->
<!-- afterbegin -->
<h2>Heading</h2>
<p>This is a P tag</p>
<!-- beforeend -->
</div>
<!-- afterend -->
<script>
let elm = document.getElementById("intro");
let html = "<h1> new h1 </h1>";
elm.insertAdjacentHTML('beforebegin',html);
</script>
</body>
</html>
/// :---- GET CSS VALUE USING JS :----
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#btn{
background-color: red;
color: white;
outline: 0;
}
</style>
</head>
<body>
<button id="btn">Click me</button>
<script>
let btn = document.getElementById('btn');
let css = getComputedStyle(btn);
console.log(css);
</script>
</body>
</html>
// :---- DOM EVENT LISTNERS :----
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">click me</button>
<button id="btn2">click me</button>
<script>
// addEventListner
let btn = document.getElementById("btn");
btn.addEventListener('click',function(){
console.log("mouse clicked");
});
btn.addEventListener('mouseover',function(){
console.log("mouse over");
})
// removeEventListner
let btn2 = document.getElementById('btn2');
let click2 = ()=>{
console.log("click 2 is activated");
}
let click3 = ()=>{
console.log("click 3 is activated");
}
btn2.addEventListener('click',click2);
btn2.addEventListener('click',click3);
// remove works in external funcitons :-
btn2.removeEventListener('click',click2);
</script>
</body>
</html>
:---- MOUSE EVENT :----
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mouse Events</title>
<style>
#box{
height: 100px;
width: 100px;
background-color: royalblue;
}
</style>
</head>
<body>
<!-- <div id="box" onclick="fun()"></div> -->
<!-- <div id="box" oncontextmenu="fun()"></div> -->
<!-- onContext function triggerd for right mouse click -->
<!-- <div id="box" ondblclick="fun()"></div> -->
<div id="box" onmousedown="fun()"></div>
<script>
function fun(){
console.log('Mouse events');
}
</script>
</body>
</html>
:---- KEY EVENTS :----
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> KEY EVENT </title>
<style>
</style>
</head>
<body>
<script>
window.addEventListener('keydown', checkKey);
function checkKey(event) {
console.log(event.key);
}
</script>
</body>
</html>
:--- SCROLL EVENT :---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> SCROLL EVENT </title>
<style>
body{
height: 1000px;
width : 2000px;
}
</style>
</head>
<body>
<p>Hello</p>
<script>
// 1.
// window.addEventListener('wheel', checkKey);
// function checkKey(event) {
// if(event.deltaY < 0){
// console.log("scrolling Up");
// }else if (event.deltaY>0) {
// console.log('scrolling Down');
// }
// }
// 2.
window.addEventListener('scroll' , colorChange);
function colorChange (){
if (window.pageYOffset>150) {
document.body.style.background = "red";
}else if(window.pageYOffset<150){
document.body.style.background = "white";
}
}
</script>
</body>
</html>
:----- INPUT FORM EVENT :-----
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>INPUT FORM EVENT</title>
<style>
body{background: rgb(156, 158, 36); }
#myInput{
margin: 300px 570px;
padding: 20px 10px;
outline: none;
border: none;
}
</style>
</head>
<body>
<form action="">
<input type="text" id="myInput">
</form>
<script>
let x = document.getElementById('myInput');
x.addEventListener('focus',myFocusFunction);
x.addEventListener('blur',myBlurFunction);
x.addEventListener('change',function(){
console.log(this.value);
});
function myFocusFunction() {
x.style.background = "skyBlue";
}
function myBlurFunction() {
x.style.background = "white";
}
</script>
</body>
</html>
:---- PREVENTS DEFAULT :----
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prevent Default </title>
<!-- Prevent default se ham kisi chiz ko rok sakte hai
jaise abhi hamne single click link ko roka -->
</head>
<body>
<a href="https://www.google.com" id="anchor">Click here</a>
</body>
<script>
let link = document.getElementById('anchor');
link.addEventListener('click' , function(param) {
console.log("link click ");
param.preventDefault();
});
</script>
</html>
:----- WINDOW OBJECT :----
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Window Object</title>
</head>
<body>
<button id="btn1">Google</button>
<button id="btn2">yahoo</button>
<button id="btn3">Close</button>
<script>
// New Window me open karna !!
let btn1 = document.getElementById('btn1');
let btn2 = document.getElementById('btn2');
let btn3 = document.getElementById('btn3');
let url = "https://www.google.com";
let url2 = 'https://in.search.yahoo.com/?fr2=inr';
let win; // we created global variable ...
let features = 'height=500,width=500';
let features2 = 'height=500,width=500';
btn1.addEventListener('click' , function(){
win = window.open(url,'google',features);
});
btn2.addEventListener('click' , function(){
window.open(url2,'yahoo',features2);
});
btn3.addEventListener('click', function(){
win.close();
});
</script>
</body>
</html>
:---- TimeOut and TimeInterval :----
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TimeOut and TimeInterval</title>
</head>
<body>
<button id="btn">Clear Inrerval </button>
<script>
// 1️⃣TimeOut Method() :-
// let TimeOutId = setTimeout(myFun,5000);
// function myFun(){
// alert("Hello world")
// }
// clearTimeout(TimeOutId);
// 2️⃣ SetIntervalMethod() :-
let t1 = setInterval(fun, 1100);
function fun() {
console.log("Hello world");
}
let btn1 = document.getElementById('btn');
btn1.addEventListener('click', function(){
clearInterval(t1); // 3️⃣ clearInterval
})
</script>
</body>
</html>
:----- Location Object / Link attachach :-----
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Location Object</title>
</head>
<body>
<button id="btn">click</button>
<script>
let btn1 = document.getElementById('btn');
btn1.addEventListener('click',function(){
// window.location = "https://www.google.com" // 1st
// location.href = "https://www.google.com"; // 2nd
// location.assign("https://www.google.com"); // 3rd
// location.replace('https://www.microsoft.com'); // 4th (but no back button)
location.reload(); // It reload the page
})
</script>
</body>
</html>
ECMA Script
let and const :-
let can be changed but const never change
Default Parameter
function talk(msg = "Hello", number = 2){
console.log(msg,number);
}
talk()
Rest Parameters (...) :-
function sum (...args){
let result = 0;
for(let i = 0; i<args.length; i++ ){
result += args[i];
}
console.log(result);
}
sum(1,2,3);
Spread Operator (...) // for adding array or object into each other or copying
let array1 = [1,2,3];
let array2 = [5,4,6,...array1];
let array3 = [...array1,...array2];
console.log(array3);
For Of Loop :-
let score = [30,20,40,50,70];
for(let x of score){
console.log(x);
}
let Name = "Hello world";
for(let y of Name){
console.log(y);
}
Template Literals :-
Array Destructuring :-
let book = ["Java", 128, 150];
old method to get data
let bookName = book[0];
let pages = book[1];
let price = book[2];
console.log(price);
Array destructuring method
let[bookName,page,price] = book;
console.log(bookName);
Where it used
function book(){
// do something
return ["Rd sharma",200];
}
let[bookName , price] = book();
console.log(bookName);
Object Destructuring
Normal
let book = {
bookName : "Advance Js",
page:150,
price: 200,
};
let bokName = book.bookName;
console.log(bokName);
Destructuring object method:
let book = {
bookName : "Advance Js",
page:150,
price: 200,
publication: {
pub_name : "XYZ",
year : 2021
}
};
let{bookName,page,price,publication : {pub_name,year}} = book;
console.log(pub_name);
MODULES :-
OOPs before ES6
Constructor function
function Person (first,last,a){
this.firstName = first;
this.lastName = last;
this.age = a;
this.sayHello = function(){
alert("Hello");
}
this.changeAge = function(newAge){
this.age = newAge;
}
}
let person1 = new Person("Himanshu","Tiwari",19);
person1.changeAge(28);
let person2 = new Person("Ajeet","Kumar",22);
console.log(person1,person2);
Prototype
let person1 = {};
console.log(person1);
let person2 = {
myName : "Himanshu"
}
console.log(person2.hasOwnProperty('myName'));
use of prototype
function Person (first,last,a){
this.firstName = first;
this.lastName = last;
this.age = a;
}
Person.prototype.fullName = function(){
console.log(this.firstName + " " + this.lastName);
}
let person1 = new Person('Himanshu',"kumar",19);
let person2 = new Person("Ajeet","Kumar",22);
console.log(person1.fullName());
console.log(person2);
Inheritence:-
function Creature(ls){
this.lifespan = ls
}
Creature.prototype.breath = function(){
console.log("breathing....");
}
let creature1 = new Creature(100);
console.log(creature1);
function Person (first){
this.firstName = first;
}
Person.prototype.fullName = function(){
console.log("Rahul Kumar");
}
// // // Performing Inheritence but it replace
// // // Person.prototype = Object.create(Creature.prototype);
// How can we actually perform inheritance chaining
Person.prototype.__proto__ = Creature.prototype;
let person1 = new Person("Rahul","Kumar",20);
console.log(person1.fullName());
ES6 Classes ,inheritance and Object :--
class person{
constructor(n,a){
this.name = n ;
this.age = a;
}
sayHi(){
console.log("hii..");
}
static hello(){
console.log("hello");
}
}
let person1 = new person("himanshu",19);
console.log(person1);
person1.sayHi();
// static func calling by class
// VVI stactic func or method is called by class not from obj.
person.hello();
Inheritance :-
class emp{
constructor(n){
this.name = n;
}
msg(){
console.log("Hi...");
}
}
class manager extends emp {
constructor(n,d){
super(n);
// super is used for getting prarent's value
this.department = d;
}
info(){
// calling msg here .
super.msg()
console.log(this.name + " is manager of department " + this.department);
}
}
let mng1 = new manager("Himanshu", "web dev");
console.log(mng1.info());
// we can create multiple class and inheriate into each other..
class admin extends manager{
}
let admin1 = new admin("himanshu",'web dev');
console.log(admin1);
Public Private
class emp{
#name = "";
constructor(n){
this.#name = n;
}
#getName(){
console.log(this.#name);
}
pubfun(){
this.#getName();
}
}
let emp1 = new emp("himanshu");
console.log(emp1.pubfun());
Mixing
let userfulMethod = {
sayHi(){
console.log("hi");
},
sayBye(){
console.log("Bye");
}
};
class user{
constructor(){
this.name = "HK"
}
}
// assigning object in class.
Object.assign(user.prototype, userfulMethod)
let usr1 = new user();
console.log(usr1.sayHi());
Map
let array1 = [1,2,3,4,56,];
let array2 = array1.map (x => x*2);
console.log(array2);
filter function
let array1 = [1,2,3,4,56,];
let array2 = array1.filter (function(x){
if (x/2 == 0) {
return x;
}else{
console.log("😏");
}
});
console.log(array2);