(click to expand/hide)
- create a folder, and switch to the folder directory
mkdir <folder name>
cd <folder name>
- create required files (in the folder)
touch app.js
mkdir views
cd views
touch home.ejs header.ejs footer.ejs
- initialize npm and install required npm libraries (in the folder)
npm init
npm i express body-parser ejs lodash mongoose dotenv
res.render("filename");
res.render("filename", {<var1 in ejs>: <var1 in js>, <var2 in ejs>: <var2 in js>});
- calling variable in ejs
<%= variablename %>
<% for(let i=0; i<newListItems.length ; i++){ %>
<div class="item">
<input type="checkbox">
<p>
<%= newListItems[i] %>
</p>
</div>
<% } %>
- in this case the header.ejs will render before the div element and footer.ejs will render after the div element
<%- include("header") -%>
<div class="box" id="heading">
<h1>It's <%= listTitle %>!</h1>
</div>
<%- include("footer") -%>
- import Strings/Objects/Functions
let example = require('path/filename.js');
- export functions
module.exports.<function name> = function() { ... code ... return variable/object; };
- export functions in bulk
function example1(){ } function example2(){ } module.exports = { example1, example2 }
app.get("/posts/:postName", function(req, res){
console.log(req.params.postName);
});
- some()
- return type : boolean value
if(array.some(item => item.title === req.params.ItemName)){ console.log("Match Found"); }
- find()
- return type : object
let foundItem = array.find(item => item.title === req.params.ItemName); if(foundItem){ console.log(foundItem.title); }
- install dotenv package if have bot install already, and create a .env file
npm i dotenv
touch .env
- Store private information in .env
API_KEY = 00000000000
- Calling private information in javascript file
require("dotenv").config();
let example = process.env.API_KEY;
const https = require("https"); //make sure to include library, it is a built-in nodejs library so we don't have to npm install it.
const exampleAPI_URL = "https://api.exampleapi.com/key?=value";
https.get(exampleAPI_URL, function(res){
console.log(res.statusCode); //get the status code
res.on("data", function(data){
const weatherData = JSON.parse(data); // JSON.parse will convert the response data from hex format to json format
console.log(weatherData);
//JSON.stringify(weatherData); //this will turn weatherData from object to string
});
});
async function getInfoDB() {
let result;
try {
await mongoose.connect("mongodb+srv://" + process.env.MONGO_USERNAME + ":" + process.env.MONGO_PS + "@cluster0.6gezmfg.mongodb.net/<db name>", { useNewURLParser: true });
result = await <collection name>.find({});
mongoose.connection.close();
} catch (err) {
console.error(err);
mongoose.connection.close();
}
return result;
}
- Include jquery cdn libraris
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
- Include jquery custom js script file
<script src="./<path>/<script file name>.js"></script>
function functionName() {
// Fetch and process data
$.ajax({
url: "/<pathname>",
method: "GET",
async:false, //disallow concurrent running
success: function (data) {
function2Name(data);
},
error: function () {
console.log("An error occurred accessing stock info data");
function3Name();
},
complete: function () {
function4Name();
}
});
// Fetch and process data
$.ajax({
url: "/<pathname2>",
method: "GET",
async:false, //disallow concurrent running
success: function (data) {
function5Name(data);
},
error: function () {
console.log("An error occurred accessing stock info data");
function6Name();
},
complete: function () {
function7Name();
}
});
}
$(document).ready(function () {
setTimeout(functionName, 1000); // 1000 means delay for 1 second then call function "function"
});
- In bash
npx create-react-app <app name>
- In bash located into the react app directory
cd <app name>
npm start
- In bash located into the react app directory
cd <app name>
npm install react-scripts@latest
<script src="./src/index.js" type="text/jsx"></script>
import React from 'react';
import ReactDOM from 'react-dom/client';
import React from 'react';
import ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<h1>
Hello World
</h1>
);
import React from "react";
function Footer() {
const currentYear = new Date().getFullYear();
return (
<footer>
<p>Copyright â“’ {currentYear}</p>
</footer>
);
}
export default Footer;
import React from "react";
import ReactDOM from "react-dom";
function Card(props) {
return (
<div>
<h2>{props.name}</h2>
<img src={props.img} alt="avatar_img" />
<p>{props.tel}</p>
<p>{props.email}</p>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<div>
<h1>My Contacts</h1>
<Card
name="Beyonce"
img="https://blackhistorywall.files.wordpress.com/2010/02/picture-device-independent-bitmap-119.jpg"
tel="+123 456 789"
email="[email protected]"
/>
<Card
name="Jack Bauer"
img="https://pbs.twimg.com/profile_images/625247595825246208/X3XLea04_400x400.jpg"
tel="+7387384587"
email="[email protected]"
/>
</div>,
document.getElementById("root")
);
- const [state, setState] = useState(initialState);
import React, { useState } from "react"; function App() { const [count, setCount] = useState(0); function increase() { setCount(count + 1); } function decrease() { setCount(count - 1); } return ( <div className="container"> <h1>{count}</h1> <button onClick={decrease}>-</button> <button onClick={increase}>+</button> </div> ); } export default App;
const [inputText, setInputText] = useState("");
const [items, setItems] = useState([]);
function handleChange(event) {
const newValue = event.target.value;
setInputText(newValue);
}
function addItem() {
setItems(prevItems => {
return [...prevItems, inputText];
});
setInputText("");
}
- First install react-router-dom
npm install react-router-dom
- In index.js import BrowserRouter
import React from 'react'; import ReactDOM from 'react-dom/client'; import { BrowserRouter } from 'react-router-dom' import App from './App'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <BrowserRouter> <App /> </BrowserRouter> );
- Finally add to the desired react component
import React from 'react'; import { Link } from 'react-router-dom'; import './GameCard.css'; const GameCard = (props) => { return ( <Link to='/about' className="game-card"> <img className="game-card__image" src={props.imageUrl} alt={props.imgTitle} /> <div className="game-card__details"> <h2 className="game-card__title">{props.title}</h2> <p className="game-card__description">{props.description}</p> </div> </Link> ); }; export default GameCard;
//Map -Create a new array by doing something with each item in an array.
// const newNumbers = numbers.map(function (x) {
// return x * 2;
// });
// is same as
const newNumbers = numbers.map( x => x * 2);
//Find - find the first item that matches from an array.
// const newNumber = numbers.find(function (num) {
// return num > 10;
// })
const newNumber = numbers.find(num => num > 10);
const citrus = ["Lime", "Lemon", "Orange"];
const fruits = ["Apple", ...citrus, "Banana", "Coconut"];
const fullName = {
fName: "James",
lName: "Bond"
};
const user = {
...fullName,
id: 1,
username: "jamesbond007"
};
console.log(user);
// console : Object {fName: "James", lName: "Bond", id: 1, username: "jamesbond007"}
- Condition ? Do if True : Do if False
- Example : isEmpty === true ? addFunction() : removeFunction()
- If we want one of the condition to do nothing, simply set it to null or use && operator
- isEmpty === true ? addFunction() : null
- isEmpty === true && addFunction()
- If we want one of the condition to do nothing, simply set it to null or use && operator
- example 1 (In JavaScript)
function getFee(isMember) { return (isMember ? '$2.00' : '$10.00'); } console.log(getFee(true)); // Expected output: "$2.00" console.log(getFee(false)); // Expected output: "$10.00" console.log(getFee(null)); // Expected output: "$10.00"
- example 2 (In React JavaScript)
import React from "react"; import Login from "./Login"; var isLoggedIn = false; const currentTime = new Date(2019, 11, 1, 9).getHours(); console.log(currentTime); function App() { return ( <div className="container"> {/*Ternary Operator*/} {isLoggedIn ? <h1>Hello</h1> : <Login />} {/*AND Operator*/} {currentTime > 12 && <h1>Why are you still working?</h1>} </div> ); } export default App;
- example 1
const array1 = [1, 4, 9, 16]; // Pass a function to map const map1 = array1.map(x => x * 2); console.log(map1); // Expected output: Array [2, 8, 18, 32]
- example 2
// in emojipedia.js const emojipedia = [ { id: 1, emoji: "💪", name: "Tense Biceps", meaning: "“You can do that!” or “I feel strong!” Arm with tense biceps. Also used in connection with doing sports, e.g. at the gym." }, { id: 2, emoji: "🙏", name: "Person With Folded Hands", meaning: "Two hands pressed together. Is currently very introverted, saying a prayer, or hoping for enlightenment. Is also used as a “high five” or to say thank you." }, { id: 3, emoji: "🤣", name: "Rolling On The Floor, Laughing", meaning: "This is funny! A smiley face, rolling on the floor, laughing. The face is laughing boundlessly. The emoji version of “rofl“. Stands for „rolling on the floor, laughing“." }, { id: 4, emoji: "🤓", name: "Nerd Face", meaning: "Huge glasses, awkward smile and buck teeth. Used humorously or ironically for nerds or to express how smart you are. Stereotype of a nerd; a smart but funny-dressed person with social deficits." } ]; export default emojipedia;
// in App.js import React from "react"; import Entry from "./Entry"; import emojipedia from "../emojipedia"; function createEntry(emojiTerm) { return ( <Entry key={emojiTerm.id} emoji={emojiTerm.emoji} name={emojiTerm.name} description={emojiTerm.meaning} /> ); } function App() { return ( <div> <h1> <span>emojipedia</span> </h1> <dl className="dictionary">{emojipedia.map(createEntry)}</dl> </div> ); } export default App;
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue
);
console.log(sumWithInitial);
// Expected output: 10
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// Expected output: 12
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// Expected output: 3
const dude = { name: 'jeff', weapons: { main: 'sword', alt: 'bat' } };
const bruh = { ...dude }; // shallow copy, nested objects still maintain reference to their original object
const bruh2 = JSON.parse(JSON.stringify(dude)); // deep copy method 1, turn object to string then turn it back to json
const bruh3 = structuredClone(dude); // deep copy method 2