JS Essentials Cheat Sheets-1
JS Essentials Cheat Sheets-1
1. Spread Operator
The Spread Operator is used to unpack an iterable (e.g. an array, object, etc.) into individual
elements.
Example:
console.log(arr2); // [1, 2, 3, 4]
Example:
console.log(arr2); // [2, 3]
1.1.2 Concatenation
Example:
console.log(arr3); // [2, 3, 4, 5]
Example:
Example:
1.2.2 Concatenation
Example:
console.log(personDetails); // Object {name: "Rahul", age: 27, city: "Hyderabad", pincode: 500001}
The Spread Operator syntax can be used to pass an array of arguments to the function. Extra values
will be ignored if we pass more arguments than the function parameters.
Example:
function add(a, b, c) {
return a + b + c;
console.log(add(...numbers)); // 6
2. Rest Parameter
Example:
function numbers(...args) {
console.log(args); // [1, 2, 3]
numbers(1, 2, 3);
2.1 Destructuring arrays and objects with Rest Parameter Syntax
2.1.1 Arrays
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]
2.1.2 Objects
Example:
firstName: "Rahul",
lastName: "Attuluri",
age: 27
};
console.log(firstName); // Rahul
Note:
Example-1:
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]
numbers(1, 2, 3, 4, 5);
Example-2:
console.log(a);
console.log(rest);
console.log(b);
numbers(1, 2, 3, 4, 5); // Uncaught SyntaxError: Rest parameter must be last formal parameter
3. Functions
3.1 Default Parameters
Example:
function numbers(a = 2, b = 5) {
console.log(a); // 3
console.log(b); // 5
numbers(3);
We can include the variables or expressions using a dollar sign with curly braces ${ }.
Example:
console.log(message); // OK
2. Conditional Statements
A Switch statement is a conditional statement like if...else statement used in decision making.
Syntax:
switch (expression) {
case value1:
break;
case value2:
break;
...
case valueN:
break;
default:
break;
}
Example:
let day = 1;
switch (day) {
case 0:
console.log("Sunday");
break;
case 1:
console.log("Monday"); // Monday
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
case 5:
console.log("Friday");
break;
case 6:
console.log("Saturday");
break;
default:
console.log("Invalid");
break;
}
If there is no break statement, then the execution continues with the next case until the break
statement is met.
3. Defining Functions
Function Declaration
Function Expression
Arrow Functions
Syntax:
// statement(s)
};
sum();
Example:
let result = a + b;
return result;
};
console.log(sum(4, 3));
In arrow functions, the return statement and curly braces are not required for simple expressions.
Example:
Example:
console.log(greet("Rahul")); // Hi Rahul!
3.1.3 No parameters
If there are no parameters, parentheses will be empty, but they should be present.
Example:
console.log(sayHi()); // Hello!
Example:
return {
firstName: name
};
};
Simple Expression:
console.log(createUser()); // undefined
JavaScript considers the two curly braces as a code block, but not as an object syntax.
So, wrap the object with parentheses to distinguish with a code block.
The Scope is the region of the code where a certain variable can be accessed.
Block scope
Global scope
If a variable is declared with const or let within a curly brace ({}), then it is said to be defined in the
Block Scope.
if..else
function (){}
switch
for..of, etc.
Example :
let age = 27;
let x = 0;
console.log(x); // 0
If a variable is declared outside all functions and curly braces ({}), then it is said to be defined
in the Global Scope.
When a variable declared with let or const is accessed, Javascript searches for the variable in
the block scopes first followed by global scopes.
Example:
const x = 30;
function myFunction() {
if (x > 18) {
console.log(x); // 30
myFunction();
2. Hoisting
Hoisting is a JavaScript mechanism where function declarations are moved to the top of their scope
before code execution.
Example:
let x = 15;
let y = 10;
console.log(result); // 25
function add(a, b) {
return a + b;
Example:
myFunction();
let x = 5;
};
myFunction();
let x = 5;
};
3.1 Map()
The map() method creates a new array with the results of calling a function for every array element.
The map() method calls the provided function once for each element in an array, in order.
Here the callback is a function that is called for every element of array.
currentValue is the value of the current element and index is the array index of the current element.
Here index and arr are optional arguments.
Example:
3.2 forEach()
The forEach() method executes a provided function once for each array element. It always returns
undefined.
Example:
3.3 filter()
The filter() method creates a new array filled with all elements that pass the test (provided as a
function).
A new array with the elements that pass the test will be returned. If no elements pass the test, an
empty array will be returned.
Example:
console.log(positiveNumbers); // [1, 3]
3.4 reduce()
The reduce() method executes a reducer function (that you provide) on each element of the array,
resulting in single output value.
Here accumulator is the initialValue or the previously returned value of the function and
currentValue is the value of the current element, index and arr are optional arguments.
Example:
console.log(array1.reduce(reducer)); // 10
3.5 every()
The every() method tests whether all elements in the array pass the test implemented by the
provided function. It returns a Boolean value.
Example:
console.log(result); // true
3.6 some()
The some() method tests whether at least one element in the array passes the test implemented by
the provided function. It returns a Boolean value.
Example:
console.log(result); // true
3.7 reverse()
The reverse() method reverses the order of the elements in an array.The first array element
becomes the last, and the last array element becomes the first.
Syntax : array.reverse()
Example:
3.8 flat()
The flat() method creates a new array with all sub-array elements concatenated into it recursively up
to the specified depth.
Example:
console.log(arr1.flat()); // [ 0,1,2,3,4 ]
Mutable methods will change the original array and Immutable methods won't change the original
array.
shift() map()
unshift() filter()
push() reduce()
pop() forEach()
sort() slice()
reverse() join()
A Factory function is any function that returns a new object for every function call.
Syntax:
return {
property1: parameter1,
property2: parameter2,
...
...
Example:
return {
color: color,
brand: brand,
start: function() {
console.log("started");
};
Eaxmple:
return {
color,
brand,
start() {
console.log("started");
};
2. Constructor Function
A regular function that returns a new object on calling with the new operator. The created new
object is called an Instance.
Syntax:
function FunctionName(parameter1, parameter2, ...) {
this.property1 = parameter1;
this.property2 = parameter2;
...
...
When a function is called with the new operator, it does the following steps:
Example:
this.color = color;
this.brand = brand;
this.start = function() {
console.log("started");
};
console.log(car1); // Car { }
Here,
car1 is instance
new new
3. JS Functions
name
length
constructor
prototype, etc.
apply()
bind()
call()
toString(), etc.
Example:
this.color = color;
this.brand = brand;
this.start = function() {
console.log("started");
};
console.log(Car.name); // Car
Example:
this.color = color;
this.brand = brand;
this.start = function() {
console.log("started");
};
console.log(Car.length); // 2
Example:
this.color = color;
this.brand = brand;
this.start = function() {
console.log("started");
};
console.log(typeof(Car)); // function
Example:
this.color = color;
this.brand = brand;
this.start = function() {
console.log("started");
};
function Date()
function Error()
function Promise()
function Object()
function String()
In JavaScript, date and time are represented by the Date object. The Date object provides the date
and time information and also provides various methods.
new Date()
new Date(milliseconds)
new Date(datestring)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
You can create a date object without passing any arguments to the new Date() constructor function.
For example,
console.log(typeof(now)); // object
Here, new Date() creates a new date object with the current date and local time.
Note:
1. Coordinated Universal Time (UTC) - It is the global standard time defined by the World Time
Standard. (This time is historically known as Greenwich Mean Time, as UTC lies along the
meridian that includes London and nearby Greenwich in the United Kingdom.)
The Date object contains a number that represents milliseconds since 1 January 1970 UTC.
The new Date(milliseconds) creates a new date object by adding the milliseconds to zero time.
For example,
The new Date(date string) creates a new date object from a date string.
Example:
The month can be full or abbreviated. Also, month names are case insensitive.
For example,
let time1 = new Date(2021, 1, 20, 4, 12, 11, 0);
For example,
Warning
If you pass only one argument, it is treated as milliseconds. Hence, you have to pass two
arguments to use this date format.
When you assign out of range values in the Date object, it auto-corrects itself.
For example,
There are methods to access and set values like a year, month, etc. in the Date Object.
Method Description
Returns the numeric value corresponding to the current time (the number of milliseconds passed since January 1, 1970, 00:00:00
now()
UTC)
getDate() Gets the day of the month (1–31) according to local time
getDay() Gets the day of the week (0-6) according to local time
getUTCDate() Gets the day of the month (1–31) according to universal time
Example:
console.log(date1.getFullYear()); // 1947
console.log(date1.getMonth()); // 7
date1.setYear(2021);
date1.setDate(1);
In Object methods, it refers to the object that is executing the current function.
In Regular functions, it refers to the window object.
In Arrow functions, it refers to the context in which the code is defined.
1.1 this in Object Methods
Example:
let car = {
color: "blue",
brand: "Audi",
start: function() {
};
car.start();
In the above example, this refers to the car object as it's executing the method start.
Example:
function start() {
console.log(this); // Window { }
start();
Arrow function inherits this from the context in which the code is defined.
Example:
let car = {
color: "blue",
brand: "Audi",
start: () => {
console.log(this); // Window { }
}
};
car.start();
let car = {
color: "blue",
brand: "Audi",
start: function() {
setTimeout(() => {
}, 1000);
};
car.start();
Example:
this.color = color;
this.brand = brand;
this.start = function() {
console.log(this); // Car { }
};
car1.start();
this.color = color;
this.brand = brand;
this.start = () => {
console.log(this); // Car { }
};
car1.start();
2.1 Immutable
Number
String
Boolean
Symbol
Undefined, etc.
Example:
let x = 5;
let y = x;
y = 10;
console.log(x); // 5
console.log(y); // 10
2.2 Mutable
Object
Array
Function
Example:
let x = { value: 5 };
let y = x;
let z = { value: 20 };
y.value = 10;
y = z;
3. Declaring Variables
Using let
Using const
Using var
3.1 let
Example:
let x;
x = 10;
console.log(x); // 10
x = 15;
console.log(x); // 15
3.2 const
While declaring variables using const,
Initialization is mandatory
Once a value is initialized, then it can't be reassigned
Without Initialization:
const x;
Reassignment:
const x = 7;
Example:
const car = {
color : "blue",
brand : "Audi"
};
car.color = "red";
console.log(car.color); // red
const car = {
color : "blue",
brand : "Audi"
};
car.color = "red";
function Array()
function Function()
function Promise()
function Object()
function String()
2. Built-in
Array
Constructor Function
Properties:
constructor
length
prototype, etc.
Methods:
push()
pop()
splice()
shift(), etc.
2.2 Creating an Array with the new Operator (Older way of writing)
Syntax:
Example:
console.log(myArray.length); // 4
3. Prototype Property
The Prototype property will be shared across all the instances of their constructor function.
Example: console.log(Array.prototype);
console.log(Object.getPrototypeOf(myArray));
On calling the new() operator, all the properties and methods defined on the prototype will become
accessible to the instance objects. This process is called Prototypal Inheritance.
Properties:
name
length
constructor
prototype, etc.
Methods:
apply()
bind()
call()
toString(), etc.
4.2 Creating a Function with the new Operator (Older way of writing)
`this.color = color;
this.brand = brand;
this.start = function() {
console.log("started");
};`);
console.log(Function.prototype);
The Prototype Properties/ Methods are the properties or methods common across the instance
objects.
Examples:
calculateAge
displayGreetings
displayProfileDetails
calculateIncome
Example:
this.firstName = firstName;
this.lastName = lastName;
Person.prototype.displayFullName = function() {
};
The Instance Specific Properties/ Methods are the properties or methods specific to the instance
object.
Examples:
gender
yearOfBirth
friendsList
name
Example:
this.firstName = firstName;
this.lastName = lastName;
Person.prototype.displayFullName = function() {
};
console.log(Object.getOwnPropertyNames(person1));
The class is a special type of function used for creating multiple objects.
The constructor method is a special method of a class for creating and initializing an object of that
class.
Syntax:
class MyClass {
constructor(property1, property2) {
this.property1 = property1;
this.property2 = property2;
method1() { ... }
method2() { ... }
Syntax :
class MyClass {
constructor(property1, property2) {
this.property1 = property1;
this.property2 = property2;
method1() { ... }
method2() { ... }
Example :
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
displayFullName() {
}
let person1 = new Person("Virat", "Kohli");
Example:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
Example:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
displayFullName() {
The Instance Prototype refers to the prototype object of the constructor function.
Example:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
displayFullName() {
Note
The Type of a class is a function
2.Inheritance in JS Classes
The Inheritance is a mechanism by which a class inherits methods and properties from another class.
2.1 Extends
The extends keyword is used to inherit the methods and properties of the superclass.
2.2 Super
Calling super() makes sure that SuperClass constructor() gets called and initializes the instance.
Syntax :
class SuperClass {
constructor(property1, property2){
super(property1);
this.property2 = property2;
method1() { }
Here the constructor method is overridden. If we write the SuperClass methods in SubClass, it is
called method overriding.
Syntax :
class SuperClass {
constructor(property1, property2){
super(property1);
this.property2 = property2;
Example:
class Animal {
constructor(name) {
this.name = name;
eat() {
}
makeSound() {
constructor(name, breed) {
super(name);
this.breed = breed;
sniff() {
constructor(name, breed) {
super(name);
this.breed = breed;
knead() {
3.this in classes
Example:
class Animal {
constructor(name) {
this.name = name;
eat() {
return this;
makeSound() {
Example:
class Animal {
constructor(name) {
this.name = name;
constructor(name, breed) {
super(name);
this.breed = breed;
sniff() {
return this;
Example :
alert("First Line");
alert("Second Line");
alert("Third Line");
The code executes line by line. This behavior is called synchronous behavior, in JS alert works
synchronously.
2. Asynchronous Execution
Example 1:
const url = "https://apis.ccbp.in/jokes/random";
fetch(url)
.then((response) => {
return response.json();
})
.then((jsonData) => {
//statement-1
console.log(jsonData); // Object{ value:"The computer tired when it got home because it had a
hard drive" }
});
//statement-2
In the above example, the second statement won’t wait until the first statement execution. In JS,
fetch() works asynchronously.
3. JS Promises
2. A promise is an object that represents a result of operation that will be returned at some
point in the future.
Example :
const url = "https://apis.ccbp.in/jokes/random";
Note
A promise will be in any one of the three states:
Example:
responsePromise.then((response) => {
console.log(response); // Response{ … }
});
Example:
responsePromise.then((response) => {
return response;
});
responsePromise.catch((error) => {
});
Syntax :
responsePromise
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
Example:
responsePromise.then((response) => {
console.log(response.json());
});
Example:
responsePromise
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
Example:
responsePromise
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data); // Object { value: "They call it the PS4 because there are only 4 games worth
playing!"
})
.catch((error) => {
console.log(error);
});
JS Promises | Part 2 | Cheat Sheet
1. Asynchronous JS code style
There are two main types of asynchronous code style you'll come across in JavaScript:
Callback based
Promise based
Example : fetch()
Promises are the new style of async code that you'll see used in modern JavaScript.
Syntax :
const myPromise = new Promise((resolveFunction, rejectFunction) => {
//Async task
});
The Promise constructor takes a function (an executor) that will be executed immediately
and passes in two functions: resolve, which must be called when the Promise is resolved
(passing a result), and reject when it is rejected (passing an error).
The executor is to be executed by the constructor, during the process of constructing the
new Promise object.
Example :
const myPromise = () => {
setTimeout(() => {
resolve();
}, 1000);
});
};
console.log(myPromise());
Example :
const myPromise = () => {
setTimeout(() => {
resolve("Promise Resolved");
}, 1000);
});
};
myPromise().then((fromResolve) => {
});
Example :
const myPromise = () => {
setTimeout(() => {
reject("Promise Rejected");
}, 2000);
});
};
myPromise()
.then((fromResolve) => {
console.log(fromResolve);
})
.catch((fromReject) => {
});
3. Async/Await
1. The Async/Await is a modern way to consume promises.
2. The Await ensures processing completes before the next statement executes.
Syntax :
const myPromise = async () => {
};
myPromise();
Note
1. Use async keyword before the function only if it is performing async operations.
2. Should use await inside an async function only.
Example :
console.log(jsonData);
};
doNetworkCall();
Example :
const url = "https://a.ccbp.in/jokes/random";
try {
console.log(jsonData);
} catch (error) {
console.log(error);
};
doNetworkCall();
Example :
const url = "https://apis.ccbp.in/jokes/random";
console.log(jsonData);
};
console.log(asyncPromise);
4. String Manipulations
4.1 trim()
Syntax : string.trim()
Example:
console.log(greeting);
console.log(greeting.trim());
4.2 slice()
The slice() method extracts a section of a string and returns it as a new string, without modifying the
original string.
Example:
console.log(text.slice(2, 3)); // e
4.3 toUpperCase()
Syntax : string.toUpperCase()
Example:
4.4 toLowerCase()
Syntax : string.toLowerCase()
Example:
4.5 split()
The split() method is used to split a string into an array of substrings and returns the new array.
Example:
4.6 replace()
The replace() method searches a string for a specified value, or a regular expression, and returns a
new string where the specified values are replaced.
Example:
The includes() method determines whether a string contains the characters of a specified string.
It returns true if the string contains the value, otherwise it returns false.
Example:
console.log(word); // true
console.log(number); // false
4.8 concat()
Example:
console.log(str1.concat(str2)); // HelloWorld
console.log(str1.concat(" Pavan", ". Have a nice day.")); // Hello Pavan. Have a nice day.
4.9 indexOf()
The indexOf() method returns the position of the first occurrence of a specified value in a string.
Example:
console.log(str.indexOf("Global")); // 9
console.log(str.indexOf("up")); // 21
4.10 startsWith()
The startsWith() method determines whether a string begins with the characters of a specified
string, returning true or false as appropriate.
Syntax : string.startsWith(searchvalue, start)
Example:
console.log(str.startsWith("rld")); // false
console.log(str.startsWith("World")); // true
4.11 endsWith()
The endsWith() method determines whether a string ends with the characters of a specified string,
returning true or false as appropriate.
Example:
console.log(str.endsWith("you?")); // true
console.log(str.endsWith("re")); // false
4.12 toString()
Syntax : string.toString()
Example:
console.log(newNumber); // 46
4.13 substring()
The substring() method returns the part of the string between the start and end indexes, or to the
end of the string.
Example:
4.14 Length
Syntax : string.length
Example:
console.log(str.length); // 34