Saturday, March 30, 2024

Explain Javascript Async/Await?

"async and await make promises easier to write". async makes a function return a Promise while await makes a function wait for a Promise

Async Syntax:

The keyword async before a function makes the function return a promise:

Example:

async function myFunction() {

  return "Hello";

}

The above is the same as below:

function myFunction() {

  return Promise.resolve("Hello");

}

Await Syntax:

The await keyword can only be used inside an async function.

The await keyword makes the function pause the execution and wait for a resolved promise before it continues:

let value = await promise;

Let us understand this with an example,

function myFunction(some) {

  console.log('Inside myFunction');

}

async function promiseDemonstration(){

let myPromise = new Promise(function(myResolve, myReject) {

   let x = 0;

  if (x == 0) {

    myResolve("OK");

    console.log('Inside If');

    setTimeout(myFunction , 3000);

  } else {

    console.log('Inside else');

    myReject("Error");

  }

});

let value = await myPromise;

console.log('Awaiting Promise'+value);

myPromise.then(

  function(value) {

    console.log('Inside Value');

    myFunction(value);},

  function(error) {

    console.log('Inside Error');

    myFunction(error);}

);

}

promiseDemonstration();

Explain JavaScript Promise Object?

As we have seen earlier, With asynchronous programming, JavaScript programs can start long-running tasks, and continue running other tasks in parallel.

But, asynchronus programmes are difficult to write and difficult to debug.

Because of this, most modern asynchronous JavaScript methods don't use callbacks. Instead, in JavaScript, asynchronous programming is solved using Promises instead.

A Promise contains both the producing code and calls to the consuming code:

Promise Syntax:

let myPromise = new Promise(function(myResolve, myReject) {

// "Producing Code" (May take some time)

  myResolve(); // when successful

  myReject();  // when error

});

// "Consuming Code" (Must wait for a fulfilled Promise)

myPromise.then(

  function(value) { /* code if successful */ },

  function(error) { /* code if some error */ }

);

When the producing code obtains the result, it should call one of the two callbacks:

When     Call

Success     myResolve(result value)

Error     myReject(error object)

Promise Object Properties:

A JavaScript Promise object can be:

Pending

Fulfilled

Rejected

The Promise object supports two properties: state and result.

While a Promise object is "pending" (working), the result is undefined.

When a Promise object is "fulfilled", the result is a value.

When a Promise object is "rejected", the result is an error object.

myPromise.state      myPromise.result

"pending"      undefined

"fulfilled"      a result value

"rejected"      an error object

Let us understand the use of Promise with an example:

function displayValue(some) {

 console.log('Inside displayValue');

}

let myPromise = new Promise(function(myResolve, myReject) {

  let x = 0;

// The producing code (this may take some time)

  if (x == 0) {

    myResolve("OK");

  } else {

    myReject("Error");

  }

});

myPromise.then(

  function(value) {displayValue(value);},

  function(error) {displayValue(error);}

);

Output:

Inside displayValue


Let us understand the use of Promise with setTimeout.

Example Using Callback:

setTimeout( myFunction, 1000);

function myFunction() {

  console.log('Inside myFunction');

}

Output:

Inside myFunction

Example Using Promise:

function myFunction(some) {

  console.log('Inside myFunction');

}

let myPromise = new Promise(function(myResolve, myReject) {

   let x = 1;

  if (x == 1) {

    myResolve("OK");

    console.log('Inside If');

    setTimeout(myFunction , 3000);

  } else {

    console.log('Inside else');

    myReject("Error");

  }

});

myPromise.then(

  function(value) {

    console.log('Inside Value');

    myFunction(value);},

  function(error) {

    console.log('Inside Error');

    myFunction(error);}

);

Output:

Inside If
Inside Value
Inside myFunction

What are classes in Javascript and explain Inheritance?

A JavaScript class is not an object. It is a template for JavaScript objects. Use the keyword class to create a class. 

Always add a method named constructor().

class Employee {

  constructor(name, department) {

    this.name = name;

    this.department = department;

  }

}

The example above creates a class named "Employee".

The class has two initial properties: "name" and "department".

The example below uses the Employee class to create a Employee object.

const myEmp = new Employee("Farukh", IT);

The constructor method is called automatically when a new object is created. The constructor method is a special method.

It has to have the exact name "constructor".

Sample Example to demonstrate class use:

class Employee {

  constructor(name, department) {

    this.name = name;

    this.department = department;

  }

  displayValue() {

    console.log('Name is '+this.name);

    console.log('department is '+this.department);

  }

}

const myEmp = new Employee("Farukh", "IT");

myEmp.displayValue();

Output:

Name is Farukh

department is IT

Class Inheritance:

To create a class inheritance, use the extends keyword.

A class created with a class inheritance inherits all the methods from another class:

class Employee {

  constructor(name, department) {

    this.name = name;

    this.department = department;

  }

}

class Manager extends Employee {

  constructor(name, department, position) {

    super(name, department);

    this.position = position;

  }

  displayValue() {

    console.log('Name is '+this.name);

    console.log('department is '+this.department);

    console.log('position is '+this.position);

  }

}

const myEmp = new Manager("Farukh", "IT", "Consultant");

myEmp.displayValue();

Output:

Name is Farukh

department is IT

position is Consultant

The super() method refers to the parent class.

By calling the super() method in the constructor method, we call the parent's constructor method and gets access to the parent's properties and methods.

Explain JavaScript Callbacks?

 A callback is a function passed as an argument to another function.

In the below example, we can see we are passing displayValue function as an argument to doSum function while calling doSum function.

doSum(2, 3, displayValue);

function displayValue(sum) {

  console.log('callback function called');

  console.log('Sum is '+sum);

}

function doSum(num1, num2, sampleCallbackDemonstration) {

  let sum = num1 + num2;

  sampleCallbackDemonstration(sum);

}

Output:

callback function called

Sum is 5

Note: When you pass a function as an argument, remember not to use parenthesis.

When to Use a Callback?

They above example is to understand the callback syntax.

Where callbacks really shine are in asynchronous functions, where one function has to wait for another function like waiting for a file to load.

In the real world, callbacks are most often used with asynchronous functions.

A typical example is JavaScript setTimeout().

setTimeout(myFunction, 3000);

function myFunction() {

  // some code here

}

In the example above, myFunction is used as a callback.

myFunction is passed to setTimeout() as an argument.

3000 is the number of milliseconds before time-out, so myFunction() will be called after 3 seconds.

With asynchronous programming, JavaScript programs can start long-running tasks, and continue running other tasks in parallel. But, asynchronus programmes are difficult to write and difficult to debug.Because of this, most modern asynchronous JavaScript methods don't use callbacks. Instead, in JavaScript, asynchronous programming is solved using Promises instead.

What is Javascript Object and Object Methods?

Javascript Object:

As we have already learned that JavaScript variables are containers for data values.

The below code assigns a simple value (Mumbai) to a variable named text:

let text="Mumbai";

Objects are variables too. But objects can contain many values.

The below code assigns many values (Mumbai, Maharashtra, India) to a variable named text:

const text = {name:"Mumbai", state:"Maharashtra", country:"India"};

a) object are used to store collections of data and more complex entities.

b) objects can be created using {...} with optional list of properties, a property is "key": "value" pair.

c) Creating an empty object,

let studentDetail = {};

let studentDetail = new Object();

d) Creating an object with properties,

let studentDetail = {

"name": "Test",

"rollNo": 1,

"Full Name": "Test User"

};

e) To access the property values use dot notation or array notation in case of space in key name as shown below,

studentDetail.name  // dot notation

To access full name use array notation as it has space.

studentDetail[Full Name]   // array notation

f) Adding a value to property,

studentDetail.department = 'Computer Science';

g) We may add comma to last property as shown below.

let studentDetail = {

name: "Test",

rollNo: 1,

};

h) To access the keys use,

Object.keys(studentDetail)

i) Use JSON.stringify to convert object to string

var jsonStrng= JSON.stringify(studentDetail);

console.log(jsonStrng);

"{"name":"Test","rollNo":1,"Full Name":"Test User"}"

j) Use JSON.parse to convert string to object

Object = JSON.parse(jsonStrng);

{name: "Test", rollNo: 1, Full Name: "Test User"}

Object Methods:

An object method is an object property containing a function definition.

const person = {

  firstName: "Farukh",

  lastName: "Haider",

  fullName: function() {

    return this.firstName + " "  + this.lastName;

  }

};

console.log(person.fullName());

Output:

Farukh Haider

How to Access JavaScript Object Properties?

The syntax for accessing the property of an object is:

objectName.property

objectName["property"] 

Let us understand this with an example?

const person = {

  fname:" John",

  lname:" Doe",

  age: 25

};

console.log('person'+person.fname);

console.log('person'+person["fname"]);

Output:

person John

person John

We can also iterate over object as shown below:

for (let x in person) {

  console.log(person[x]);

}

Output:

John

Doe

25