JavaScript Cheat Sheet
by Web Dev via cheatography.com/186440/cs/38966/
Variables
Variables are containers of data which we can access anywhere in the program
Value Types
Number Numeric Values
String A sequence of characters enclosed within quotes
Boolean True or False
Array A special variable, which can hold more than one value.
Object Key and Value pairs
String Methods
.length returns the number of characters
string.slice(x,y) returns a part of the string.
x - index of the start item
y - count of the last item
Number(String) converts the string containing numeric values into Number datatype
.toUpperCase() converts the string to uppercase
.toLowerCase() converts the string to lowercase
Arrays
Declaring Array let arrayName = []
Accessing Items arrayName[index]
.length returns the length of the array
.push(data) Adds a new item to the end of the array arrayName.push("data")
.pop() Removes the last item arrayname.pop()
.unshift(data) Adds a new item to start of the array arrayName.unshift(data)
.shift() Removes the first item of the array arrayName.shift()
.join(seperator) Converts the array into string with the seperator
.slice(x,y) Gets a part of the array x - index of the start item y - count of the last item
.reverse() reverse the array items arrayName.reverse()
.sort() 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
By Web Dev Published 28th May, 2023. Sponsored by ApolloPad.com
cheatography.com/web-dev/ Last updated 9th December, 2023. Everyone has a novel in them. Finish
Page 1 of 6. Yours!
https://apollopad.com
JavaScript Cheat Sheet
by Web Dev via cheatography.com/186440/cs/38966/
Node Modules
Node modules provide a way to re-use code in your Node application.
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
NPM NPM is a package manager for Node.js packages, or modules.
Initializing NPM npm init -y
Installing a module npm install moduleName
using the modules const module = require("NPMModuleName")
NodeJS Basic App
Importing Express const express = require("express");
Invoking Express const app = express();
express urlencoding app.use(express.urlencoded({extended: false}));
using express's urlencoded req.body
Setting EJS app.set("view engine", "ejs");
Using EJS res.render("fileName", {});
Dotenv Module It is a module used to get access to the environment variables from the .env file
npm install dotenv
configuration of Dotenv require("dotenv").config()
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
By Web Dev Published 28th May, 2023. Sponsored by ApolloPad.com
cheatography.com/web-dev/ Last updated 9th December, 2023. Everyone has a novel in them. Finish
Page 2 of 6. Yours!
https://apollopad.com
JavaScript Cheat Sheet
by Web Dev via cheatography.com/186440/cs/38966/
Javascript Fetch
function callAPI() {
async function getData() {
let response = await fetch(url, options);
let data = response.json();
return data;
}
getData().then(res => {
console.log(res);
})
}
Using APIs
import https from "https"
https.request(url, options, callback() {})
callback(res) {
let resData = ""
res.on("data", (chuncks) =>
resData += chunks
})
res.on("end", () =>
console.log("The data from the API: " + JSON.parse(resData))
})
}
URL Path
"/root/:id" refers to a url with the value in place of id will be stored in a object
req.body.params.id access the parameter of the URL Path
req.body.query.pName used to access the path parameters
Functions
A Function is a small block of code which performs a specific task. We can create a new Function using function keyword.
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).
myfunc(4)
The return statement stops the execution of a function and returns a value.
function myFunc(parameters) { return VALUES }
conditional statements
Conditional statements are used to perform different actions based on different conditions.
There are there types of conditional statements
By Web Dev Published 28th May, 2023. Sponsored by ApolloPad.com
cheatography.com/web-dev/ Last updated 9th December, 2023. Everyone has a novel in them. Finish
Page 3 of 6. Yours!
https://apollopad.com
JavaScript Cheat Sheet
by Web Dev via cheatography.com/186440/cs/38966/
conditional statements (cont)
if (condition1) {
// code to be executed if the condition1 is true
} else if (condition2) {
// code to be executed if the condition1 is true
} else if (condition3) {
// code to be executed if the condition1 is true
} else {
// code to be executed if all the conditions are false
}
Finding HTML Elments
document The whole html document
getElementById(ID) Gets the element with the specified ID
getElementByClassName(class) Gets the elements with the Specified CLASS
getElementByTagName(Tag) Gets the specified Tag elements
querySelector(Query) Returns the first element which satisfy the query
querySelectorAll(Query) Returns all the elements which satisfy the query
NodeJS
NodeJS is a open-source cross-platform runtime runtime environment for backend JavaScript
Install NodeJS
Mongoose
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 = require("mongoose");
Connecting to MongoDB Database:
mongoose.connect(connection string, {useNewUrlParser: true})
A Schema in mongoDB or mongoose is a structure for the data validation. mongoose will return a error if the data is not the same
Schema and Model:
const Schema = mongoose.Schema(Fields and their info)
const model = mongoose.model("collectionName", Schema)
Using the model variable, we can perform all the CRUD Operations
EJS (Embedded JavaScript templating)
EJS is a simple templating language that lets you generate HTML markup with plain JavaScript, where we can substitute values from JavaScript
Setting EJS
app.set("view engine", "ejs");
Using EJS
res.render("fileName", {});
EJS Website
By Web Dev Published 28th May, 2023. Sponsored by ApolloPad.com
cheatography.com/web-dev/ Last updated 9th December, 2023. Everyone has a novel in them. Finish
Page 4 of 6. Yours!
https://apollopad.com
JavaScript Cheat Sheet
by Web Dev via cheatography.com/186440/cs/38966/
bcrypt
Module It is used for salting and hashing the passwords
installing bcrypt npm install bcrypt
requiring bcrypt const bcrypr = require("bcrypt")
hashing password bcrypt.hash("password", hashing rounds).then(hash = { //code })
comparing password with hash bcrypt.compare("password", hash).then(result => {})
Passport.js and Express-Session
Passport is authentication middleware for Node.js. Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-
based web application
Using Passport.js, Express-Session and as well as passport-local as a strategy we can login a user and maintain the login user
Bacis Passport.js, Express-Session 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")
router.use(session({
secret: "some secret",
store: { MongoStore.create({
MongoDB Connection String ,
mongoUrl:
touchAfter: 24 * 3600
},
cookie: {
maxAge: 14
24 60 60 1000
},
resave: false,
saveUninitialized: true
})
router.use(passport.initialize());
router.use(passport.session());
passport.serializeUser(
(user, done) => {
By Web Dev Published 28th May, 2023. Sponsored by ApolloPad.com
cheatography.com/web-dev/ Last updated 9th December, 2023. Everyone has a novel in them. Finish
Page 5 of 6. Yours!
https://apollopad.com
JavaScript Cheat Sheet
by Web Dev via cheatography.com/186440/cs/38966/
Bacis Passport.js, Express-Session Code (cont)
> done(null, user);
}
)
passport.deserializeUser(
(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);
}
}
}
)
router.post("/login", (req, res, next) => {
if (req.isAuthenticated == true) { res.redirect("/") }
else if ( req.isUnauthenticated == true) { return next(); }
)
Note
Add typekey to the package.json to use import method to import modules
Dotenv
Dotenv Module It is a module used to get access to the environment variables from the .env file
Installation:
npm install dotenv
Configuration of Dotenv
require("dotenv").config()
By Web Dev Published 28th May, 2023. Sponsored by ApolloPad.com
cheatography.com/web-dev/ Last updated 9th December, 2023. Everyone has a novel in them. Finish
Page 6 of 6. Yours!
https://apollopad.com