Javascript Notes
Javascript Notes
semicolons used
dynamically typed language-> not a fixed datatype of a varaible like python
if(YES){
alert("This code is executed");
}
2).Undefined:
var myvar; -> when we define a variable but don't specify its value then it
will be undefined variable.
alert(myvar);
3).String:
var str1 = "Manas Jayaswal";
var str2 = "Hello World";
sequence of characters stored inside double or single inverted comma.
4).Null:
var myvar = null;
alert(myvar);
5).Number:
var int = 100;
var hex = 0xfff;
var float = 100.5;
var exponential = 2.34e2;
var octal = 030;
6).Bigint:
var big_int = 324728349238n; // n must be written after writing the integer
we can use
console.log(typeof <variable name>);
to determine the datatype of the variable
variables:
Declaring a variable:
let name;
Initializing a variable:
name = "Manas Jayaswal";
Updating a variable:
name = "Ayush Jayaswal";
Camelcase
let firstName = "Manas";
Pascalcase
let LastName = "Jayaswal";
Snakecase
let middle_name = "Kumar";
Operator in Javascript:
exponetiation operator -> **
relational operator:
equal to -> ==
strictly -> ===
for example 1=='1' -> true
and 1==='1' -> false
var x = "7"
if-else statement:
if(condition){
console.log("code to if condition is true");
}else{
console.log("run some other code instead");
}
* If we give output using console log it won't be shown in the website it will be
shown in the console of developer tool.
* console.log(`${fruittype} is not present today`);
1).For loop:
for(let i=0;i<10;i++){
console.log("Manas Jayaswal");
}
2).While loop:
let i = 0;
while(i<10){
console.log("Namaste, World");
i++;
}
3).Do-While loop:
let j = 10;
do{
console.log("Namaste, World");
}while(j<10);
4).for-in loop:
a).Using Objects:
let animal = {
name : "Zebra",
leg : 4
};
output->
name Zebra
leg 4
b).Using Arrays:
//using loops
Output:
0 Manas
1 Ayush
2 Shreyash
**For of loop using Arrays: //For of loop is only made for arrays not for
objects
Output:
Manas
Ayush
Shreyash
**********Strings************
Concatanation:
"Manas" + "Jayaswal" = "ManasJayaswal"
"mjmanas" + 54 = "mjmanas54"
54 + 54 = 108
**Template literals:
let score = 10033;
console.log(`Your score is ${score}`);
********String Methods*********
c). str.indexOf("Jayaswal") -> it returns the index from where the word starts
inside the string.
d). str.slice(5,7) -> it returns the substring of str from index 5 to index 7-1=6
e). str.toUpperCase() -> it returns the string after making all the letters in the
capital form
f). str.toLowerCase() -> it returns the string after converting all the letters to
small case.
1).Objects:
let animal{
name : "Cow",
legs : 4
};
2).Arrays:
3).Functions:
function namasteWorld(){
console.log("Namaste World");
}
namasteWorld();
function helloName(name){
console.log(`hello ${name}`);
}
helloName();
function addition(a,b){
return a+b;
}
a).String:
->Implicit Conversion:
123+''
->Explicit Conversion:
String(123)
String(123) //'123'
String(-12.3) //'-12.3'
String(null) //'null'
String(undefined) //'undefined'
String(true) //'true'
String(false) //'false'
b).Boolean:
->Impicit Conversion:
!!2 //If logical operator is used then it will autometically be
converted to boolean
if(2) {..........}
2 || 'hello'
->Explicit Conversion:
Boolean('') //false
Boolean(0) //false
Boolean(-0) //false
Boolean(NaN) //false
Boolean(null) //false
Boolean(undefined) //false
Boolean(false) //false
**On converting user defined datatypes(arrays,objects,function) into boolean
datatype, it will always be converted to true.
c).Number:
->Implicit Conversion:
+'123'
123 != '456'
4 > '5'
5/null
true | 0
->Explicit Conversion:
Number(null) //0
Number(undefined) //NaN
Number(true) //1
Number(false) //0
Number(" 12 ") //12
Number("-12.34") //-12.34
Number("\n") //0
Number(" 12s ") //NaN
Number(123) //123
******************Objects*************************
const course = {
lecture : 10,
section : 3,
title : 'Javascript',
notes : {
intro: "Welcome to JS course."
},
enroll(){
console.log('You are successfully enrolled');
}
}
course.enroll();
console.log(course);
course.price = 999; //object course was declared as const, even though it can
be changed, because it is referencing data type.
console.log(course);
****************Factory Function*****************
function createCourse(){
return {
lecture : 10,
section : 3,
title : 'Javascript',
notes : {
intro: "Welcome to JS course."
},
enroll(){
console.log('You are successfully enrolled');
}
}
// return course;
}
for eg:
function createCourse(title){
return {
title : title,
enroll(){
console.log('You are successfully enrolled');
}
}
// return course;
}
console.log(course.title);
// Constructor Function
function Course(title){
this.title = title,
this.enroll = function(){
console.log("You are successfully enrolled..");
}
}
const course = new Course("Cpp"); //here new keyword is use to return the function
pointed by this to an empty variable, we can do it manually also, on removing new
keyword and placing a return this; inside the constructor function...
console.log(course.title);
course.enroll();
delete course.title
console.log(course.title) //output will be undefined
for example:
console.log(course1.constructor);
console.log(str.constructor);
***********************************************************************************
*********************
function Course(title){
this.title = title;
this.enroll = function(){
console.log("You are successfully enrolled...");
}
}
function createCourse(title){
return {
title : title,
enroll(){
console.log("You are successfully enrolled...");
}
}
}
course2 = createCourse("Python");
console.log(course1.title);
console.log(course1.constructor);
console.log(course2.title);
console.log(course2.constructor);
***********************************************************************************
**************************
=>Pass by value and Pass by reference:
console.log(number,number_2);
const obj = {
num : 10
}
const obj_2 = obj;
obj.num = 15;
console.log(obj,obj_2);
obj_2.num = 10;
console.log(obj,obj_2);
***********************************************************************************
**************************
// But if we wanna use pass by value in Reference Datatype we can use below
methods:
//Method :1
course1 = {
title : "Javasript",
enroll(){
console.log("You are successfully enrolled...");
}
}
course2 = { ...course1 };
console.log(course1,course2);
course1.title = "Cpp";
console.log(course1,course2);
********************************************************
//Method :2
course1 = {
title : "Javasript",
enroll(){
console.log("You are successfully enrolled...");
}
}
course2 = Object.assign({},course1);
console.log(course1,course2);
course1.title = "Cpp";
console.log(course1,course2);
********************************************************
//Method :3
course1 = {
title : "Javasript",
enroll(){
console.log("You are successfully enrolled...");
}
}
console.log(course1,course2);
***************************Objects Exercise***********************************
function Items(name,price,discount){
this.name = name;
this.discount = discount;
this.price = price;
this.showPrice = function(){
console.log(`The Price of the ${this.name} is ${this.price}`);
}
this.applyDiscount = function(){
this.price -= (this.price*(this.discount/100));
}
}
***********************************************************************************
************
************Classes***************
// Classes behaves same as constructor function but they have different syntax
class Product{
constructor(name,price,discount){
this.name = name;
this.price = price;
this.discount = discount;
}
applyDiscount = function(){ //methods should be written outside the
constructor
this.price -= (this.price*(this.discount/100));
}
showPrice = function(){
console.log(`The Price of the ${this.name} is ${this.price}`);
}
}
class Product1{
constructor(name,price,discount){
this.name = name;
this.price = price;
this.discount = discount;
applyDiscount = function(){
this.price -= (this.price*(this.discount/100));
}
showPrice = function(){
console.log(`The Price of the ${this.name} is ${this.price}`);
}
}
applyDiscount = function(){ //methods should be written outside the
constructor
this.price -= (this.price*(this.discount/100));
}
showPrice = function(){
console.log(`The Price of the ${this.name} is ${this.price}`);
}
get getDiscountValue(){
return this.discount;
}
set setDiscountValue(value){
this.discount = value;
}
}
class Product{
constructor(name){
console.log("Hey this line is executed");
this.name = name;
}
showName(){
console.log(`${this.name} is a product..`);
}
}
*****************************Arrays*****************************************
//Declaration of array
1).Push:
array.push(10) //appends 10 at the end of the array and returns the new length of
the array
2).Unshift:
array.unshift(0) //appends 0 at the front of the array and returns the new length
of the array
3).Pop:
array.pop(); //it removes the last element from the array and returns the removed
element
4).Shift:
array.shift(); //it removes the first element of the array and returns the
removed element
*********In Javascript single array can store values of different datatype and that
can be changed dynamically too.
5).indexOf: //it returns -1 if the value if not present at that particular domain
**includes method won't work if the elements inside array are of referencing
datatype i.e. objects or arrays and hence we will use find methods for them to
detect
8).find:
const array = [
{
name : "Manas",
follower:400
},
{
name : "Shreyash",
follower:300
},
{
name : "Ayush",
follower:200
}
]
or
console.log(arr1.concate("Manas"));
console.log(arr1.concate("Manas","Shreyash"));
console.log(arr1.concate(arr2));
11).spread operator:
//if we have to concatanate two arrays we can use method given below
arr3 = [...arr1,...arr2];
//if we have to copy the elements of arr1 in arr3 we can use the method given below
arr3 = [...arr1];
arr3 = [...[1,2,3,4],...[5,6,7,8]];
12).forEach method:
array.forEach(function(element,index){
console.log(element,index);
}));
13).join method:
console.log(array.join('')); //"manas"
console.log(str.split(<separator>);
console.log(str.split('_')); //['m','a','n','a','s']
**the first parameter passed in the function inside find or filter method is the
element of the array whereas the second parameter passed is the index of element
16).map method: //we will use it when we have large number of buttons,
we somehow make all of them in array and apply operations, eventListeners on them
using ma
array = [1,2,3,4,5];
***********************************************************************************
**************************
buttons.map(btn => {
btn.addEventListener('click',btnFunction);
function btnFunction(event){
if(btn.textContent == "←"){
screen.textContent = screen.textContent.slice(0,
(screen.textContent.length)-1);
}
else if(btn.textContent == "="){
// console.log("hello");
screen.textContent = eval(screen.textContent);
}
else{
screen.textContent += btn.textContent;
}
}
});
***********************************************************************************
****************************
17).reduce method: //to find the sum of all the follower in the array
console.log(total);
18).sort method:
console.log(sortByName);
19).every method:
20).some method:
21).Destructuring of an array:
// Destructuring an array
console.log(first); //1
console.log(second); //2
console.log(third); //3
console.log(fourth); //4
1).global scope:
//same as python
2).local scope:
**we have to use let keyword or const keyword while defining variables in place of
var because it attaches with window object.
**these different properties of var and let will be visible in case of blocks not
in case of function.
var name = "Manas"; //by using var keyword variable name is attached to window
object and hence it can be chaged inside block
if(true){
var name = "Shreyash";
}
console.log(name); //the output will be Shreyash
if(true){
let xyz = "Manas";
}
if(true){
var xyz = "Manas";
}
function father(){
var x = "Manas";
//here variable x is accessible but not y.
function child(){
var y = "Shreyash";
//here both variables x and y are accessible.
}
}
*******************************DOM
Manipulation*******************************************
**querySelector => used to select the first element with a particular classname or
id or tagname etc,
**querySelector => used to select all the elements with the particular classname or
id or tagname etc.
**if we makes our attributes by our own then we can't access directly it in
javascript
=> like id and class are attributes and we make another attribute data inside
a tag then we can't access it inside the script tag
=> <li id="manas" data="abc">Manas<\li>
then on doing console.log(manas.id) we get output as manas which is the
id , but on doing console.log(manas.data) we get undefined as output.
=> console.log(manas.attributes());
**Methods to add a new element node or text node using javascript.
**If we want we can append the whole html code inside a tag.
newDiv.innerHTML(`<ul>
<li id="manas" data="valid">Manas</li>
<li>Shreyash</li>
<li>Ayush</li>
</ul>`); //this will appends the entire html code
inside the div tag
**the first parameter passed in the even function is the event object, we can
access it by below method =>
<!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>DOM Manipulation</title>
</head>
// Childrens
// console.log(document.body.childNodes)
// console.log(document.body.children)
// for (node of document.body.children) {
// console.log(document.body.children)
// }
// console.log(document.body.firstChild)
// console.log(document.body.lastChild)
// console.log(document.body.firstElementChild)
// console.log(document.body.lastElementChild)
// const childrensOfBody = Array.from(document.body.children)
// console.log(childrensOfBody)
// Siblings
// const ulTag = document.body.children[0]
// const firstLi = ulTag.children[0]
// const secondLi = ulTag.children[1]
// console.log(secondLi.previousElementSibling.textContent)
// ID search
// element.style.background = "red"
// listItem = document.getElementsByClassName("list-item")
// console.log(document.getElementsByTagName("table"))
// Attributes
// console.log(element.getAttribute('data'))
// console.log(element.setAttribute('order-placed', 'pending'))
// console.log(element.removeAttribute('order-placed'))
// console.log(element.hasAttribute('order-placed'))
// console.log(element.attributes)
// Manipulating Classes
// body.className = "second page"
// body.classList.add('new')
// body.classList.remove('new')
// body.classList.toggle('new')
// console.log(body.classList)
// Mainipulating Style
// body.style.color= "red"
// body.style['background-color']= "orange"
// body.style.margin= "200px"
// Events
function callMe(event){
console.log(event.type)
console.log(event.currentTarget)
console.log(event.clientY)
console.log(event.clientX)
alert("Thanks for Watching")
}
// clickBtn.onclick = callMe
clickBtn.addEventListener('click', callMe)
// clickBtn.addEventListener('click', function(){
// alert("Thanks")
// })
// clickBtn.removeEventListener('click',callMe)
// clickBtn.removeEventListener('click', function(){
// alert("Thanks")
// })
</script>
</body>
</html>