Comprehensive JavaScript Cheat Sheet for Quick Reference and Mastery
76 views
13 slides
Aug 14, 2024
Slide 1 of 13
1
2
3
4
5
6
7
8
9
10
11
12
13
About This Presentation
"This comprehensive JavaScript cheat sheet provides a quick reference guide to essential syntax, functions, and concepts. Perfect for beginners and experienced developers alike, it covers everything from basic data types and operators to advanced topics like closures and async/await. Keep it ha...
"This comprehensive JavaScript cheat sheet provides a quick reference guide to essential syntax, functions, and concepts. Perfect for beginners and experienced developers alike, it covers everything from basic data types and operators to advanced topics like closures and async/await. Keep it handy to streamline your coding process and enhance your JavaScript mastery."
Size: 853.39 KB
Language: en
Added: Aug 14, 2024
Slides: 13 pages
Slide Content
Note:varNlet&
constote o::
Bo:as iecVbtsu lb
ser:ote Botaoy:euE
xpe sannetewre
yelVeew lpeh au
rbBetes bw gove .
bn lpau rpeolupeelE
2BasicVocabulary
Expression
K tenetewreN Bo:de bt o
vtbdg bn tenetewre/uO
ows Bo:de/uO rbhyawes
Valp bgetolbt/uONwhich
result in a single value.
Variable
K wohes tenetewre lb
oBo:deauoBotaoy:eE
Keyword / reserved word
Kwc Vbts lpol au gotl bn
lpe Bbroyd:otc bn lpe
gtbvtohhawv :owvdove au
ro::es o iecVbts
/oEiEo teuetBes VbtsOE
Smohg:eukBot ( 7 an nbtEEE
Operator
)getolbtu ote teuetBesTVbtsu lpol
getnbth orlabw bw Bo:deu ows Botaoy:euE
Smohg:euk7T(Paw(((lcgebn M(EEE
Statement
K vtbdg bn VbtsuN wdhyetu
ows bgetolbtu lpoldo a
taskau o ulolehewlE
vara=7+"2";
{
{
1Seven(7)Types
jE Jltawv
}; [f32lr
,; ]==ela1
z; [fee
O; B1cl91lc
8; :n32=e
5; h2/l"+
T Kttoc
- Function
"Any text"
123.45
trueorfalse
null
undefined
Symbol('something')
{key:'value'}
[1,"text",false]
functionname() { }
{
Six Primitive Types
varuser={
name: "Aziz Ali",
yearOfBirth:1988,
calculateAge:function(){
// some code to calculate age
}
}
{
Key
xpeue ote lpe
iecu awduet=2/l"+;
Value
xpeue ote lpe
Bo:deu bn lpe
teugerlaBe iecu
awduet=2/l"+;
Method
If a key has a
ndwrlabw ou o
Bo:deN alu ro::es
ohelpbsE
3Object
u1 =2/l"+ &7 a ca+a +n.l &1
JavaScript that is used to store
orbhyawolabwbnsoloawo
uahg:e iecTBo:de goatE xpolu alE
"Don't just learn JavaScript - Become a Full-Stack JavaScript Developer"
https://iLoveCoding.org
iLoveCoding
JavaScriptCheatsheet
Learn JavaScript Correctly (Video course)https://ilovecoding.org/courses/js2
Page 1
<>
♥iLoveCoding
4Function
F unctioNc oa aomefC d bnctlNutNkRbnckfRkocdaRtioNcr(loabnctlNutNkRp)IvPncaslRcilR
unctioNc oa tdffRkr gnctioNca dffNs uNP NP/dcoAoc/ tNkR ociN aRtioNca dck tNkR PRnadbofoiCr
Using a function has ONLY two parts. (1) Declaring/de$ning a function, and (2) using/running a function.
// Function declaration / Function statement
functionsomeName(param1,param2){
// bunch of code as needed...
vara=param1+"love"+param2;
returna;
}
// Invoke (run / call) a function
someName("Me", "You")
Name of function
Thats it, its just a name
you give to your function.
Tip: Make your function
names descriptive to what
ilR unctioNc kNRar
Code block
FcC tNkR soiloc ilR tnPfC
braces { ... } is called a
"block of code", "code
block" or simply "block".
This concept is not just
limited to functions. "if
statements", "for loops"
dck NilRP aidiRmRcia
use code blocks as well.
Return (optional)
F unctioNc tdc NeioNcdffC
spit-out or "return" a value
once its invoked. Once a
Function b(tubndY no Fubtf(b
focRa Nu tNkR soiloc ilR
unctioNc Pncr
Invoke a function
Invoking, calling or running a function all mean the same
thing. When we write the function name, in this case
aNmR)dmR,followedbythebracketssymbol"}like this
doe(2se("},thecodeinsidethefunctiongetsexecuted.
Passing parameter(s) to a function (optional)
At the time of invoking a function, parameter(s)
mdC bR edaaRk iN ilR unctioNc tNkRr
Parameters / Arguments
(optional)
F unctioNc tdc NeioNcdffC
take parameters (a.k.a
sbvue(ntd}p 1f(
unctioNc tdc ilRc naR
iloa ocuNPmdioNc soiloc
ilR tNkR oi ldar
"Don't just learn JavaScript - Become a Full-Stack JavaScript Developer"
https://iLoveCoding.org
iLoveCoding
JavaScriptCheatsheet
Learn JavaScript Correctly (Video course)https://ilovecoding.org/courses/js2
Page 2
<>
♥iLoveCoding
5Vocabulary around variables and scope
vara="global";
functionfirst(){
vara="fresh";
functionsecond(){
console.log(a);
}
}
Scope chain
The nested hierarchy of scope is
called the scope chain. The JS
engine looks for variables in the
scope chain upwards (it its
ancestors, until found)
Scope
The limits in which a variable exists.
Global scope
The outer most scope is called the Global
scope.
Functional scope
Any variables inside a function is in scope
of the function.
Lexical Environment (Lexical scope)
The physical location (scope) where a
variable or function is declared is its lexical
environment (lexical scope).
Rule:
(1) Variables in the outer scope can be
accessed in a nested scope; But variables
inside a nested scope CANNOT be accessed
by the outer scope. (a.k.a private variables.)
(2) Variables are picked up from the lexical
environment.
console.log(a);
vara="me";
a="me";
a=12;
vara;
Variable Declaration
The creation of the
variable.
Variable Initialization
The initial
assignment of value
to a variable.
Variable Assignment
Assigning value to a
variable.
Hoisting
Variables are
declared at the top
of the function
automatically, and
initialized at the time
they are run.
"Don't just learn JavaScript - Become a Full-Stack JavaScript Developer"
https://iLoveCoding.org
iLoveCoding
JavaScriptCheatsheet
Learn JavaScript Correctly (Video course)https://ilovecoding.org/courses/js2
Page 3
<>
♥iLoveCoding
2+"7";// "27"
true - 5 // -4
Type coercionpriority order:
2+ "7;/tr
ny td:Cac
Ay hmmsagr
Coercion in action
Lmal eEol :gqa larlau
vEar ecRori em /m:Igca DoOOacare PeRIalPb eEa JgSgp/coIe ariora
/iirSWi. ih Uho'rsi hor i-Wr toih /ohimrs .h ti U/o UhSW/sr imr ijh
Sgsdaly
7Coercion
BWrs/ihs. /sr sr.rs'rbkjhsb. im/i WrsRhsS /Uitho ho '/:vr. /ob '/st/c:r.u
Arithmetic
++C++
++k++
++*++
++/++
++%++
++**++
Assignment
++=++
+++=++
++-=++
++*=++
Logical
++||++
++&&++
Equality
++===++
++==++
Conversion
C++
k++
!++
Add
pdCecg/e
Multiply
LoSoDa
Remainder
Exponential
Assign value
Add then assign
pdCecg/e eEar glloir
Multiply then assign
Bs
And
Equality
Equality with coercion
Convert to number
Convert to number then negate it
Convert to boolean then inverse it
Relational / Comparison
++>=++
++<=++
++!=++
++!==++
Increment / Decrement
++CC
++kk
CC++
kk++
Others
eRIamO++
++orlegr/amO++
(++)
+++.Wsr/bkhWrs/ihs
+
++[++]
orj++
Dasaea++
(++u++:++)
Greater than or equal to
Less than or equal to
Not equal after coercion
Not equal
Post?x increment
Post?x decrement
Pre?x increment
Pre?x increment
Operator Precedence
Given multiple operators are used in an expression, the "Operator
Precedence" determines which operator will be executed ?rst. The
higher the precedence, the earlier it will get executed.
Operator Associativity
Given multiple operators have the same precedence, "Associativity"
brirsStor. to jmtUm btsrUitho imr Uhbr jt:: cr W/s.rbu
paa eEaOperator Precedence and Associativity tableEaca:
http://bit.ly/operatortable
6Operators
Full list of JavaScript operatorshttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators
"Don't just learn JavaScript - Become a Full-Stack JavaScript Developer"
https://iLoveCoding.org
iLoveCoding
JavaScriptCheatsheet
Learn JavaScript Correctly (Video course)https://ilovecoding.org/courses/js2
Page 4
<>
♥iLoveCoding
for(initial-expression;condition;second-expression){
// run this code in block
}
Loops are used to do something repeatedly. For instance lets say we get a list of 50
blog posts from the database and we want to print their titles on our page. Instead of
writing the code 50 times, we would instead use a loop to make this happen.
while(i<3){
// run this code in block
i++;
}
do{
// run this code in block
i++;
}while(i<3);
Step 1:Run the initial expression.
Step 2:Check if condition meets. If
condition meets, proceed; or else end the
loop.
Step 3:Run the code in block.
Step 4:Run the second-expression.
Step 5:Go to Step 2.
Step 1:If the condition is true, proceed; or
else end the loop.
Step 2:Run the code in block.
Step 3:Go to Step 1.
Step 1:Run the code in block.
Step 2:If the condition is true, proceed; or
else end the loop.
Step 3:Go to Step 1.
For loop
While loop
Do while loop
10LoopStatements
"Don't just learn JavaScript - Become a Full-Stack JavaScript Developer"
https://iLoveCoding.org
iLoveCoding
JavaScriptCheatsheet
Learn JavaScript Correctly (Video course)https://ilovecoding.org/courses/js2
Page 6
<>
♥iLoveCoding
Event Loop
Eve ntLopT
hirLd -dPaLTT
yhh- -dPaLTT
Third-Party
Process
JavaScript Engine
csPJSs ngC lPopLgp
ngLakpiPo lPopLgp
ngLakpiPo lPopLgp
Call Stack
MSTpQio Q udTpQPkp
hSTW hSTW hSTW
Message Queue
12Event Loop
There are 3 ways to create variables in JavaScript:
varCletandconst.VariablescreatedwithvarSdL
in scope of the function (or global if declared in the
global scope);letvariables are block scoped; and
consttSdiSJsLT SdL siWLletplus their values
cannot be re-assigned.
vara="some value"; // functional or global scoped
letb="some value"; // blockscoped
constc="some value";// block scoped + cannot get new value
11Ways to create a variable
"Don't just learn JavaScript - Become a Full-Stack JavaScript Developer"
https://iLoveCoding.org
iLoveCoding
JavaScriptCheatsheet
Learn JavaScript Correctly (Video course)https://ilovecoding.org/courses/js2
Page 7
<>
♥iLoveCoding
13Browser
Document
The viewport or the section
where the website is displayed is
called the document of the page.
https://...
Window
Each tab of a browser is
considered the window.
This is the outer most
container that a web-app
can access.
Notice: A website opened
in one tab CANNOT
access the window
object of another tab.
Pretty cool right?
The browser contains a
lot of components that a
Front-End Developer may
need, such asNavigator,
JavaScript Engineand
Dev Tools.
A web browser is a pretty advance piece of software which contains a lot of components. Many of these components are accessible to a
web developer, so we can create complex web apps. At the same time a lot of components are kept out of reach of the web developer for
security purposes. For instance, we as web developers can get access to the user's location, but we cannot get access to the user's saved
passwords or browsing history.Let's see below how a browser is structured:
Dev Tools
JavaScript Engine
HTML / CSS Processor
Navigator
"Don't just learn JavaScript - Become a Full-Stack JavaScript Developer"
https://iLoveCoding.org
iLoveCoding
JavaScriptCheatsheet
Learn JavaScript Correctly (Video course)https://ilovecoding.org/courses/js2
Page 8
<>
♥iLoveCoding
14DOM-DocumentObjectModel
What is a "Node"?
(in the context of DOM)
Node:Every item in the DOM
tree is called a node. There
are two types of node - A text
node, and an element node:
Text Node:Node that has text.
Element Node:Node that has
an element.
Child Node:A node which is a
child of another node.
Parent Node:A node which
has one or more child.
Descendent Node:A node
which is nested deep in the
tree.
Sibling Node:A node that
share the same parent node.
Query/Get Elements
// Preferred way:
document.querySelector('css-selectors')
document.querySelectorAll('css-selectors', ...)
// Old ways, and still work:
document.getElementsByTagName ('element-name')
document.getElementsByClassName ('class-name')
document.getElementById('id')
Create / clone Element
document.createElement('div')
document.createTextNode('some text here')
node.cloneNode()
node.textContent='some text here'
Modify Element
node.style.color='red'
node.style.padding='10px',
node.style.fontSize='200%'
node.setAttribute('attr-name', 'attr-value')
node.removeAttribute('attr-name')
Get and Modify Element Class
node.classList
node.classList.add('class-name', ...)
node.classList.remove('class-name', ...)
node.classList.toggle('class-name')
node.classList.contains('class-name')
node.classList.replace('old', 'new')
Add node to document
parentNode.appendChild(nodeToAdd)
parentNode.insertBefore(nodeToAdd,childNode)
Remove Node
parentNode.removeChild(nodeToRemove)
// Hack to remove self
nodeToRemove.parentNode.remov eChild(nodeToRemove)
Get Element Details
node.nextSibling
node.firstChild
node.lastChild
node.parentNode
node.childNodes
node.children
Events
node.addEventListener('event-name',callback-function)
node.removeEventListener('event-name',callback-function)
List of Events:https://developer.mozilla.org/en-US/docs/Web/Events
or google"Mozilla event reference"
"Don't just learn JavaScript - Become a Full-Stack JavaScript Developer"
https://iLoveCoding.org
iLoveCoding
JavaScriptCheatsheet
Learn JavaScript Correctly (Video course)https://ilovecoding.org/courses/js2
Page 9
<>
♥iLoveCoding
16Built-inObjects
Date
Buuilt -nuObllj ejct- cu sDa cMt auhA
constd=newDate('9/17/1988');
d.getDay()
d.getFullYear()
d.getMonth()
Date.now()
Milliseconds since Jan 1, 1970
Math
Buuilt -nuObllj njcM- cu sDa cMt auhA
Math.pow(2,3) // 8
Math.sqrt(16) // 4
Math.min(7,8,6)// 6
Math.max(7,8,6)// 8
Math.floor(123.45)// 123
Math.ceil(123.45)// 124
Math.round(123.45)// 123
Math.random() // 0.45..
JavaScript gives us a ton of useful
built-in objects to make our lives
easier. TheDateandMathobjects
are very useful on a regular basis.
Take a look at some of their
features on the right.
oIll lbAc ur dIblcbD udPthcA bD pjSjghNbmc SbAbc1((r8Mhh/tutsortYiJoewssDioYnht9,0lh/o78hptghFDuDl7Ywr(h2t.tYt97thcsogDs3qgyt7(8
15AutoInheritedProperties
String
Buuilt -nuObllj gcNbDi- cu sDa cMt auhA
.concat()
.charAt()
.indexOf()
.startsWith()
.endsWith()
.split()
.slice()
Number
coonst d=oewssD 6;JgtYd (o '9/ (1t /o78
.toFixed()
.toPrecision()
.toString()
Boolean
coonst d=oewssD 4oostD9d (o '9/ (1t /o78
.toString()
Array
1oonst d=oewssD mYYDxd (o '9/ (1t /o78
.filter()
.map()
.find()
.every()
.some()
.sort()
.slice()
.splice()
.reduce()
.forEach()
When you create a value in
JavaScript, certain properties are
automatically inherited by this value.
This magic happens because every
typehas aconstructorwith a special
property calledprototype.All
methods on theprototypegets
automatically inherited by the new
value created for thattype.
Take a look at some of of these
methods on the right.
constthing="some text"; constnum=123.45;
fao9d( y;8( stDY9 FDuDl7Ywr( , 4t7oJt D );ss,l(D75 FDuDl7Ywr( atutsortYf
https://iLoveCoding.org
iLoveCoding
JavaScriptCheatsheet
Learn JavaScript Correctly (Video course)https://ilovecoding.org/courses/js2
Page 10iLoveCoding<>
♥
What is a Promise?
WhatisP is ro ameP?n nArn yhacikPs r NsP:NJ ?aosnhN?n vAPo kPrJioS
{Uom nslgrm(BgBhs ons}sA C e(B)Usi Us rn>>it n w/(B)Usiw airnhsi Uo
chn(ngoiis Uo {U>> (hg heBg shrriss B( =nU>h(i B= omno ons}A
PB(}Ugc {Uom n e(B)Usi rBgsUsos B= o{B en(osv ,Cj D(inoUgc n e(B)UsPy
ngt ,kj TsUgc n e(B)UsiA
What is an Async task?
Cg nslgr ons} Us Bgi Ug {mUrm n omU(tuen(ol e(Briss Us
tBUgc omi ons}A
fdn)e>is'
uSi;hisoUgcLsigtUgctnonoBntnonansi
uSi;hisoUgcLsigtUgctnon.Un200/e(BoBrB>
-Workingwiththe-lesystemofthecomputer
17Promise
Note:90% of the time you will be working with pre-existing
e(B)UsisA 0mi soie B= wD(inoUgc n e(B)Usiw {Bh>t ai tBgi =B(
lBh iUomi( al n >Ua(n(ly =(n)i{B(} B( ig.U(Bg)igo lBh n(i
hsUgcA fdn)e>is B= e(B)Usis' =iorm
//(B)Using a promise
p.then((res)=>{
console.log(res)
})
.catch((err)=>{
console.log(err)
})
// (A) Create a promise
constp=newPromise((resolve,reject)=>{
// Do some async task
setTimeout(()=>{
if(condition){
resolve('Successful login');
}else{
reject('Login failed');
}
},2000)
})
"Don't just learn JavaScript - Become a Full-Stack JavaScript Developer"
https://iLoveCoding.org
iLoveCoding
JavaScriptCheatsheet
Learn JavaScript Correctly (Video course)https://ilovecoding.org/courses/js2
Page 11iLoveCoding<>
♥
18'this'keyword
varname="Fatema";
functionfun(){
// some code here
console.log(this.name);
}
constuser={
name: "Marium",
yearOfBirth:1999,
calcAge:function(){
constcurrentYear=(newDate()).getFullYear();
returncurrentYear-this.yearOfBirth;
}
}
fun(); // 'this' is global. Logs "Fatema"
user.calcAge();// 'this' is the user object
fun.call(user);// 'this' is the user object. Logs "Marium"
Scenario #1:thisinside a function
1thitskehyword Soscik io nao#1a o#:hfiu
Scenario #2:thisinside a method
1thitskehyword Soscik io ith o#:hfi ith
2hitod sk scu
Scenario #3:When function is run with
call,bindorapply
mthc 1 3Wcfisoc sk f1aahd Wkscn ith
uf1aalS1r12,u#scdlS1r12,oru1SSaylS1r12,
2hitodb ith prkiS1r12#hfo2h ith o#:hfi
it1i ithitskehyword rh3hrk iou
'thitskehyword sk Wkhd scksdh 1 3Wcfisocu 'thitsk
ehyword sk 2hrhay 1 rh3hrhcfh io 1coithr o#:hfiu
mt1i ithitskehyword rh3hrk io dhShcdk oc ith
kfhc1rso or ith w1y ith 3Wcfisoc sk s2Sah2hcihdu
Ihrh 1rh ith N kfhc1rsok io rh2h2#hrJ
Important Note:
vc ith #rowkhrb nao#1a sk ithwscdowo#:hfiu
vc Codhu:kb nao#1a sk ithnao#1ao#:hfiu
"Don't just learn JavaScript - Become a Full-Stack JavaScript Developer"
annueO99mAtYrwtfmcist;i
iLoveCoding
JavaScriptCheatsheet
Ar);c D)Y)-/;mun wt;;r/no" g'mfrt /t.;er}annueO99motYr/tfmcist;i9/t.;ere9{eb
L)ir jb
<>
♥iLoveCoding
191DefingaiDn
// Defining a Constructor
functionCar(make, model, year){
this.make=make;
this.model=model;
this.year=year;
this.setMiles=function(miles){
this.miles=miles
returnmiles;
}
}
// Using a constructor
constcar1=newCar('Toyota','Prius',2016);
constcar2=newCar('Hyundai','Sonata',2018);
// Adding method to the constructor prototype
Car.prototype.age =function(){
return(newDate()).getFullYear() -this.year;
}
car1.age();// 2
Cgos Dt irguc(
A) Set properties
inside a constructor.
B) Set methods inside
the prototype
property.
meskm,sdkDnl
The new keyword is
used to create a new
object (instance) from
the constructor.
mynDiDidysmynDysnid
prototype is a special
property on every
object. Properties
(methods or values)
attached to the
prototype property
get inherited to every
instance of the
constructor.
)r{i hf { aDefingaiDn.
In JavaScript, a constructor is a special
function that acts as a mold to create
new objects.
There are numerous built-in constructors
in JavaScript, such asString,Number,
Promise,Date,Array,Object,andmany
more.
We can create our own custom
constructors if need be.
A great place to use a constructor is
when you are creating multiple objects of
the same kind.
There are two parts to working with a
constructor:
=;M }sUehe1 { aDefingaiDn
When creating a custom constructor
=wM 'fhe1 { aDefingaiDn
with the "new"keyword
"Don't just learn JavaScript - Become a Full-Stack JavaScript Developer"
https://iLoveCoding.org
iLoveCoding
T{P{2anhyi/rs{ifrssi
Learn JavaScript Correctly (Video course)https://ilovecoding.org/courses/js2
Page 13
<>
♥iLoveCoding