JavaScript CheatSheet

Looking for a reliable and comprehensive reference guide to boost your JavaScript skills? Our professional-grade JavaScript cheat sheet is the perfect tool for developers of all levels. Whether you're a beginner or an experienced programmer, our cheat sheet provides a concise and easy-to-use summary of the most essential syntax, functions, and methods in JavaScript.

Our cheat sheet is carefully crafted by industry experts, ensuring that it includes everything you need to know to become proficient in JavaScript development. From basic concepts like variables and data types to advanced topics like object-oriented programming and asynchronous functions, our cheat sheet covers it all.

With clear explanations and practical examples, our cheat sheet makes learning and mastering JavaScript simple and efficient. You'll have all the information you need readily available at your fingertips, helping you be more productive and efficient in your coding projects.

Don't waste any more time searching through long-winded documentation or struggling with complex code snippets. Download our JavaScript cheat sheet today and take your programming skills to the next level!


Table of Content


Show more


# Getting started Javascript


What is Javascript ?

JavaScript is a lightweight, interpreted programming language.

JavaScript is a programming language that powers the dynamic behavior on most websites.

Alongside HTML and CSS, it is a core technology that makes the web run.

console.log()

alert('bestforstudy.com Hello world!');
  
  
  console.log('bestforstudy.com  Hello world!');
  // Output: bestforstudy.com Hello world!

Numbers

let amount = 10;
  
  let price = 5.95;
  
  let count = 0;

Variables

let x = null;
  let name = "bestforstudy.com";
  const found = false;
  
  console.log(name, found, x);
  // Output: bestforstudy.com, false, null
  
  
  var a;
  console.log(a); 
  // Output: undefined

Strings

let single = 'Wheres my bandit hat?';
  let double = "Wheres my bandit hat?";
  
  
  console.log(single.length);
  // Output: 21

Arithmetic Operators

5 + 5 = 10     // Addition
  
  10 - 5 = 5     // Subtraction
  
  5 * 10 = 50    // Multiplication
  
  10 / 5 = 2     // Division
  
  10 % 5 = 0     // Modulo

Comments

// This line will denote a comment
  
  
  /*  
  The below configuration must be 
  changed before deployment. 
  */

Assignment Operators

let number = 120;
  
  // Both statements below will add 10
  number = number + 10;
  number += 10;
  
  console.log(number); 
  // Output: 140

String Interpolation

let age = 10;
  
  
  // String concatenation
  'Jim is ' + age + ' years old.';
  
  
  // String interpolation
  `Jim is ${age} years old.`;

let Keyword

let count; 
  console.log(count); 
  // Output: undefined
  
  
  count = 10;
  console.log(count); 
  // Output: 10

const Keyword

const numberOfColumns = 4;
  
  
  // TypeError: Assignment to constant...
  numberOfColumns = 8;

# Conditionals in Javascript


if Statement

const isRaining = true;
  
  if (isRaining) {
    console.log('It is Raining');
  }
  
  // Output: It is Raining

Ternary Operator

var x=1;
  
  
  result = (x == 1) ? true : false;
  // Output: true

Operators

true || false;       // true
  10 > 5 || 10 > 20;   // true
  false || false;      // false
  10 > 100 || 10 > 20; // false
  
  
  
  // Logical Operator &&
  true && true;        // true
  1 > 2 && 2 > 1;      // false
  true && false;       // false
  4 === 4 && 3 > 1;    // true
  
  
  
  // Comparison Operators
  1 > 3                // false
  3 > 1                // true
  250 >= 250           // true
  1 === 1              // true
  1 === 2              // false
  1 === '1'            // false
  
  
  
  // Logical Operator !
  let lateToWork = true;
  let oppositeValue = !lateToWork;
  
  console.log(oppositeValue); 
  // Output: false

else if

const size = 10;
  
  if (size > 100) {
    console.log('Big');
  } else if (size > 20) {
    console.log('Medium');
  } else if (size > 4) {
    console.log('Small');
  } else {
    console.log('Tiny');
  }
  
  // Output: Small

switch Statement

const food = 'apple';
  
  switch (food) {
    case 'oyster':
      console.log('The taste of the sea');
      break;
    case 'pizza':
      console.log('A delicious pie');
      break;
    default:
      console.log('Enjoy your meal');
  }
  
  // Output: Enjoy your meal

# Functions in JavaScript


Functions

// Defining the function:
  function sum(num1, num2) {
      return num1 + num2;
  }
  
    
  // Calling the function:
  sum(4, 16); 
  // Output: 20

Anonymous Functions

// Named function
  function rocketToMars() {
      return 'BOOM!';
  }
    
    
  // Anonymous function
  const rocketToMars = function() {
  return 'BOOM!';
  }

Arrow Functions (ES6)

// With two arguments
  const sum = (param1, param2) => { 
    return param1 + param2; 
  }; 
  console.log(sum(2,5)); 
  // Output: 7 
  
  
  
  // With no arguments
  const printHello = () => { 
    console.log('hello'); 
  }; 
  printHello(); 
  // Output: hello
  
  
  
  // With a single argument
  const checkWeight = weight => { 
    console.log(`Weight : ${weight}`); 
  }; 
  checkWeight(25); 
  // Output: Weight : 25 
  
  
  
  // Concise arrow functions
  const multiply = (a, b) => a * b; 
  
  console.log(multiply(2, 30)); 
  // Output: 60 

return Keyword

// With return
  function sum(num1, num2) {
      return num1 + num2;
  }
    
  
  // The function doesn't output the sum
  function sum(num1, num2) {
      num1 + num2;
  }

Calling Functions

// Defining the function
  function sum(num1, num2) {
      return num1 + num2;
  }
  
  
  // Calling the function
  sum(2, 9); 
  // Output: 11

Function Expressions

const cat = function() {
      return 'Moew!';
  }

Function Parameters

// The parameter is name
  function sayHello(name) {
    return `Hello, ${name}!`;
  }

Function Declaration

function add(num1, num2) {
      return num1 + num2;
  }

# Scope in Javascript


Scope

function yourFunction() {
    
    var yourName = "bestforstudy.com";
    // Code here can use bestforstudy.com
    
  }
  
  // Code here can't use bestforstudy.com

Block Scoped Variables

const isMarried = true;
  
  
  if (isMarried == true) {
    const statusMessage = 'You married';
  }
  
  
  // Uncaught ReferenceError...
  console.log(statusMessage);

Global Variables

// Variable declared globally
  const yourColor = 'red';
  
  
  function printYourColor() {
    console.log(yourColor);
  }
  
  
  printYourColor(); 
  // Output: red

# Arrays in Javascript


Arrays

const a1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  
  
  // Different data types
  const a2 = [1, 'chicken', false];

Property .length

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  
  numbers.length 
  // Result is: 9

Index

// Accessing an array element
  const myArray = [150, 250, 350];
  
  
  console.log(myArray[0]); 
  // Output: 150
  
  
  console.log(myArray[1]); 
  // Output: 250

Method .push()

// Adding a single element:
  const cart = ['apple', 'banana'];
  cart.push('orange'); 
  
  
  // Adding multiple elements:
  const numbers = [0, 1, 2];
  numbers.push(3, 4, 5);

Method .pop()

const a= ['eggs', 'flour', 'chocolate', 'bread', 'sugar'];
  
  
  const p = a.pop(); // 'sugar'
  
  console.log(a); 
  // Output: ['eggs', 'flour', 'chocolate', 'bread']

Mutable

const names = ['Fizz', 'ZinZhao', 'Jihin', 'Yasuo'];
  
  
  names.push('Nasus');
  // Output: ['Fizz', 'ZinZhao', 'Jihin', 'Yasuo', 'Nasus']

# Loops in Javascript


While Loop

while (condition) {
      // code block to be executed
  }
  
  
  let i = 1;
  while (i < 10) {        
      console.log(i);
      i++;
  }

Reverse Loop

const a = ['Apple', 'Orange'];
  
  
  for (let i = a.length - 1; i >= 0; i--){
    console.log(`${i}. ${items[i]}`);
  }
  
  
  // Output: 2. Orange
  // Output: 1. Apple

DoWhile Statement

x = 0
  i = 0
  
  
  do {
      x = x + i;
      console.log(x)
      i++;
  } while (i < 5);
  
  
  // Output: 0 1 3 6 10

For Loop

for (let i = 0; i < 10; i++) {
      console.log(i);
  };
    
  
  // Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Looping Through Arrays

for (let i = 0; i < array.length; i++){
      console.log(array[i]);
  }
    
  
  // Output: The result will print every item in the array

Break

for (let i = 0; i < 99; i += 1) {
      if (i > 5) {
         break;
      }
      console.log(i)
  }
  
  
  // Output: 0 1 2 3 4 5

Continue

for (i = 0; i < 10; i++) {
      if (i === 3) { 
          continue; 
      }
  
      console.log(i);
  }

Nested

for (let i = 0; i < 2; i += 1) {
  
      for (let j = 0; j < 3; j += 1) {
  
        console.log(`${i}-${j}`);
      }
      
  }

for...in loop

let object = {
      brand: 'Samsung'
      , model: 'Galaxy Note 20'
  };
  
  
  for (const property in object) {
      console.log(`${property}: ${object[property]}`);
  }
  
  // Output:
  // "brand: Samsung"
  // "model: Galaxy Note 20"=

# Iterators in Javascript


Functions Assigned to Variables

let plusSix = (number) => {
    return number + 6;  
  };
  
  
  // f is assigned the value of plusSix
  let f = plusSix;
  
  plusSix(3); 
  // Output: 9
  
  
  // Since f has a function value, it can be invoked. 
  f(9); 
  // Output: 15

Callback Functions

const isEven = (n) => {
      return n % 2 == 0;
  }
    
  
  let printMsg = (evenFunc, num) => {
      const isNumEven = evenFunc(num);
      console.log(`${num} is an even number: ${isNumEven}.`)
  }
   
  
  // Pass in isEven as the callback function
  printMsg(isEven, 4); 
  // Output: The number 4 is an even number: True.

Array Method .reduce()

const array1 = [1, 2, 3, 4];
  const reducer = (previousValue, currentValue) => previousValue + currentValue;
  
  
  // 1 + 2 + 3 + 4
  console.log(array1.reduce(reducer));
  // Output: 10
  
  
  // 5 + 1 + 2 + 3 + 4
  console.log(array1.reduce(reducer, 5));
  // Output: 15

Array Method .map()

const a = ['Iron Man', 'Hulk', 'Spider Man', 'Captain America'];
  
  
  const announcements = a.map(member => {
    return member + ' is a superhero.';
  })
  
  
  console.log(announcements);
  
  // Result:
  // Iron Man is a superhero.
  // Hulk is a superhero.
  // Spider-Man is a superhero.
  // Captain America is a superhero.

Array Method .forEach()

const numbers = [28, 77, 45, 99, 27];
  
  
  numbers.forEach(number => {  
      console.log(number);
  }); 
  
  // Output: 28, 77, 45, 99, 27

Array Method .filter()

const randomNumbers = [4, 11, 42, 14, 39];
  
  
  const filteredArray = randomNumbers.filter(n => {  
      return n > 5;
  });
  
  // Output: 11, 42, 14, 39

# Objects in Javascript


Accessing Properties

const phone = { 
    brand: 'Apple',
    price: { dollar: '$200' }
  };
  
  
  console.log(phone.brand); 
  // Output: Apple
  
  
  console.log(phone.price.dollar); 
  // Output: $200

Naming Properties

// Example of invalid key names
  const trainSchedule = {
      // Invalid because of the space between words.
      platform num: 10, 
  
      // Expressions cannot be keys.
      40 - 10 + 2: 30,
      
      // A + sign is invalid unless it is enclosed in quotations.
      +compartment: 'C'
  }

Non-existent properties

const apple = {
      color: 'red'
  };
  
  
  console.log(apple.place); 
  // Output: undefined

Mutable

const student = {
      name: 'Jack',
      score: 95,
      grade: 'A',
  }
  
  
  console.log(student)
  // { name: 'Jack', score: 95, grade: 'A' }
  
  
  delete student.score
  student.grade = 'B'
  console.log(student)
  // { name: 'Jack', grade: 'B' }
  
  
  student = {}
  // TypeError: Assignment to constant variable.

Assignment shorthand syntax

const person = {
      name: 'Jack',
      age: '30',
  };
  
  
  const { name, age } = person;
  
  
  console.log(name); 
  // Output: 'Jack'
  
  
  console.log(age);  
  // Output: '30'

Delete operator

const person = {
      firstName: "Robin",
      age: 30,
      hobby: "Soccer",
      goal: "Learning JavaScript at bestforstudy.com"
  };
  
  
  delete person.hobby; // or delete person[hobby];
  
  
  console.log(person);
  /* Result:
  
      {
          firstName: "Robin",
          age: 30,
          goal: "Learning JavaScript at bestforstudy.com"
      }
  
  */

Objects as arguments

const origNum = 8;
  const origObj = {color: 'blue'};
  
  
  const changeItUp = (num, obj) => {
    num = 7;
    obj.color = 'red';
  };
  
  
  changeItUp(origNum, origObj);
  
  
  // Will output 8 since integers are passed by value.
  console.log(origNum);
  
  
  // Will output 'red' since objects are passed 
  // by reference and are therefore mutable.
  console.log(origObj.color);

Shorthand object creation

const activity = 'Surfing';
  
  
  const beach = { activity };
  
  
  console.log(beach); 
  // Output: { activity: 'Surfing' }

this Keyword

const dog = {
    name: 'Flower',
    age: 2,
    whatName() {
      return this.name  
    },
    whatAge() {
      return this.age
    }
  };
  
  
  console.log(dog.whatName()); 
  // Output: Flower
  
  
  console.log(dog.whatAge()); 
  // Output: 2

Factory functions

// A factory function that accepts 'name', 
  // 'age', and 'breed' parameters to return 
  // a customized dog object. 
  const dogFactory = (name, age, breed) => {
    return {
      name: name,
      age: age,
      breed: breed,
      bark() {
        console.log('Woof!');  
      }
    };
  };
  
  
  let dog = dogFactory("Flower", 2, true);
  
  console.log(dog.name);
  // Output: Flower
  
  console.log(dog.bark());
  // Output: Woof!

Methods

const engine = {
    // method shorthand, with one argument
    start(adverb) {
      console.log(`The engine starts up ${adverb}...`);
    },  
    // anonymous arrow function expression with no arguments
    sputter: () => {
      console.log('The engine sputters...');
    },
  };
  
  
  engine.start('noisily');
  // Output: The engine starts up noisily...
  
  engine.sputter();
  // Output: The engine sputters...

Getters and setters

const myCat = {
    _name: 'Kitty',
    get name() {
      return this._name;  
    },
    set name(newName) {
      this._name = newName;  
    }
  };
  
  // Reference invokes the getter
  console.log(myCat.name);
  
  // Assignment invokes the setter
  myCat.name = 'Dog';

# Class in Javascript


Static Methods

class Dog {
    constructor(name) {
      this._name = name;  
    }
    
    introduce() { 
      console.log('This is ' + this._name + ' !');  
    }
    
    // A static method
    static bark() {
      console.log('Woof!');  
    }
  }
  
  const myDog = new Dog('Flower');
  myDog.introduce();
  // Output: This is Flower !
  
  
  // Calling the static method
  Dog.bark();
  // Output: Woof!

Class

class Song {
    constructor() {
      this.title;
      this.author;
    }
    
    play() {
      console.log('Song playing!');
    }
  }
  
  const mySong = new Song();
  
  mySong.play();
  // Output: Song playing!

Class Constructor

class Song {
    constructor(title, artist) {
      this.title = title;
      this.artist = artist;
    }
  }
  
  
  const mySong = new Song('Bohemian Rhapsody', 'Queen');
  
  
  console.log(mySong.title);
  // Output: Bohemian Rhapsody

Class Methods

class Song {
    play() {
      console.log('Song is Playing!');
    }
    
    stop() {
      console.log('Song is Stopping!');
    }
  }

extends

// Parent class
  class Media {
    constructor(info) {
      this.publishDate = info.publishDate;
      this.name = info.name;
    }
  }
  
  
  // Child class
  class Song extends Media {
    constructor(songData) {
      super(songData);
      this.artist = songData.artist;
    }
  }
  
  
  const mySong = new Song({ 
    artist: 'Queen', 
    name: 'Bohemian Rhapsody', 
    publishDate: 1975
  });

# Modules in Javascript


Require

// First way declare
  var moduleA = require( "./module-a.js" );
  
  
  // Second way declare, The .js extension is optional
  var moduleA = require( "./module-a" );
  
  // => Both ways will produce the same result.
  
  
  
  // Now the functionality of moduleA can be used
  console.log(moduleA.someFunctionality)

Export

// module "moduleA.js"
  export default function addFive(x) {
      return x + 5;
  }
  
  
  // In main.js
  import cube from './moduleA.js';
  
  
  // Now the `addFive` function can be used straightforwardly.
  console.log(addFive(3)); 
  // Output: 8

Export Module

let Course = {};
  
  
  Course.name = "Learn Javascript at bestforstudy.com"
  
  
  module.exports = Course;

Import keyword

// addFive.js
  export const addFive = (x) => {
      return x + 5
  }
  
  
  // main.js
  import { addFive } from './addFive';
  
  console.log(add(2)); 
  // Output: 7

# JavaScript Promises


Promise

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

Promise states

const promise = new Promise((resolve, reject) => {
    const res = true;
    // An asynchronous operation.
    if (res) {
      resolve('Res is true!!');
    }
    else {
      reject(Error('Res is false!!'));
    }
  });
  
  
  promise.then((res) => console.log(res), (err) => alert(err));

Executor function

const executorFn = (resolve, reject) => {
    resolve('Resolved!');
  };
  
  
  const promise = new Promise(executorFn);

setTimeout()

const loginAlert = () =>{
    alert('You logged into bestforstudy.com');
  };
  
  
  setTimeout(loginAlert, 10000);

.then() method

const promise = new Promise((resolve, reject) => {    
    setTimeout(() => {
      resolve('Your output here!!!');
    }, 5000);
  });
  
  
  promise.then((res) => {
    console.log(res);
  }, (err) => {
    alert(err);
  });

.catch() method

const promise = new Promise((resolve, reject) => {  
    setTimeout(() => {
      reject(Error('Your promise have an error'));
    }, 5000);
  });
  
  
  promise.then((res) => {
    console.log(value);
  });
  
  
  promise.catch((err) => {
    alert(err);
  });

Promise.all()

const promise1 = Promise.resolve(3);
  const promise2 = 55;
  const promise3 = new Promise((resolve, reject) => {
    setTimeout(resolve, 100, 'hello world!');
  });
  
  
  Promise.all([promise1, promise2, promise3]).then((values) => {
    console.log(values);
  });
  
  
  // Output: Array [3, 55, "hello world!"]

Avoiding nested Promise and .then()

const promise = new Promise((resolve, reject) => {  
      setTimeout(() => {
        resolve('*');
      }, 5000);
  });
  
    
  const twoStars = (star) => {  
      return (star + star);
  };
  
  
  const oneDot = (star) => {  
      return (star + '.');
  };
  
  
  const print = (val) => {
      console.log(val);
  };
  
  
  // Chaining them all together
  promise.then(twoStars).then(oneDot).then(print);

Creating

const executorFn = (resolve, reject) => {
      console.log('Inside the executor function !!!');
  };
    
  
  // Create a new promise
  const promise = new Promise(executorFn);

Chaining multiple .then()

const promise = new Promise(resolve => setTimeout(() => resolve('dbestforstudy.com'), 100));
  
  
  promise.then(res => {
      return res === 'bestforstudy.com' ? Promise.resolve('Hello bestforstudy.com!') : Promise.reject('Who are you?')
  }).then((res) => {
      console.log(res)
  }, (err) => {
      alert(err)
  });

# Async-Await in Javascript


What is Async-Await ?

An async function is a function declared with the async keyword, and the await keyword is permitted within them. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

The await operator is used to wait for a Promise. It can only be used inside an async function within regular JavaScript code; however, it can be used on its own with JavaScript modules.

Asynchronous

function hello() {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve('Hello Wellcome to bestforstudy.com !');
        }, 5000);
      });
  }
  
  // Async Function Expression
  const showMessage = async function() {
      const showMsg = await hello();
      console.log('Message:', showMsg);
  }
  
  
  // Async Arrow Function
  const showMessage1 = async () => {
      const showMsg = await hello();
      console.log('Message:', showMsg);
  }
  
  
  showMessage(); 
  // Output: Message: Hello Wellcome to bestforstudy.com ! <-- after 5 seconds
  showMessage1(); 
  // Output: Message: Hello Wellcome to bestforstudy.com ! <-- after 5 seconds

Resolving Promises

// Using the static Promise.resolve method
  Promise.resolve('Hello World').then(function(value) {
      console.log(value);
      // Output: Hello World
  }, function(value) {
      // not called
  });
  
  
  // Resolving an array
  var arr = ['No.1', 'No.2', 'No.3'];
  var p = Promise.resolve(arr);
  p.then(function(v) {
      console.log(v[1]);
      // Output: No.2
  });
  
  
  // Resolving another Promise
  var original = Promise.resolve(105);
  var cast = Promise.resolve(original);
  cast.then(function(value) {
      console.log('value is: ' + value);
  });
  
  console.log('Is original === cast ? ' + (original === cast));
  // Output:
  // Is original === cast ? true
  // value is: 105

Async Await Promises

function hello() {
      return new Promise(resolve => {
          setTimeout(() => {
              resolve('Hello Wellcome to bestforstudy.com !');
          }, 5000);
      });
  }
  
  
  async function showMessage() {
      const msg = await hello();
      console.log('Message:', msg);
  }
    
  
  showMessage(); 
  // Output: Message: Wellcome to bestforstudy.com ! 
  // <-- It will show message after 5 seconds -->

Error Handling

async function errHandler() {
      try{
          const pizza = await Pizza(['Apple']);
          console.log(pizza);
      } catch(err) {
          console.log('Oh No Error !!!');
          console.log(err);
      }
  }
  
  
  errHandler();
  /**
   * Output: 
   
      Oh No Error !!!
      VM57:7 ReferenceError: Pizza is not defined
          at errHandler (:3:23)
          at :12:1
  
   */

Aysnc await operator

function helloWorld() {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve('Hello World!');
        }, 2000);
      });
  }
    
  async function msg() {
      const msg = await helloWorld();
      console.log('Message:', msg);
  }
    
  
  msg(); // Message: Hello World! <-- after 2 seconds

# JavaScript Requests


JSON

const objectJson = {
      "site_name": "bestforstudy.com",
      "cheat_sheet": "JavaScript",
      "type": "JSON",
      "level": 6  
  };

XMLHttpRequest

const xhr = new XMLHttpRequest();
  xhr.open('GET', 'bestforstudy.com/getJsonObject');

GET Method

const req = new XMLHttpRequest();
  req.responseType = 'json';
  req.open('GET', '/getSampleData?sitename=bestforstudy');
  req.onload = () => {
    console.log(xhr.response);
  };
  
  req.send();

POST Method

const loginData = {
      username: 'admin',
      password: 12346
  };
  
  
  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/login');
  xhr.responseType = 'json';
  xhr.send(JSON.stringify(loginData));
  
  
  xhr.onload = () => {
  console.log(xhr.response); // Your response will be here
  };

fetch api

fetch('https://bestforstudy.com/login', {
    method: 'POST',
    body: formData
  })
  .then(response => response.json())
  .then(result => {
    console.log('Login Success:', result);
  })
  .catch(error => {
    console.error('Login Error:', error);
  });

JSON Formatted

fetch('https://bestforstudy.com/getSample')
  .then(response => response.json())
  .then(jsonResponse => {
      console.log(jsonResponse);
  });
  
  // Output: 
  /**
   *  {
          "data": "sample data here",
          "author": "bestforstudy.com"
      }
   */

promise url parameter fetch api

fetch('https://bestforstudy.com/login')
  .then(
      response  => {
          console.log(response);
      },
      rejection => {
          console.error(rejection.message);
      }
  );

Fetch API Function

fetch('https://bestforstudy.com/login')
  .then((resp) => resp.json())
  .then(function(data) {
    let authors = data.results;
    return authors.map(function(author) {
      let li = createNode('li');
      let img = createNode('img');
      let span = createNode('span');
      img.src = author.picture.medium;
      span.innerHTML = `${author.name.first} ${author.name.last}`;
      append(li, img);
      append(li, span);
      append(ul, li);
    })
  })
  .catch(function(error) {
    console.log(error);
  });

async await syntax

async function myFetch() {
    let response = await fetch('coffee.jpg');
  
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
  
    let myBlob = await response.blob();
  
    let objectURL = URL.createObjectURL(myBlob);
    let image = document.createElement('img');
    image.src = objectURL;
    document.body.appendChild(image);
  }
  
  myFetch()
  .catch(e => {
    console.log('There has been a problem with your fetch operation: ' + e.message);
  });


Best Suggest