Javascript Notes
Javascript Notes
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
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
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
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
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
Spread Operator(…)
1. Get all elements of one array into another array for example
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;
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;
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
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);
}
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
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
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
“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