Show Menu

JavaScript Cheat Sheet by

A Bacis Javascript Cheat Sheet


Variables are containers of data which we can access anywhere in the program

Value Types

Numeric Values
A sequence of characters enclosed within quotes
True or False
A special variable, which can hold more than one value.
Key and Value pairs

String Methods

returns the number of characters­ice­(x,y)
returns a part of the string.
x - index of the start item
y - count of the last item
converts the string containing numeric values into Number datatype
converts the string to uppercase
converts the string to lowercase


Declaring Array
let arrayName = []
Accessing Items
returns the length of the array
Adds a new item to the end of the array
Removes the last item
Adds a new item to start of the array
Removes the first item of the array
Converts the array into string with the seperator
Gets a part of the array x - index of the start item y - count of the last item
reverse the array items
sorts the array items consisting only strings
.sort(­(a,b) => a-b)
sorts the array items of numbers in ascending order
.sort(­(a,b) => b-a)
sorts the array items of numbers in decending order

Node Modules

Node modules provide a way to re-use code in your Node applic­ation.
There are internal modules which come along with nodejs and also external modules which we can install using a package manager i.e npm, yarn


NPM is a package manager for Node.js packages, or modules.
Initia­lizing NPM
npm init -y
Installing a module
npm install moduleName
using the modules
const module = requir­e("N­PMM­odu­leN­ame­")

NodeJS Basic App

Importing Express
const express = requir­e("e­xpr­ess­");
Invoking Express
const app = express();
express urlenc­oding­e(e­xpr­ess.ur­len­cod­ed(­{ex­tended: false}));
using express's urlencoded
Setting EJS­t("view engine­", "­ejs­");
Using EJS­nde­r("f­ile­Nam­e", {});
Dotenv Module
It is a module used to get access to the enviro­nment variables from the .env file
npm install dotenv
config­uration of Dotenv

Basic Mongoose Connection

const mongoose = require("mongoose");

mongoose.connect(connection string, {useNewUrlParser: true});
const Schema = new mongoose.Schema({
  field1: { type: String, required: true },
  field2: { type: Number, required: true }

module.exports = mongoose.mondel( collection name, Schema )

Basic NodeJS App

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ exteded : true });
app.use(express.static("public");  // making a folder to have static files like css, js

Javascript Fetch

function callAPI() {
  async function getData() {
    let response = await fetch(url, options);
    let data = response.json();
    return data;
  getData().then(res => {

Using APIs

import https from "­htt­ps"
https.r­eq­uest(url, options, callback() {})
callba­ck(res) {
let resData = ""
res.on­("da­ta", (chuncks) =>
resData += chunks
res.on­("en­d", () =>
consol­e.l­og(­"The data from the API: " + JSON.parse(resData))

URL Path

refers to a url with the value in place of id will be stored in a object­dy.p­ar­
access the parameter of the URL Path­dy.q­ue­ry.p­Name
used to access the path parameters


A Function is a small block of code which performs a specific task. We can create a new Function using
function myFunc() { // code to be executed }
The code inside the function can be executed by calling the function anywhere in the program.
Parameters are the variables defined with the function, but their values are assigned when they are invoked(called).
The return statement stops the execution of a function and returns a value.
function myFunc­(pa­ram­eters) { return VALUES }

condit­ional statements

Condit­ional statements are used to perform different actions based on different condit­ions.
There are there types of condit­ional statements
if (condi­tion1) { 
// code to be executed if the condition1 is true
} else if (condi­tion2) {
// code to be executed if the condition1 is true
} else if (condi­tion3) {
// code to be executed if the condition1 is true
} else {
// code to be executed if all the conditions are false

Finding HTML Elments

The whole html document
Gets the element with the specified ID
Gets the elements with the Specified CLASS
Gets the specified Tag elements
Returns the first element which satisfy the query
Returns all the elements which satisfy the query


NodeJS is a open-s­ource cross-­pla­tform runtime runtime enviro­nment for backend JavaScript


Mongoose is an Object Document Mapper (ODM) that is mostly used when the Node.JS server is integrated with the MongoDB database
Requiring Mongoose:
const mongoose = requir­e("m­ong­oos­e");
Connecting to MongoDB Database:
mongoo­se.c­on­nect(connection string, {useNe­wUr­lPa­rser: true})
A Schema in mongoDB or mongoose is a structure for the data valida­tion. mongoose will return a error if the data is not the same
Schema and Model:
const Schema = mongoo­se.S­chema(Fields and their info) 
const model = mongoo­se.m­od­el(­"­col­lec­tio­nNa­me", Schema)
Using the model variable, we can perform all the CRUD Operations

EJS (Embedded JavaScript templa­ting)

EJS is a simple templating language that lets you generate HTML markup with plain JavaSc­ript, where we can substitute values from JavaScript
Setting EJS­­t(­"view engine­­", "­­ej­s­");
Using EJS­­nd­e­r­("f­­ile­­Na­m­e­", {});


It is used for salting and hashing the passwords
installing bcrypt
npm install bcrypt
requiring bcrypt
const bcrypr = requir­e("b­cry­pt")
hashing password
bcrypt.hash("­pas­swo­rd", hashing rounds).then­(hash = { //code })
comparing password with hash­mpare("­pas­swo­rd", hash).then­(result => {})

Passpo­rt.js and Expres­s-S­ession

Passport is authen­tic­ation middleware for Node.js. Extremely flexible and modular, Passport can be unobtr­usively dropped in to any Expres­s-based web applic­ation
Using Passpo­rt.js, Expres­s-S­ession and as well as passpo­rt-­local as a strategy we can login a user and maintain the login user

Bacis Passpo­rt.js, Expres­s-S­ession Code

const app = require("express");
const router = express.Router();

const localStrategy = require("mongoose-local");
const passport = require("passport");
const session = require("express-session");
const MongoStore = require("connect-mongo")
const users = require("./models/mongo-user.js")
  secret: "some secret",
  store: { MongoStore.create({
   mongoUrl: MongoDB Connection String,
   touchAfter: 24 * 3600
  cookie: {
   maxAge: 14  24  60  60  1000
  resave: false,
  saveUninitialized: true

  (user, done) => {
     done(null, user);

  (user, null) => {
    users.find({_id: user._id}).then(data => {
      done(null, data);

passport.use( new localStrategy(
  (username, password, done) => {
    users.find({username: username}).then( data => {
      if (data.password == password) {
        done(null, data);
     else if (data.password != password) {
        done(null, false);
)"/login", (req, res, next) => { 
  if (req.isAuthenticated == true) { res.redirect("/") } 
  else if ( req.isUnauthenticated == true) { return next(); } 


key to the packag­e.json to use
method to import modules


Dotenv Module It is a module used to get access to the enviro­­nment variables from the .env file
npm install dotenv
Config­­ur­ation of Dotenv


No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          JavaScript Cheat Sheet
            Bootstrap Glyphicons Cheat Sheet by James Croft