0 ratings0% found this document useful (0 votes) 45 views13 pagesJavaScript CheatSheet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
@ Seven (7) Types
1. String ‘Any text”
2. Number 123.45
3. Boolean true or false
4, Null null
5. Undefined undefined
6. Symbol Symbol ("something' )
7. Object { key: ‘value’ }
+ Array [1, “text”, false]
= Function function name() { }
@ Object
‘An object is a data type in
var user = {
JavaScript that is used to store
a combination of dataina oe
simple key-value pair. Thats it yearofBirth
calculateagi
Key some code
These are the }
keys in user object.
@ Basic Vocabulary
Variable
Anamed reference to
a value is a variable
Operator
Operators are reserved-words that
perform action on values and variables.
Examples: + - = * in === typeof =
Statement
2 A group of words, numbers
eS and operators that doa
Note: var,
const areal Keyword / reserved word
valid keywordsto Any word that is part of oe
ecavevarabes. the vocabulary of the Acfaonca aera
Heweentteig -Programminglanguage is group of reference(s)
coveredon page7 called a keyword and value(s) combined
ofthis cheatsheet. (a.k.a reserved word). with operator(s), which
Examples: var = * i for. resultin a single value.
ai", Value Method
These are the Ifakey has a
1988, values of the
respective keys
inuser object.
function as a
value, its called
a method.
function(){@ Function
Parameters / Arguments
‘A function is simply a bunch of code bundled in a section. This bunch of code ONLY runs when the (optional)
function is called. Functions allow for organizing code into sections and code reusability. ‘A function can optionally
take parameters (aka
arguments). The
function can then use
this information within
the code it has.
Using a function has ONLY two parts. (1) Declaring/defining a function, and (2) using/running a function.
n // Function de
Thats it its just a name
ation Pruners
yougie toyurtneon. \_ neon oneName( arent, parand) {
To: Mate your ncn
Name of fun¢
a Function stati
on
names descriptive to what / h of code es needed Code block
ee / bunch of code as needed ee any code within the cuty
var a = paraml + "love" + param2; braces... }is called a
“block of code’, “code
return a; k .
enum (optenal) ————" block or simply "block
‘function ean optioaly Y Tite foneone
spitout or return’ a value - statements’ "for loops”
once its invoked. Once a / Invoke (run / call) a function and other statements
function returns, no further
lines of code within the someName("Me", "You" use code blocks as well
————
function run. eee
7
Invoke a function Passing parameter(s) to a function (optional)
Invoking, calling or running a function all mean the same At the time of invoking a function, parameter(s)
thing, When we write the function name, in this case ‘may be passed to the function code.
someName, followed by the brackets symbol () lke this
someName(, the code inside the function gets executed.® Vocabulary around variables and scope
Variable Declaration Scope
ver a; The creation of the __Thelimits in which a variable exists, var @ = “global”;
variable.
oe Function Farst(){
Variable nalization The outer most scope is called the Global var a = “fresh
a= 12; Teil scope
Pasar function second(){
Functional scope console.109(2);
Any variables inside a function isin scope ,
Variable Assignment of the function
Assigning value toa
variable
Lexical Environment (Lexical scope) ‘Scope chain
The physical location (scope) where a The nested hierarchy of scope is
console.1og(a); Hoisting variable or functions declared is ts lexical called the scope chain. The JS
oenearae: Variables are environment (lexical scope) engine looks for variables in the
declared at the top scope chain upwards (tits
of the function ule ancestors, until found)
automatically, and (1) Variables in the outer scope can be
inialzed atthe time accessed ina nested scope; But variables
they are run 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.© Operators *
Operators are reserved-words that perform action on values and variables.
Arithmetic Relational / Comparison Operator Precedence
4 Add Greater than or equal to Given multiple operators are used in an expression, the “Operator
~. Subtract Less than or equalto Precedence" determines which operator will be executed first. The
+ Multiply I=. Not equal after coercion higher the precedence, the earlier it wll get executed.
/.. Divide Not equal
%.. Remainder Operator Associativity
© Exponential Increment / Decrement Given multiple operators have the same precedence, “Associativty"
+++ Postfix increment determines in which direction the code will be parsed.
Assignment ~ Postfix decrement
‘Assign value See the Operator Precedence and Associativty table here:
Add then assign ++. Prefix inerement nto /bittoperatortab
Subtract then assign Prefix increment
Multiply then assign
Others @ Coercion
ae Ne When trying to compare different "types', the JavaScript engine
oo i attempts convert one ype int anther so it can compare the two
‘pread-operator values
Equality ‘Type coercion priority order aoe
Equality {4 1. String a
Equality with coercion new 2. Number true - 5 4
delete 3. Boolean
Conversion Gt) a
+.. Convert to number Coercion in action
Convert to number then negate it Does this make sense?
!.. Convert to boolean then inverse itConditional Statements
Conditional statements allow our program to run specific code only if certain conditions are
‘met. For instance, lets say we have a shopping app. We can tell our program to hide the
“checkout” button if the shopping cart is empty.
If -else Statement: Run certain code, “if a
condition is met. Ifthe condition is not met,
the code in the "else" block is run (if
available.)
expression, and runs the code of the “case”
‘where the expression matches. The "break"
keyword is used to end the switch
statement,
if (a> @) {
switeh (expression) {
case choicet
aver run this code
eieel( break;
run this code
} case choice
run this code
break;
‘Ternary Operator: A ternary operator returns
the first value if the expression is truthy, or
else retums the second value. default
run this code
(expression)? iffrue: ifFalse; }
@ Truthy / Falsy
There are certain values in JavaScript that
return true when coerced into boolean, Such
values are called truthy values. On the other
hhand, there are certain values that return
false when coerced to boolean, These
values are knows as falsy values.
‘Truthy Values Falsy Values
true false
"text" c
2 e
72 -0
Infinity NaN
-Infinity null
O undefined
u© Loop Statements
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 thei titles on our page. Instead of
writing the code 50 times, we would instead use a loop to make this happen.
‘Step 1: Run the initial expression,
‘Step 2: Check if condition meets. If
condition meets, proceed; of else end the
loop.
For loop
‘Step 3: Run the code in block.
dition; second-expre
“
‘Step 4: Run the second-expression.
Step 5: Go to Step 2.
ie oo
; step contin ite proceso
while (4{
// Do some async task
setTimeout(()=>{
if (condition) {
resolve( ‘Successful login’) ;
} else {
reject('Login failed’);
}
}, 2000)
y)
What is an Asyne task?
‘An async task is one in which a third-party process is
doing the task.
Examples:
- Requesting/sending data to a database
= Requesting/sending data via HTTP protocol
= Working with the file system of the computer
// (B) Using a promise
[Link]((res)=>{
console. 1og(res)
»)
-catch((err)=>{
console. log(err)
+)
Note: 90% of the time you will be working with pre-existing
promises. The step of "Creating a promise” would be done for
yyou either by a library, framework or environment you are
Using. Examples of promises: fetch® ‘this’ keyword
‘The this keyword is used inside a function. The this
keyword is merely a reference to another object.
What the this keyword refers to depends on the
scenario or the way the function is implemented.
Here are the 3 scenarios to remember:
‘Scenario #1: this inction
The this keyword points to global object.
‘Scenario #2: this it
The this keyword points to the object the
method is in.
‘Scenario #3: When function is run with
call,bind or apply
When a function is called using the
.call(param) bind(param) or .apply(param)
‘method, the first param become the object
that the this keyword refers to
Important Note:
In the browser, global is the window object.
In Node js, global is the global object.
var name = "Fatema";
function fun(){
some code here
console.1og( [Link]) ;
const user = {
name: "Marium",
yearOfBirth: 1999,
caloage: function(){
const currentYear
new Date()).getFullyear();
return currentYear - [Link];
+
}
fun(); this’ is global. Logs "Fatema’
[Link](); // ‘this’ is the user object
[Link](user); // ‘this’ is the user object. Logs "Mariun’© Constructor
Defining a Constructor Rule of thum
What is a constructor?
‘unetion Car 1% a a) i
In JavaScript, aconsttuctoris a special 7 uNe10n Car(make, model, year) ise Sooeton
function that acts as a mold to create ee ecko
new objects [Link] = model; 8) Set methods inside
‘There are numerous built-in constructors eae oo Claes
pert
in JavaScript, such as String, Number, a
Promise, Date, Array, Object, and many [Link] = function(miles){
more. [Link] = miles sew" keyword
ve . . return miles; The new keyword is
fe can create cur own custom " used to reste a new
constructors if need be. ) object (instance) from.
the constructor.
A great place to use a constructor is we constructo
when you are creating multiple objects of tram o en! aren
the same kind const art = new Car(*Toyota’, ‘Prius’, 2016); "prototype" property
prototype is a special
property on every
object. Properties
(methods or values)
[Link] = function(){ attached to the
return (new Date()).getFullYear() - [Link] prototype property
get inherited to every
(2) Using a constructor >
cabo instance of the
with the "no" keyword an constructor.
[Link](); // 2
“There are two parts to working with a const car2 = new Car(*Hyundai', ‘Sonata’, 2018);
constructor:
(1) Defining a constructor
When creating a custom constructor