Categories
JavaScript Basics

JavaScript Cheat Sheet — JSON, Loops, and Promises

Spread the love

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript

JSON

We can create JSON strings from JavaScript objects with the JSON.stringify method:

const obj = {
  "name": "Jane",
  "age": 18,
  "city": "Chicago"
};
const json = JSON.stringify(obj);

And we can convert JSON strings back to JavaScript objects with JSON.parse :

const obj = JSON.parse(json);

We can use it to store data in local storage.

We’ve to convert objects into strings first to store them.

To store objects we call localStorage.setItem :

const obj = {
  "name": "Jane",
  "age": 18,
  "city": "Chicago"
};
const json = JSON.stringify(obj);
`localStorage.setItem('json', json);`

The first argument is the key.

And we can get data by their keys with getItem :

localStorage.getItem('json')

Loops

JavaScript comes with various kinds of loops.

One kind of loop is the for loop:

for (let i = 0; i < 10; i++) {
  console.log(i);
}

We can loop through any kind of iterable object with the for-of loop:

for (let i of custOrder) {
  console.log(i);
}

Some iterable objects include arrays, strings, and node lists.

Another kind of loop is the while loop:

let i = 1;
while (i < 100) {
  i *= 2;
  console.log(i);
}

There’s also the do-while loop:

let i = 1;
do {
  i *= 2;
  console.log(i);
} while (i < 100)

The break keyword lets us end the loop early:

for (let i = 0; i < 10; i++) {
  if (i == 5) {
    break;
  }
  console.log(i);
}

The continue keyword lets us skip to the next iteration:

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

Data Types

JavaScript comes with various data types.

They include:

let age = 18;                           // number
let name = "Jane";                      // string
let name = { first: "Jane", last: "Doe" };  // object
let truth = false;                      // boolean
let sheets = ["HTML", "CSS", "JS"];       // array
let a; typeof a;                        // undefined
let a = null;                           // value null

Objects

We can create an object with curly braces:

let student = {
  firstName: "Bob",
  lastName: "Doe",
  age: 18,
  height: 170,
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
};

It has properties and methods.

this is the student object itself.

We can call fullName with student.fullName() .

And we can assign values to properties with:

student.age = 19;

Promises

We can create promises with the Promise constructor:

function add(a, b) {
  return Promise((resolve, reject) => {
    setTimeout(() => {
      if (typeof a !== "number" || typeof b !== "number") {
        return reject(new TypeError("Inputs must be numbers"));
      }
      resolve(a + b);
    }, 1000);
  });
}

We can resolve to fulfill the promise with the sum.

And we call reject to reject the promise with an error.

Then we can call then to get the resolved value and catch to get the error values:

const p = sum(10, 5);
p.then((result) => {
  console.log(result)
}).catch((err) => {
  console.error(err);
});

Conclusion

We can work with JSON, local storage, promises, and loops with JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *