Javscript Essentials
Javscript Essentials
1. Spread Operator
The Spread Operator is used to unpack an iterable (e.g. an array, object, etc.) into individual elements.
JAVASCRIPT
1 let arr1 = [2, 3];
2 let arr2 = [1, ...arr1, 4];
3
4 console.log(arr2); // [1, 2, 3, 4]
JAVASCRIPT
1 let arr1 = [2, 3];
2 let arr2 = [...arr1];
3
4 console.log(arr2); // [2, 3]
1.1.2 Concatenation
JAVASCRIPT
1 let arr1 = [2, 3];
2 let arr2 = [4, 5];
3 let arr3 = [...arr1, ...arr2];
4
5 console.log(arr3); // [2, 3, 4, 5]
JAVASCRIPT
1 let person = { name: "Rahul", age: 27 };
2 let personDetails = { ...person, city: "Hyderabad" };
3
4 console.log(personDetails); // Object {name: "Rahul", age: 27, city: "Hyderabad"}
JAVASCRIPT
1 let person = { name: "Rahul", age: 27 };
2 let personDetails = { ...person };
3
4 console.log(personDetails); // Object {name: "Rahul", age: 27}
1.2.2 Concatenation
JAVASCRIPT
1 let person = { name: "Rahul", age: 27 };
2 let address = { city: "Hyderabad", pincode: 500001 };
3 let personDetails = { ...person, ...address };
4
5 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.
JAVASCRIPT
1 function add(a, b, c) {
2 return a + b + c;
3 }
4 let numbers = [1, 2, 3, 4, 5];
5
6 console.log(add(...numbers)); // 6
Try out the spread operator with arrays, objects, and function calls in the JavaScript Code Playground.
2. Rest Parameter
JAVASCRIPT
1 function numbers(...args) {
2 console.log(args); // [1, 2, 3]
3 }
4
5 numbers(1, 2, 3);
2.1.1 Arrays
JAVASCRIPT
1 let [a, b, ...rest] = [1, 2, 3, 4, 5];
2
3 console.log(a); // 1
4 console.log(b); // 2
5 console.log(rest); // [3, 4, 5]
2.1.2 Objects
JAVASCRIPT
1 let { firstName, ...rest } = {
2 firstName: "Rahul",
3 lastName: "Attuluri",
4 age: 27
5 };
6
7 console.log(firstName); // Rahul
8 console.log(rest); // Object {lastName: "Attuluri", age: 27}
Note
The Rest parameter should be the last parameter.
JAVASCRIPT
1 function numbers(a, b, ...rest) {
2 console.log(a); // 1
3 console.log(b); // 2
4 console.log(rest); // [3, 4, 5]
5 }
6 numbers(1, 2, 3, 4, 5);
JAVASCRIPT
1 function numbers(a, ...rest, b) {
2 console.log(a);
3 console.log(rest);
4 console.log(b);
5 }
6 numbers(1, 2, 3, 4, 5); // Uncaught SyntaxError: Rest parameter must be last formal parameter
3. Functions
JAVASCRIPT
1 function numbers(a = 2, b = 5) {
2 console.log(a); // 3
3 console.log(b); // 5
4 }
5
6 numbers(3);
Try out the Rest Parameter and Default Parameters in the JavaScript Code Playground.
We can include the variables or expressions using a dollar sign with curly braces
${ } .
JAVASCRIPT
1 let firstName = "Rahul";
2
3 console.log(`Hello ${firstName}!`); // Hello Rahul!
Try out including the variables, expressions, and multiline strings using the Template Literals in the JavaScript Code Playground.
MARKED AS COMPLETE
Submit Feedback
1. Operators
Syntax:
JAVASCRIPT
1 let speed = 70;
2 let message = speed >= 100 ? "Too Fast" : "OK";
3
4 console.log(message); // OK
2. Conditional Statements
Syntax:
switch (expression) {
case value1:
/*Statements executed when the
result of expression matches value1*/
break;
case value2:
/*Statements executed when the
result of expression matches value2*/
break;
...
Expand
JAVASCRIPT
1 let day = 1;
2 switch (day) {
3 case 0:
4 console.log("Sunday");
5 break;
6 case 1:
7 console.log("Monday"); // Monday
8 break;
9 case 2:
10 console.log("Tuesday");
Expand
If there is no
break statement, then the execution continues with the next case until the break statement is met.
JAVASCRIPT
1 let day = 4;
2 switch (day) {
3 case 0:
4 console.log("Sunday");
5 break;
6 case 1:
7 console.log("Monday");
8 break;
9 case 2:
10 console.log("Tuesday");
Expand
3. Defining Functions
Function Declaration
Function Expression
Arrow Functions
Function Constructor, etc.
Syntax:
JAVASCRIPT
1 let sum = (a, b) => {
2 let result = a + b;
3 return result;
4 };
5 console.log(sum(4, 3));
return statement and curly braces are not required for simple expressions.
JAVASCRIPT
1 let sum = (a, b) => a + b;
2
3 console.log(sum(4, 3)); // 7
JAVASCRIPT
1 let greet = name => `Hi ${name}!`;
2
3 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.
JAVASCRIPT
1 let sayHi = () => "Hello!";
2
3 console.log(sayHi()); // Hello!
JAVASCRIPT
1 let createUser = name => {
2 return {
3 firstName: name
4 };
5 };
6
7 console.log(createUser("Rahul")); // Object {firstName: "Rahul"}
Simple Expression
JAVASCRIPT
1 let createUser = name => { firstName: "Rahul" };
2
3 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.
JAVASCRIPT
1 let createUser = name => ({ firstName: "Rahul" });
2
3 console.log(createUser()); // Object {firstName: "Rahul"}
Try out the Ternary Operator, Switch Statements, Arrow Functions in the JavaScript Code Playground.
Factory and Constructor Functions | Cheat Sheet
1. Factory Function
A Factory function is any function that returns a new object for every function call.
Syntax:
JAVASCRIPT
1 function createCar(color, brand) {
2 return {
3 color: color,
4 brand: brand,
5 start: function() {
6 console.log("started");
7 }
8 };
9 }
10
Expand
JAVASCRIPT
1 function createCar(color, brand) {
2 return {
3 color,
4 brand,
5 start() {
6 console.log("started");
7 }
8 };
9 }
10
Expand
2. Constructor Function
Syntax:
JAVASCRIPT
1 function Car(color, brand) {
2 this.color = color;
3 this.brand = brand;
4 this.start = function() {
5 console.log("started");
6 };
7 }
8
9 let car1 = new Car("blue", "Audi");
10 console.log(car1); // Car { }
Here,
Doesn't need new operator for function calling Needs new operator for function calling
Try out the Factory and Constructor Functions in the JavaScript Code Playground.
3. JS Functions
name
length
constructor
prototype, etc.
apply()
bind()
call()
toString(), etc.
JAVASCRIPT
1 function Car(color, brand) {
2 this.color = color;
3 this.brand = brand;
4 this.start = function() {
5 console.log("started");
6 };
7 }
8 console.log(Car.name); // Car
JAVASCRIPT
1 function Car(color, brand) {
2 this.color = color;
3 this.brand = brand;
4 this.start = function() {
5 console.log("started");
6 };
7 }
8 console.log(Car.length); // 2
JAVASCRIPT
1 function Car(color, brand) {
2 this.color = color;
3 this.brand = brand;
4 this.start = function() {
5 console.log("started");
6 };
};
7 }
8 console.log(typeof(Car)); // function
The constructor property refers to the constructor function that is used to create the object.
JAVASCRIPT
1 function Car(color, brand) {
2 this.color = color;
3 this.brand = brand;
4 this.start = function() {
5 console.log("started");
6 };
7 }
8 let car1 = new Car("blue", "Audi");
9 console.log(car1.constructor); // f Car(color, brand) {}
function Date()
function Error()
function Promise()
function Object()
function String()
function Number(), etc.
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
For example,
JAVASCRIPT
1 let now = new Date();
2
3 console.log(now); // Tue Feb 02 2021 19:10:29 GMT+0530 (India Standard Time) { }
4 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.)
2. Local Time - The user's device provides the local time.
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,
JAVASCRIPT
1 let time1 = new Date(0);
2 console.log(time1); // Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time) { }
3
4 // 100000000000 milliseconds from 1 Jan 1970 UTC
5 let time2 = new Date(100000000000);
6 console.log(time2); // Sat Mar 03 1973 15:16:40 GMT+0530 (India Standard Time) { }
Note
The
new Date(date string) creates a new date object from a date string.
Syntax:
new Date(datestring);
JAVASCRIPT
1 let date = new Date("2021-01-28");
2
3 console.log(date); // Thu Jan 28 2021 05:30:00 GMT+0530 (India Standard Time) { }
You can also pass only the year and month or only the year. For example,
JAVASCRIPT
1 let date = new Date("2020-08");
2 console log(date); // Sat Aug 01 2020 05:30:00 GMT+0530 (India Standard Time) { }
2 console.log(date); // Sat Aug 01 2020 05:30:00 GMT+0530 (India Standard Time) { }
3
4 let date1 = new Date("2020");
5 console.log(date1); // Wed Jan 01 2020 05:30:00 GMT+0530 (India Standard Time) { }
JAVASCRIPT
1 let date2 = new Date("1 Jul 2021");
2 console.log(date2); // Thu Jul 01 2021 00:00:00 GMT+0530 (India Standard Time) { }
The month can be full or abbreviated. Also, month names are case insensitive.
JAVASCRIPT
1 let date3 = new Date("July 1 2021");
2 console.log(date3); // Thu Jul 01 2021 00:00:00 GMT+0530 (India Standard Time) { }
3
4 // commas are ignored
5 let date4 = new Date("JULY, 1, 2021");
6 console.log(date4); // Thu Jul 01 2021 00:00:00 GMT+0530 (India Standard Time) { }
For example,
JAVASCRIPT
1 let time1 = new Date(2021, 1, 20, 4, 12, 11, 0);
2 console.log(time1); // Sat Feb 20 2021 04:12:11 GMT+0530 (India Standard Time) { }
Here, months are counted from 0 to 11. January is 0 and December is 11.
If four numbers are passed, it represents the year, month, day and hours.
For example,
JAVASCRIPT
1 let time1 = new Date(2021, 1, 20, 4);
2 l l (ti 1) // S t F b 20 2021 04 00 00 GMT+0530 (I di St d d Ti ) { }
2 console.log(time1); // Sat Feb 20 2021 04:00:00 GMT+0530 (India Standard Time) { }
For example,
JAVASCRIPT
1 let time1 = new Date(2020, 1);
2 console.log(time1); // Sat Feb 20 2021 04:00:00 GMT+0530 (India Standard Time) { }
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,
JAVASCRIPT
1 let date = new Date(2008, 0, 33);
2 // Jan does not have 33 days
3 console.log(date); // Sat Feb 02 2008 00:00:00 GMT+0530 (India Standard Time) { }
There are methods to access and set values like a year, month, etc. in the Date Object.
Method Description
now() Returns the numeric value corresponding to the current time (the number of milliseconds passed since January 1, 1970, 00:00:00 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
JAVASCRIPT
1 let date1 = new Date(1947, 7, 15);
2 date1.setYear(2021);
3 date1.setDate(1);
4
5 console.log(date1); // Sun Aug 01 2021 00:00:00 GMT+0530 (India Standard Time) { }
Try out the JS function properties and Date Methods in the JavaScript Code Playground.
More Modern JS Concepts | Part 3 | Cheat Sheet
1. this
The
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.
JAVASCRIPT
1 let car = {
2 color: "blue",
3 brand: "Audi",
4 start: function() {
5 console.log(this); // Object { color: "blue", brand: "Audi", start: ƒ() }
6 }
7 };
8
9 car.start();
this refers to the car object as it's executing the method start .
JAVASCRIPT
1 function start() {
2 console.log(this); // Window { }
3 }
4 start();
In Arrow functions,
In Constructor Function,
JAVASCRIPT
1 function Car(color, brand) {
2 this.color = color;
3 this.brand = brand;
4 this.start = () => {
5 console.log(this); // Car { }
6 };
7 }
8
9 let car1 = new Car("blue", "Audi");
10 car1.start();
this in different functions like Object Methods, Arrow Functions, and Constructor Functions etc. in the JavaScript Code Playground.
2.1 Immutable
Number
String
Boolean
Symbol
Undefined, etc.
JAVASCRIPT
1 let x = 5;
2 let y = x;
3 y = 10;
4
5 console.log(x); // 5
6 console.log(y); // 10
2.2 Mutable
Object
Array
Function
JAVASCRIPT
1 let x = { value: 5 };
2 let y = x;
3 let z = { value: 20 };
4
5 y.value = 10;
6
7 console.log(x); // Object { value: 10 }
8 console.log(y); // Object { value: 10 }
9
10 y = z;
Expand
3. Declaring Variables
Using let
Using const
Using var
3.1 let
let ,
JAVASCRIPT
1 let x;
2 x = 10;
3
4 console.log(x); // 10
5
6 x = 15;
7 console.log(x); // 15
3.2 const
const ,
Initialization is mandatory
Once a value is initialized, then it can't be reassigned
Without Initialization:
JAVASCRIPT
1 const x;
2
3 x = 7; // SyntaxError {"Const declarations require an initialization value (1:21)"}
Reassignment:
JAVASCRIPT
1 const x = 7;
2
3 x = 9; // TypeError {"Assignment to constant variable."}
JAVASCRIPT
1 const car = {
2 color : "blue",
3 brand : "Audi"
4 };
5 car.color = "red";
6
7 console.log(car.color); // red
JAVASCRIPT
1 const car = {
2 color : "blue",
3 brand : "Audi"
4 };
5 car.color = "red";
6
7 car = {}; // TypeError {"Assignment to constant variable."}
Try out the Mutable and Immutable values and declare the variables using
function Array()
function Function()
function Promise()
function Object()
function String()
function Number(), etc.
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:
JAVASCRIPT
1 let myArray = new Array("a", 2, true);
2 myArray.push("pen");
3
4 console.log(myArray); // Array (4)["a", 2, true, "pen"]
5 console.log(myArray.length); // 4
3. Prototype Property
The Prototype property will be shared across all the instances of their constructor function.
JAVASCRIPT
1 console.log(Array.prototype);
JAVASCRIPT
1 let myArray = new Array("a", 2, true);
2 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)
Syntax:
JAVASCRIPT
1 let Car = new Function("color, brand",
2 `this.color = color;
3 this.brand = brand;
4 this.start = function() {
5 console.log("started");
6 };`);
7
8 console.log(Function.prototype);
The Prototype Properties/ Methods are the properties or methods common across the instance objects.
Examples:
calculateAge
displayGreetings
displayProfileDetails
calculateIncome
JAVASCRIPT
1 function Person(firstName, lastName) {
2 this.firstName = firstName;
3 this.lastName = lastName;
4 }
5
6 Person.prototype.displayFullName = function() {
7 return this.firstName + " " + this.lastName;
8 };
9
10 let person1 = new Person("Virat", "Kohli");
Expand
5.2 Instance Specific Properties/ Methods
The Instance Specific Properties/ Methods are the properties or methods specific to the instance object.
Examples:
gender
yearOfBirth
friendsList
name
JAVASCRIPT
1 function Person(firstName, lastName) {
2 this.firstName = firstName;
3 this.lastName = lastName;
4 }
5
6 Person.prototype.displayFullName = function() {
7 return this.firstName + " " + this.lastName;
8 };
9
10 let person1 = new Person("Virat", "Kohli");
Expand
Submit Feedback
JS Classes | Cheat Sheet
1. Class
The
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() { ... } } let myObject = new
MyClass(property1, property2);
Example :
JAVASCRIPT
1 class Person {
2 constructor(firstName, lastName) {
3 this.firstName = firstName;
4 this.lastName = lastName;
5 }
6 displayFullName() {
7 return this.firstName + " " + this.lastName;
8 }
9 }
10 let person1 = new Person("Virat", "Kohli");
Expand
JAVASCRIPT
1 class Person {
2 constructor(firstName, lastName) {
3 this.firstName = firstName;
4 this.lastName = lastName;
5 }
6 }
7 let person1 = new Person("Virat", "Kohli");
8 let person2 = new Person("Sachin", "Tendulkar");
9
10 console.log(person1); // Person {...}
Expand
JAVASCRIPT
1 class Person {
2 constructor(firstName, lastName) {
3 this.firstName = firstName;
4 this.lastName = lastName;
5 }
6 displayFullName() {
7 return this.firstName + " " + this.lastName;
8 }
9 }
10 let person1 = new Person("Virat", "Kohli");
Expand
The Instance Prototype refers to the prototype object of the constructor function.
JAVASCRIPT
1 class Person {
2 constructor(firstName, lastName) {
3 this.firstName = firstName;
4 this.lastName = lastName;
5 }
6 displayFullName() {
7 return this.firstName + " " + this.lastName;
8 }
9 }
10 let person1 = new Person("Virat", "Kohli");
Expand
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 { } class SubClass extends SuperClass{ constructor(property1, property2){ super(property1); this.property2 = property2; } method1() { } } let myObject = new
SubClass(property1, property2);
Here,
Syntax :
class SuperClass { } class SubClass extends SuperClass{ constructor(property1, property2){ super(property1); this.property2 = property2; } } let myObject = new SubClass(property1,
property2);
Example :
JAVASCRIPT
1 class Animal {
1 class Animal {
2 constructor(name) {
3 this.name = name;
4 }
5 eat() {
6 return `${this.name} is eating`;
7 }
8 makeSound() {
9 return `${this.name} is shouting`;
10 }
Expand
Try out creating superclass and subclass with multiple objects in the JavaScript Code Playground.
In class,
Here
JAVASCRIPT
1 class Animal {
2 constructor(name) {
( ) {
3 this.name = name;
4 }
5 }
6
7 class Dog extends Animal {
8 constructor(name, breed) {
9 super(name);
10 this.breed = breed;
Expand
Submit Feedback
JS Promises | Cheat Sheet
1. Synchronous Execution
Example :
JAVASCRIPT
1 alert("First Line");
2 alert("Second Line");
3 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:
JAVASCRIPT
1 const url = "https://apis.ccbp.in/jokes/random";
2
3 fetch(url)
4 .then((response) => {
5 return response.json();
6 })
7 .then((jsonData) => {
8 //statement-1
9 console.log(jsonData); // Object{ value:"The computer tired when it got home because it had a hard drive" }
10 });
Expand
In the above example, the second statement won’t wait until the first statement execution. In JS,
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 :
JAVASCRIPT
1 const url = "https://apis.ccbp.in/jokes/random";
2 let responseObject = fetch(url);
3
4 console.log(responseObject); // Promise{ [[PromiseStatus]]:pending, [[PromiseValue]]:undefined }
5 console.log("fetching done"); // fetching done
Note
JAVASCRIPT
1 const url = "https://apis.ccbp.in/jokes/random";
2 let responsePromise = fetch(url);
3
4 responsePromise.then((response) => {
5 console.log(response); // Response{ … }
6 });
JAVASCRIPT
1 const url = "https://a.ccbp.in/random";
2 let responsePromise = fetch(url);
3
4 responsePromise.then((response) => {
5 return response;
6 });
7 responsePromise.catch((error) => {
8 console.log(error); // TypeError{ "Failed to fetch" }
9 });
Combining multiple
Syntax :
responsePromise
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
JAVASCRIPT
1 const url = "RESOURCE_URL";
2 let responsePromise = fetch(url);
3
4 responsePromise.then((response) => {
5 console.log(response.json());
6 });
JAVASCRIPT
1 const url = "https://apis.ccbp.in/jokes/random";
2 let responsePromise = fetch(url);
3
4 responsePromise
5 .then((response) => {
6 return response.json();
7 })
8 .then((data) => {
9 console.log(data); // Object { value: "They call it the PS4 because there are only 4 games worth playing!"
10 })
Expand
Submit Feedback
JS Promises | Part 2 | Cheat Sheet
There are two main types of asynchronous code style you'll come across in JavaScript:
Callback based
Example :
setTimeout() , setInterval()
Promise based
Example :
fetch()
Promises are the new style of async code that you'll see used in modern JavaScript.
Syntax :
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 :
JAVASCRIPT
1 const myPromise = () => {
2 return new Promise((resolve, reject) => {
3 setTimeout(() => {
4 resolve();
4 resolve();
5 }, 1000);
6 });
7 };
8
9 console.log(myPromise());
When
Example :
JAVASCRIPT
1 const myPromise = () => {
2 return new Promise((resolve, reject) => {
3 setTimeout(() => {
4 resolve("Promise Resolved");
5 }, 1000);
6 });
7 };
8
9 myPromise().then((fromResolve) => {
10 console.log(fromResolve); // Promise Resolved
Expand
When
Example :
JAVASCRIPT
1 const myPromise = () => {
2 return new Promise((resolve, reject) => {
3 setTimeout(() => {
4 reject("Promise Rejected");
5 }, 2000);
6 });
7 };
8
9 myPromise()
10 .then((fromResolve) => {
Expand
3. Async/Await
Syntax :
myPromise();
Note
Example :
JAVASCRIPT
1 const url = "https://apis.ccbp.in/jokes/random";
2
3 const doNetworkCall = async () => {
4 const response = await fetch(url);
5 const jsonData = await response.json();
6 console.log(jsonData);
7 };
8
9 doNetworkCall();
Example :
JAVASCRIPT
1 const url = "https://a.ccbp.in/jokes/random";
2
3 const doNetworkCall = async () => {
4 try {
5 const response = await fetch(url);
6 const jsonData = await response.json();
7 console.log(jsonData);
8 } catch (error) {
9 console.log(error);
10 }
Expand
Example :
JAVASCRIPT
1 const url = "https://apis.ccbp.in/jokes/random";
2
3 const doNetworkCall = async () => {
4 const response = await fetch(url);
5 const jsonData = await response.json();
6 console.log(jsonData);
7 };
8
9 const asyncPromise = doNetworkCall();
10 console.log(asyncPromise);
4. String Manipulations
4.1 trim()
The
Syntax :
string.trim()
JAVASCRIPT
1 const greeting = " Hello world! ";
2 console.log(greeting);
3 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.
Syntax :
string.slice(start, end)
JAVASCRIPT
1 const text = "The quick brown fox";
2 console.log(text.slice(0, 3)); // The
3 console.log(text.slice(2, 3)); // e
4.3 toUpperCase()
The
Syntax :
string.toUpperCase()
JAVASCRIPT
1 const text = "The quick brown fox";
2 console.log(text.toUpperCase()); // THE QUICK BROWN FOX
4.4 toLowerCase()
The
Syntax :
string.toLowerCase()
JAVASCRIPT
1 const text = "Learn JavaScript";
2 console.log(text.toLowerCase()); // learn javascript
4.5 split()
The
split() method is used to split a string into an array of substrings and returns the new array.
Syntax :
string.split(separator, limit)
JAVASCRIPT
1 const str = "He-is-a-good-boy";
2 const words = str.split("-");
3
4 console.log(words); // ["He", "is", "a", "good", "boy"]
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.
Syntax :
string.replace(specifiedvalue, newvalue)
JAVASCRIPT
1 const str = "Welcome to Hyderabad";
2 const words = str.replace("Hyderabad", "Guntur");
3
4 console.log(words); // Welcome to Guntur
4.7 includes()
1. The
includes() method determines whether a string contains the characters of a specified string.
2. It returns
Syntax :
string.includes(searchvalue, start)
JAVASCRIPT
1 const str = "Learn 4.0 Technologies";
2 const word = str.includes("Tech");
3 const number = str.includes("5.0");
4
5 console.log(word); // true
6 console.log(number); // false
4.8 concat()
The
Syntax :
JAVASCRIPT
1 const str1 = "Hello";
2 const str2 = "World";
3 console.log(str1.concat(str2)); // HelloWorld
4 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.
Syntax :
string.indexOf(searchvalue, start)
JAVASCRIPT
1 const str = "Building Global Startups";
2 console.log(str.indexOf("Global")); // 9
3 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)
JAVASCRIPT
1 const str = "World-class Products";
l l ( i h(" ld")) // f l
2 console.log(str.startsWith("rld")); // false
3 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.
Syntax :
string.endsWith(searchvalue, length)
JAVASCRIPT
1 const str = "How are you?";
2 console.log(str.endsWith("you?")); // true
3 console.log(str.endsWith("re")); // false
4.12 toString()
The
Syntax :
string.toString()
JAVASCRIPT
1 const number = 46;
2 const newNumber = number.toString();
3
4 console.log(newNumber); // 46
5 console.log(typeof newNumber); // string
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.
Syntax :
string.substring(start, end)
JAVASCRIPT
1 const str = "I am learning JavaScript";
2 console.log(str.substring(2, 9)); // am lear
3 console.log(str.substring(6)); // earning JavaScript
4.14 Length
The
Syntax :
string.length
JAVASCRIPT
1 const str = "Upgrade to CCBP Tech 4.0 Intensive";
2 console.log(str.length); // 34
1. Scoping
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 :
JAVASCRIPT
1 let age = 27;
2 if (age > 18) {
3 let x = 0;
4 console.log(x); // 0
5 }
6 console.log(x); // ReferenceError{"x is not defined"}
1. If a variable is declared outside all functions and curly braces ({}), then it is said to be defined in the Global Scope.
2. When a variable declared with let or const is accessed, Javascript searches for the variable in the block scopes first followed by global scopes.
JAVASCRIPT
1 const x = 30;
2 function myFunction() {
3 if (x > 18) {
4 console.log(x); // 30
5 }
6 }
7
8 myFunction();
2. Hoisting
Hoisting is a JavaScript mechanism where function declarations are moved to the top of their scope before code execution.
JAVASCRIPT
1 let x = 15;
2 let y = 10;
3 let result = add(x, y);
4 console.log(result); // 25
5
6 function add(a, b) {
7 return a + b;
8 }
JAVASCRIPT
1 myFunction();
2 let myFunction = function () {
3 let x = 5;
4 console.log(x); // ReferenceError{"Cannot access 'myFunction' before initialization"}
5 };
JAVASCRIPT
1 myFunction();
2 let myFunction = () => {
3 let x = 5;
4 console.log(x); // ReferenceError{"Cannot access 'myFunction' before initialization"}
5 };
map() , forEach() , filter() and reverse() are some of the most commonly used array methods in JavaScript.
3.1 Map()
1. The map() method creates a new array with the results of calling a function for every array element.
2. The map() method calls the provided function once for each element in an array, in order.
Syntax :
1. Here the callback is a function that is called for every element of array.
2. 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.
JAVASCRIPT
1 const numbers = [1, 2, 3, 4];
2 const result = numbers.map((number) => number * number);
3
4 console.log(result); // [1, 4, 9, 16]
3.2 forEach()
The
forEach() method executes a provided function once for each array element. It always returns undefined.
Syntax :
JAVASCRIPT
1 let fruits = ["apple", "orange", "cherry"];
2
3 fruits.forEach((fruit) => console.log(fruit));
3.3 filter()
1. The
filter() method creates a new array filled with all elements that pass the test (provided as a function).
2. 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.
Syntax :
JAVASCRIPT
1 const numbers = [1, -2, 3, -4];
2 const positiveNumbers = numbers.filter((number) => number > 0);
3
4 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.
Syntax :
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.
JAVASCRIPT
1 const array1 = [1, 2, 3, 4];
2 const reducer = (accumulator, currentValue) => accumulator + currentValue;
3
4 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.
Syntax :
JAVASCRIPT
1 let array1 = [32, 33, 16, 20];
2 const result = array1.every((array1) => array1 < 40);
3
4 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.
Syntax :
JAVASCRIPT
1 const myAwesomeArray = ["a", "b", "c", "d", "e"];
2 const result = myAwesomeArray.some((alphabet) => alphabet === "d");
3
4 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()
JAVASCRIPT
1 const myArray = ["iBHubs", "CyberEye", "ProYuga"];
2 const reversedArray = myArray.reverse();
3
4 console.log(reversedArray); // ["ProYuga", "CyberEye", "iBHubs"]
3.8 flat()
The
flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Syntax :
JAVASCRIPT
1 const arr1 = [0, 1, 2, [3, 4]];
2 const arr2 = [0, 1, 2, [[[3, 4]]]];
3
4 console.log(arr1.flat()); // [ 0,1,2,3,4 ]
5 console.log(arr2.flat(2)); // [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()
Try out Mutable and Immutable methods in the JavaScript Code Playground.