Skip to main content

Command Palette

Search for a command to run...

JavaScript

Published
•7 min read•View as Markdown

JavaScript:

JS is a programming language. We use it to give instruction to then computer

Input--->computer--->o/p

ctrl+k to clean the scree in the console

Console.log is used to log(print) a message to the console

console.log("mgit college"); ue use single quotes also Console.log('yes')

in browser without semicolon also it will print but good practices we use ;

JavaScript will write in html code ie.

\================================= Varibales in js:

variables are containers for data rulrs: 1.variable names are case sensitive 2.sapce is not allowed 3._ or$ is allowd for 1st char but numbers are not 4.reserved words cannot be variable name

\===================================== let ,const & var:

var: variable can be re declared & updated .A global scope variable.

let: variable cannot be re declared but can be updated .A block scope variable.

const: variable cannt be re declared or updated .A block scope varibale

\==================================================== Datatypes:

primitive : Number,String,Boolean,Undefined,Null,BigInt,Symbol

typeof---> is used to say the type

Undefined: let x=undefined; typeof x->undefiuned


let x=null typeof x->Object

let x=BigInt("123") typeof x-> bigint

let y=Symbol("Hello")

Non primitive:

objects-->collection of values

key:values are stored in objects

const student={ age:10 name:nithin gpa:9 }

we can acces student["name"] or obj.key

let we can update const we cant update cost obj ->key we can update

\======================================= Operators in js:

use to perform some operation on data

Arithemtic Operators: +,-,*,/,%,**,++,--(unary operators ++,--) modulus Exponentiation


Assignment Operators:

\=,+=,-=,*=,%=,**=;

Comparison Operators:

\==,===(Equal to & type),!=,!==(Not equal to & type),>,>=,<,<=

strict version === it will check the datatype == is will check the number with string

Logical Operators:

Logical AND(&&) Logical OR(||) Logical Not(!)

Conditional Statement:

to implement some condition in the code

if,if-else,else-if if(a==a) console.log("hello");--> this is also correct

if(a==a){ console.log("hello")};

Ternary Operator:

condition? true:false example-age>18?"adult":"not adult"

prompt("Hello") let name


Every thing in JavaScript execute in execution context

it like a big box it has memory (key: value)[it is called variable environment all variables are store]

code component where code is execute line by lime [thread of execution]

JavaScript is a synchronous and single threads environment

window object is global object have the method and it is created along with the global execution javascript engine and this variable created this pints to Window

for chrome V8 is the JavaScript engine. all the javascript engine responsibility to create global object.

Any Variable are crated inside the function it is not global space.

suppose var n=2 function square(num){ var ans =num*num; return ans; }

var sqaure1=square(n); var sqaure2=square(4);

phas1 : memory creation phase phas2: code execution phase

memory | code

n: undefined (2) memory | code
square: {...} num: undefined (2) numnum
ans: undefined (4) return ans after return the value it will deleted sqaure1: undefined (4)
same as above square2: undefined memory | code (16) num: undefined (4) num
num ans: undefined (16) return ans

It handle and manage the execution context --call stack(pop the methods)top of global

call stack maintain the order of execution of execution context

call stack can call as

execution context stack program stack control stack run time stack machine stack

Hoisting: phenomenon in JavaScript even we a can access the variable in the program it does not care where it present

for variable we get undefined function get total function

undefined- allocated memory not defined-not allocated memory

when ever execution context is created a lexical environment created

lexical is local memory along with lexical environment of parent

lexical -Hierarchy where it present physically

lexical scope like check in the local ,reference of parent and then it goes to parent...... this also called as scope chain

let ,const and var

var is in store at global

let and const it stores in separate memory space (script)

Temporary dead time: the time between hoisting to till initialize the value

Reference Error when we access when it is in temporary dead time

suppose if we use let a=10 ---..>syntax error let a=10

but it was possible in var

but in const it more strict then let and we can't write like it const b; b=1000 ; we have to write when we define initialize

Type error say you are assigning to another value to const

let & const are blocked scoped

block -{//compound statement }

block combines multiple statements in side block like let and const have defined in the block scope

shadowing

var a =100; let b=9; { var a =10; let b=10; console.log(a) //10 console.log(b) //10

} console.log(a) //10 this is shadowing console.log(b) //9 for let and const same

shadowing is not only for block also for function

let a = 10; { var a=20; //error we can do it }

var a = 10; { let a=20; //NO error }

closures: function along with lexical scope bundle to form a closure

uses of closures: -module design pattern

  • currying -function like once -memorize -maintain state in async world -setTimeouts -iterators

What are the first Class functions: is called function (like function capabilities) we can say first class citizens

Function Statement vs Function Expression vs Function Declarations

Functions statements:

this is function statement aka Function Declarations . console.log("");
}

Function Expression:: this is function expression var b=function(){}

Anonymous function

function (){}

Named function expression:

What is callback function in javascript?

JavaScript is asynchronous and single threaded language

Blocking main thread

Power of callbacks

Deep About eventlistners

Closures demo with event listners

scope demo with event listeners

Garbage Collections and remove events listeners

events listeners are heavy when we attach eventlistener it attach closure and consumes more memory

Js Engine code -> parsing -> compilation -> execution

JIT compliation

interpreter -> compiler ->

Higher order function which pass the function as a parameter or return a function

Map,filter,reduce:these are higher order function

Callback Hell: Issues : 1. Call back hell(function inside function) called as pyramid of Doom 2. Inversion of control (we give loose access to that function of the callback)

for callback we pass function promise-> we attach function

A container for the future value or is the placeholder which will filled a value for certain time until value gives from the async operation or promise is an object representing eventually completion or failure of async operation promise give control to the function and these are immutable

state of the promise (intial it is in pending state) and after that it changes to full fill state and one is rejected

result of the promise

promise chaining promise.then( function(){return})

https://www.youtube.com/watch?v=U74BJcr8NeQ timetamp 9:38 for creating promise pr=new Promise(function(resolve,reject){});

promise cn attach fail back function -> catch()

what is async? ( async function f1(){})

async always return a promise if we return no promise then it will wrap the non promise into the promise and it will return the promise

async and await are used to handle the promises

await can be use inside the async function

Java Script engine waits for the promise will resolve their when we us e const p=await p

In callstack the js engine will see any await then it suspend and comes out of the function and excute another after promise resolved then it again comes into the callstack adn it start excuting where it suspend from that point

fetch() return response that is a promise and .json() with return promise of json response

Promise Api:

Promise.all([p1,p2,3]) these will call asynchronous to all and wait for to get all the result if all the result get then it return the output

it will wait for all of them to finish it will collect the result and give me the result

if any promise get error then immediately it return the error as result not wait for the other promise to get the result

it is all or none or we can call as Fail Fast

promise.allSettled([p1,p2,p3,p4]);

it will wait for all promises to settle then it get result of all if it is success then gets val and if is fails then get error for each promise

promise.race([p1,p2,p3)]

let say p1, take 1se ,p2 takes 2 s,p3 takes 3sec then it will give the value of the first settle value after next settle value gives

so if error comes the n error throw that time

promise.any([p1,p2,p3]): It is very much similar trace it wait for success when every it will success then it return the result

it all will fails then it will return an aggregate error

settled->got the result it can either be resolve or reject || success or fail ||fulfilled pr rejected

this keyword: i global space this has a value of global object

the value depends on the strict mode nad non strict mode if it is strict mode it window and if it is non strict mode then it is undefiend

There is something known as this substitution Acc to this if the value this keyword undefined or null this will be replaced with global object

inside a function the value of this keyword is wondow if we don't use use strict mode

and if we use direct call then it gives undefines and if we use window.func() then it is a window in strict mode

function and method?

when we create a function inside the object then it isa method

Three important function: https://www.youtube.com/watch?v=75W8UPQ5l7k watch this video for reference call apply bind

we can modify the this key word or set the value of this key word by using these three methods

event Listers:

onClick, onBlur, onChange, onFocus, setInterval, setTimeout