Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

JavaScript Notes

Definition: JavaScript is high level,multi-pardigm,object oriented


programming language.adds functionality to html elements

Naming Convention: Use Camel Case Standard JavaScript and can only
contain Numbers,Dollar,underscore and alphabets if we don’t follow it we
will get the syntax error and variable names cant get started with numbers
and we cant use reserve keywords however using dollar or underscore will
prevent the syntax error but its good to use the proper conventions

Data Types (Primitive)


Javascript Does Need to explicitly write datatype name it automatically
detects the data type called as dynamic data typing
1. Number: example let a=23;
2. String : inside the quotes Ex: let a=”praneeth”;
3. Boolean: ex let a= true; or let b=false;
4. Undefined: For empty value ex: let a;
5. Null,Symbol,BigInt (refer when needed)
Type Conversion/Coercion
1)if we manually changes data type it is type conversion
Ex let a=Number(“10”);
2)If js Automatically does behind scenes it is coercion
Ex: let a = “20”-10;
Functions:
1. Two types of functions declartions,expressions;
2. Declarations: function area(){return 100;} area();
3. Expressions: const area2= function
4. (){return 1220;;}
5. Declarative functions can be used before declaring
6. Expression functions cant be used before declaration js will
throw error
7. Arrow Functions: ex const area=(l,b)=>l*b;
8. We can pass default parameters to functions

9. First class funcations is like treating functions as another variable


assigning values,returning etc..
10.When function receives another function as argument we call it
as higher order functions.or it can return new function also

Arrays in JavaScript
1. Can also be created as let a=new Array(10,20,3);
2. Push returns new length
3. Pop returns removed element
4. Shift() removes first element from array
5. Includes() will return true or false and performs strict equality
6. Arrays how we specify order is important
7. To solve problem of labelling the value we moved to Object
8. For(let i=arr.length-1;i>=0;i--) //backward looping
Finding highest in array
Finding Lowest in Array

Merge Two Arrays

It doesn’t affect the original array


Looping over arrays
1. For of loop will give access to current element
2. .entries() method will return the index along with current element
Destructuring Arrays in javaScript
1. Destructuring means breaking large data structure into simple
variables
2. Ex: const [a,b,c]=[2,3,4] ie.e a=2,b=3,c=4;
3. Return multiple values from functions using array destructuring;

4. If you are taking a value from the array and that value is undefined,
then you can assign a default value to a variable.
5. Swapping without Temp variable

6. Rest operator

Array Methods in JavaScript


1. .slice(start,end) is an array method end is param is optional and it
wont affect the orginal array it simply returns new array;
End param is not inclusive

2. .splice(start,end) acts same as splice but it affects the original array by


removing the part we mentioned
3. .reverse() will reverses the array and it mutates original array

4. .join(separator) takes separator argument and converts everything in


the array to single string

5. .at(index) method return the element at that particular index it works


fine on string too

6. .forEach() will take 3 arguments current element,index and array that


is being looped and it performs call back function for every iteration
Continue; and break will not work in the foreach method and it will not
return anything and can be used to loop over sets and maps

7. .map() is array method and callback function takes3 args


current,index,arr that is being looped.performs call back function for
every iteration and put it into an array and returns that array at the
end of the iteration

8. .filter() has same props as above map and it returns new array with
elements that passes the condition that was speicified
9. .reduce() is apowerful js method for array it call back function takes
4args one is accumulator,current value index and current array and
need to pass the default/intial value of the accumulator whole purpose
of reduce is to get single value out of the big array

10..find() also accepts 3args and unlike filter method it will return the first
element that satisfies the condition provided

.findIndex() will follow same pattern but it returns the index of that
element
11..some() array method returns true if atleast one element in array gets
satisfied else returns false
12..every() array method returns true only if every element in array
satisfies the given condtion else return false
13..flat() array method flattens the array with nested arrays it takes
arguments of depth

14..flatMap() combines Flat and map method together but passing of


depth is not possible here;
15..sort() sorts an array and mutates original array by default it sorts
alphabetically to change it number sorting we need to write the
custom call back function

16.Array.from() will take two args,one is length,one Is call back


17..fill() will takes 3 args element to be filled and positions, to be filled it
mutates original array
18.New Array will be constructor method if passed only one argument it
will just create empty array with that length mo methods will work on
it except the fill method
Objects In JavaScript
1. Attach functions to objects same as key/value pairs
2. Inside function will have access to all properties of that object and will
be referred using this keyword
3. Update existing properties also
4. Shallow Copy: Object.assign method will be used to copy the existing
object without having to manipulate the original object however it will
only create new heap only for properties not for deeply nested objects
5. Deep Copy:

6. Object.keys will return all the keys in an object in array format


7. Object.values will return all the values in an object in array format
8. Object.entires will return all the key,value pairs in array format
9. Object.fromEntries() will create new object from the array
Sets in JavaScript
1. Sets is declared as ex: const a =new Set();
2. Set always holds unique values
3. .has() return true or false
4. .add(),.delete() for adding/removing
5. .clear() removes everything
6. .size() is used for getting total unique values count for that set
7. We cant get data from set;
8. Mostly used to remove duplicates from arrays
Example:

Maps in JavaScript
1. Maps is declared as const a=new Map();
2. Map is simply collection of key,value pairs
3. .set is for adding and returns updated map value
4. .get is for getting the value from map;
5. .delete is for deleting
6. .has() returns true or false
7. It can hold key of any data type unlike objects which holds only strings
8. Converting Object into map new Map(Object.entries(obj));

Arrays vs Sets
1. Use arrays for simple storing and manipulation
2. Use sets to deal with unique data
3. Searching /removing duplicates is faster in Set rather than Arrays

Objects vs Maps
1. Objects have advantage of having methods which has access to all
properties of the object where Map doesn’t have them
2. Map has advantage of key value could be any data type where as
objects keys can only be strings

Object Destructuring
1. Instead of accessing it by dot or bracket notations we can use
destructuring in javascript like this
2. Providing default values in destructuring

3. Destructing function arguments

Instead of having full object we can use whatever we want that


particular function will have to do with that object
4. Providing Custom variable names

Spread Operator(…)
1. Get all elements of one array into another array for example

2. Combine two arrays for example into 3rd one


3. Usage with Strings

4. Object Usage

5. Merging Objects

REST Operator
1. Written on left side of assignement
2. Must be always last
3. Only one Rest operator
4. Collects remaining part of array/objects
5. Passing Multiple values to function

Short Circuting in Js
1. Using OR operator

it stops executing when it first encounters truthy value and returns the
same
2. Using AND operator

It stops executing once it encounters first falsey value and return the
same if all are equally satisfied then prints last condition
3. Nullish Coescaling
JavaScript Features
1. High Level: No need to Manage Memory manually unlike c
2. Garbage-Collection: Automatically removes old unused code
3. Automatic-Compilation from human readable code to machine code
4. Supports Functional Programming,oop Programming,procedural
programming
5. First Class Functions: functions to be treated same as variables
6. Dynamic typed language: no need to assign variable data type
7. Single threaded:handles only one task at a time
8. Non blocking event loop
9. JIT(just in time compilation): Compilation and execution will happen
simultaneously
JS Engine(Behind the scenes)
1. Parsing: Checks for syntax errors and converts into ASN tree
2. Compilation:Converts programme to Machine code
3. Execution:
4. Optimization runs in background
5. CallStack: Next things ready to be executed(putting everything in box
and executing them one by one) once stack if full we will get stack
overflow error
6. Heap: Memory heap comes in. We need the memory heap as a place to
store and write information because at the end of the day all programs
just read and write operations — that is to allocate, use and release
memory.
7. Global execution Context: For code outside the functions
8. Every function gets its own execution context
9. Global execution Context will be removed from call stack on close of
browser or tab
10.Execution context will have scope chain,this keyword and variable
environment
Scoping in JavaScript
1. Scope: Where our variable is placed and where can we access it
2. Types: Function,global,block
3. Let and cost and block scoped
4. Var is function scoped
5. Every scope has access to its outer scope;

6. we wont get error here because function was


called after declaration of testName

7. we will get error here because


we are trying to access variable before declaration
8. Functions are also block scoped in strict mode
Hoisting in JavaScript
1. Moving up of variables or functions from their scope so that we can
use them before they are actually declared;
2. variables declared with var are hoisted but will be having intial value
of undefined below code will result in undefined but we wont get error

3. Let and const are not hoisted they are in temporal dead zone and js
will throw error for below code if we try to access them before
initializing;

4. Function expressions/arrow functions will follw the same treatment


based on which they type they are defined(let/const/var)
5. Temporal dead zone: if let/const are tried to access before initialization
but they are in code once they are initialized we can use it and its
removed from tdz.used in modern js to get errors in such case and
used for helping the const variable to work in expected way
6. Let and const wont be part of window object but var will be
This keyword in JavaScript
1. This keyword refers to that particular object when in strict mode;
2. this keyword will refer to global window object if not in strict mode;
3. arrow functions wont get this keyword on their own it gets from its
lexical outside environment
4. this keyword will point to dom element incase of event handling;
5. in simple function call this will be undefined in strict mode and it
refers to the window object in normal mode
Working With Strings in JavaScript
1. lastIndexOf() will return the last found letter index in string
2. .slice() return new string with provided indexes
3. .trim() removes white space from the both ends of string
4. .includes,.startswith,.endswith use cases for strings

Bind,Call,Apply In javaScript
1. Main concept of having these words is to have flexible usage of using
this keyword for the methods written inside the objects
2. Usually this keyword is referred to that particular object

3. .bind() will not immeadiately invoke the function in turn it returns new
function to be called later

4. One more Use case of Bind is when using event Listeners this keyword
will point to the element of that is binded.using bind we can override
that behavior

5. .bind will accept the object and also the arguments we can provide the
default argument and when we are actually calling that function we
can pass the rest of the arguments;
6. suppose if an object method accept two arguments we can pass 1
argument at tiem of bind and remaining during the execution
7. Important thing to remember is to have a new variable and copy the
function of object there
Closures In JavaScript
1. Function along with its lexical scope bundled together is called Closure

In simple words functions remeberes the varaibles which are present


during its creation and we call it as Closure
//closures example

for(var i=1;i<=5;i++)
{
setTimeout(function(){
// console.log(i);
},i*1000);
}
//here this will print 6 to the console 5 times because var is function
scoped and
//by the time js executes the functions i already became 6;

// two ways to solve this one is to use let.because let is block scoped
//second way is to create closure

for(var i=1;i<=5;i++)
{
function close(i)
{
setTimeout(function(){
console.log(i);
},i*1000);
}
close(i);
}

//here we are creating a new instance of i every time loop runs


Numbers in javaScript
1. Numbers are always stored as floating points even if we manually
write or not
Example: 23===23.0 will return true;
2. Fractions might become difficult while playing around because\
0.1+0.2 ===0.3 returns false because decimals;
3. Converting String to Number Number(string) or +”string”
4. Parsing Methods For Numbers
 ParseInt().takes two args returns integer part
 ParseFloat() returns fraction part also
 isNAN checks if arg is number or not
 isFinite checks if arg is finite or infinite

5. Math.sqrt() for calculating square root


6. Math.abs() for getting absolute value
7. Math.PI constant which returns 3.14
8. Math.max() for maximum value and it does type coercion
9. Math.min() for miniumum value
10.Math.trunc to remove fraction part
11.Math.random() genereates between 0 and 1
12.Mth.ceil() returns the next value
13.Math.floor() retuns previous value
14.Math.round() returns the nearest value
15.toFixed for how many decimal places we want
16.% return the remainder where .returns the quotient
17.Js ignores _ in between Numbers for ex 23_000 will take it as 23000

Dates In JavaScript
1. Can be create by using new Date() operator
2. getDay() returns the current day in week ex:sat/mon etc..
3. getTime() returns milliseconds
4. getHour,getMinutes,getSeconds all will return the specifc answers
5. Date.now() returns the milliseconds after 1970 january
6. getMonth returns from 0 to 11 0 being jan and 11 being dec
DOM Manipulation in JS
1. document.documentElement will give the access to whole document
2. document.body,document.head will igve body and head tags
3. getElementsByTagName,getElementsbyClassName will help in
returning all elements with that tag and then it automatically updates
when dom changes
4. .before() will attach element before selected node
5. .cloneNode(true) will copy the current node; tru for opying child nodes
too
6. .after() will attach element after the selected node
7. .createElement() will help in creating new html element and we need
to pass the tag as an arg like document.createElement(“h1”) it will
create h1 tag
8. .append() will attach the cur element to the last of children
9. .prepend() wll attach the cur element to the first of children
10..parentElement will give the parentElement
11..remove() removes from the dom itself or removeChildNode by
selecting parentNode also works
12..getComputedStyle(htmlELment) will return the object having whole
applied styles to that particular element;
13..setAttribute(),.getAttribute(),.removeAttribute() for altering the
attributes in html element;
14.Always try to put data- to custom attribute names which can be easily
understood by js and css
15..dataset will return the list of all data attributes present there
16.classList.add,.remove(),.contains each will take class name as an arg
and performs whatever is required
17..scroolIntoView will take to the specif element provided it will take the
args behavior:smooth for smooth transistion
18.EventCapturing means from top to bottom till innermost element
19.Eventbubbling means from bottom to top till document/html element
20.Bydefault it will be eventbubbling if at all we want we can set it to
true(usecapture) argument
21.eventDelegation simply refers to instead of attaching eventlistner for
each click we use click on parent then use target value to do what we
want to do
22..childNodes will return everything including text,comments etc..
23.children will give only HTML live collection

2. DOMContententReady=document.ready() wont wait for external


images/files to load
3. Load event fires once dom,images,external files are loaded
4. beforeUnload() gets triggered before when someone leaves/reload the
page
OOPS with JavaScript
1. Class is like a blue print on how the object looks like but not the
original object;
2. Instance is a real object ccreated from the Class using new keyword
3. Abstraction:hiding implementation details
4. Encapsulation:methods and data props cant be accessed from outside
5. Inheritance:parent class extends its methods and data props to its child
class.and child class can have its own methods additional to that
6. Polymorphism: overwriting parent class methods with child class
Constructor/New Operator in Oops

Prototypes in Oops

Prototype Chain
Js Will look for the method/property 1st on the object later it looks on
the __proto__ here.if it cant find here it will go to the protype
inherited here we have prototype inheritenace from the Person
Constructor.js will look here also.if it cant find here also.it will again go
deep to check ultimately it reaches object.prototype if it cant find
there also it will return null;
ES6 classes

1. Written using keyword class


2. Class is not hoisted
3. Class is first class citizen same like functions
4. Class is always executed in strict mode
Static Methods in Oops
1. Declared using static keyword;
2. It cant be inherited by any instances created with the
class
3. This keyword points to entire class/constructor

4.
Object.create() method will create an empty object but it also
accepts one object as argument which will set that prototype to the
newly created object

Inheritance

Class Based Inheritance


Async/Await/promises in Javascript
1. Uusally js is single threaded synchronous Programming
language
2. Js executes next line only if previous line of code is executed
completely
3. Sometimes this results in blocking behaviour like if we have
one task that takes more time and rest of our code has to wait
4. So we have some asynchronous function in javascript.one
example could be setTimoutMethod,eventListeners
methods.etc..
5. Promise is a container for future value
6. Promise have fulfilled and rejected states once async task is
completed
7. .then() is used to fulfil the promise
8. .catch() is used for handling rejected promises like any error
9. .finallly() gets called no matter what happens with promiss
10. Promises Will only fails if no internet
11. Throw new Error(“message”) will reject the promise and
we will get custom message
Async behind the browser
Js runtime environemtn consists of following things
1)heap for storing objects and variables
2)Call stack where execution takes place
3)Call back que
4)Web Apis(Dom,timers,navigators,fetch)
So any kind of executions related to web Api doesn’t run in the
call stack since it is synchronous and might take long time to
proceed.once async operation is completed in the web api
environment.it will put the code in callBack que and MicroTaks
que mostly used for promises which takes more priority than the
normal callback queue and event loop will take care of which
thing to be put into the call stack once it is free
EventLoop now looks at callback Queue or microTaks Quue and
then puts them into callStack
Async/await
Async should be keyword on the function saying js that it should
be treated asynchronously
.then() is used to resolve promises before await keyword is used
now to resolve the promises.
Await block the execution till that line is completed
Async functions return promise
Promis.allSettled() will return the array with all the status of
passed promises.it wont short circuit it will return whatever is
there in the Promise
Promise.any() will return first fulfilled promise and will simply
reject rest of the things
Modules in Js
1. Modules are small building blocks to build one large
application
2. We can write re usable code
3. Share data between files
4. Can write isolated code and more organized way
5. We need to specify type=module during the script linking in
html
6. Import statement no matter where we write those will be
executed in the first(hoisted)
7. Two types of exports namely default exports and named
exports
8. Default export doesn’t need to specify name and only one for
the module
Example:

9. Named exports: Need to mention the name of the variable or


function whatever we are exporting
Example:

10. Import all the exports from a module


1. We can also import using custom names using “as” keyword
2. Modules always runs in strict mode;
3. This keyword by default refers to undefined
4. Whatever is declared in the modules are always private unless
they are shared
5. Modules are loaded asynchronously.
6. Es2022 now supports top level await in modules that means
we can use await keyword without usage of async keyword
Need to be careful with this approach since it blocks entire
execution till that is completed
Quick Bites
1. Type of null returns object
2. ** is for performing power example 2**3=8
3. Mathematical operators take more precedence than logical operators
4. Mathematics (left to right execution) ex: let a =2+3
5. Assignment right to left execution
6. Use backticks to use values inside strings(string template literals
Ex: `im a ${variable}`
7. Falsey Values: 0,NAN,undefined,null,””
8. == converts(loose equality) and(===) doesn’t converts(strict equals)
9. Prompt method provides Input to get input from user
10.Switch: break; is must otherwise loop keeps going and it is strict equals
11.Statements: Complete Ones ends with semicolon
12.Expressions: Part of statements which produce values
13.Use Strict: helps to avoid accidental errors shows errors in console
14.Const: can be mutated other than primitive data types ex(array,object)
15.indexOf(): method returns index if found or else -1
16.Continue: will exit the current iteration
17.Break: will exit the whole loop
18.Console.table() will print the results in tabular form
19.textContent(); will return the text content inside an element
20.Math.floor(Math.random() * n) + 1 for creating random number
between 1 to n;
21.No Need to call the function in event listener mention the name will be
enough js will automatically call it
22.Arrow Functions wont get this keyword and arguments keyword
23.Primitives points to new address whenever they are changed;
24.Since objects are stored in heap memory stack will only have reference
to it and everytime something changes it will directly update the
address it pointed to initially and now whatever variables are pointing
to that address will have updated value
25.Optional Chaining

26.IIFE: (Immediately invoked function expressions)


Used for creating scopes and could be called only once

27.Closures might come with side effect of memory leak/not garbage


collected since the variable are still remembered by js
28.insertAdjacentHTML is method performed on html elements which
take two args postion and content
postion values can be beforestart,beforeend,afterbegin,afterene
29 suppose a=10;a++; if we log a++ it will still retun old value but it
actually changes the old value;whereas ++a will return the updated
value
30 weakMap() and weakSet() refer in web.takes only object as input
31 .padStart(2,0) to add zero before the number less than 10 example

“9”.padStart(2,0)=09
“11”.padStart(2,0)=11
32 ClearTimeout() to remove the timeout()
33 cleatInterval() to remove the setIntervalMethod();
34 async() loads along with html but when html parsing stops until that
async is completed better use for 3rd party libraries ex;analytics
35 defer downloads the file beforehand but it waits till all html is loaded
then executes it best usage
36 for older browsers need to put in the bottom of page only
37 declaring variable like #movements in back class makes movements as
private field and will not be accessed outside the class
38 navigatior.geolocation.getcurrentposition helps in getting the users
location access and it takes two call backs 1 is for success and I if user
denies it.success function will return the current position
39 Object.freeze we can use it for both objects and arrays and make them
immutable it only does top level freeze
40 Object.fromEntries will create new object from the entries array
41 HAshChanged is eventlistener available on the window to listen
whenever the hash changes in url
42 New FormData(form) will give the form values in entries manner

You might also like