JS Cheat Sheet
Variable and Comments
Section titled “Variable and Comments”JavaScript Variables
var // function-scoped, can be redeclared and updatedlet // block-scoped, can be updated but not redeclaredconst // block-scoped, can't be updated or redeclaredComments
// Single line comment
/* Multi-line comment */Data Types
Section titled “Data Types”Primitive Data Types
var num1 = 455 // Numbervar str1 = "A String" // Stringvar bool1 = true // Booleanvar undef = undefined // Undefinedvar nul = null // Nullvar sym = Symbol('id') // Symbol (unique)Reference Datatype
// Arrayvar arr = [1, 2, "doe", 4, 5];console.log(arr); // [1, 2, "doe", 4, 5]console.log(arr[0]); // 1
// Objectvar marks = { ravi: 34, shubham: 78, harry: 99.977};console.log(marks); // {ravi: 34, shubham: 78, harry: 99.977}console.log(marks.shubham) // 78Operators in JS
Section titled “Operators in JS”// Assignment Operators= += -= *= /=
// Arithmetic Operators+ - * / %
// Comparison Operators== != === !== < > <= >=
// Logical Operators&& || !
// Bitwise Operators& | ^ ~ << >> >>>Function
Section titled “Function”Anonymous Function
// Anonymous Function Expressionconst funcVar = function() { };
// Immediately Invoked Function Expression (IIFE)(function() {})();
// Callback ExamplesetTimeout(function() {}, time);
// Event Handler Exampledocument.getElementById("elementId").addEventListener("event", function() {});Named Function (Assigning to variable is optional)
// Named Function Declarationfunction funcName() { }
// Named Function Expressionconst funcVar = function funcName() { };
// Named Function Expression with Immediate Invocation(function funcName() {})();Arrow Function
// Arrow Functionconst funcName = () => { };
// Immediately Invoked Arrow Function (IIFE)(() => {})();Condition in Javascript
if(x<18){ // logic}else if(x>31){ // logic}else{ // logic}For Loop
for(var i=0; arr.length; i++){ // logic}// Iterate from a lower bound value to upper bound valueWhile Loop
//while loopwhile(j<arr.length){ // logic j++;}// Iterate until a given condition is trueFor Each Loop ⭐
arr.forEach(functions(element){ // logic})// Ierate over elements of sequence - array, string etc.do-while ⭐
do{ // Logic ; j++;}while (j < arr.length);// Run a loop at least one time.Break and Continue
for( var i = 0; i<10; i++){
// continue if(i==4){ continue; // skip current iteration } // break if(i==6){ break; // exit the loop } // logic}// continue: skip loop's execution for a condition// break: terminate loop based on conditionMethods in Javascript ⭐
Section titled “Methods in Javascript ⭐”Methods on array
let myArray = ["Fan", "Camera", 34, null, true ]
// Length of ArraymyArr.length
// Remove last elment from arraymyArr.pop() // ["Fan", "Camera", 34, null]
// Push an element to an IndexmyArr.push("harry")
// Remove first element from array ⭐myArr.shift()
// Add element to Starting ⭐myArr.unshift("Harry")
// Print arrayconsole.log(myArr) // ["Harry", "Camera", 34, null, "harry"]
// Print length of new array ⭐console.log(myArr.unshift("Gurav")) // 6
// Convert array to string ⭐myArr.toString() // "Harry,Fan,Camer,34,,true"
// Sort Array (in Dictionary Order) ⭐let d = [1,4,6,43,23,32324]d.sort() // [1, 23, 32324, 4, 43, 6]String Methods in JS
let myLovelyString = "Gaurav is a good boy, Gaurav";
// Length of stringmyLovelyString.length // 20
// Starting index of substringmyLovelyString.indexOf("Gaurav") //0 (first matched index)
// Starting index of substringmyLovelyString.lastIndexOf("Gaurav") //23 (last matched index)
// Slicing in string (startIndex, size)myLovelyString.slice(0,3) // "Gau
// Replace first substring occurence in stringmyLovelyString.replace("Gaurav","Meena") //"Meena is a good boy, Gaurav"Date-Time Method in JS
// Create a new Date object representing the current date and timelet myDate = new Date(); // e.g., Mon July 01 2024 22:47:00 GMT+0530 (IST)
// Get the time in milliseconds since Jan 1, 1970 (Unix Epoch)myDate.getTime()
// Get the 4-digit year (e.g., 2024)myDate.getFullYear()
// Get the day of the week (0 = Sunday, 1 = Monday, ..., 6 = Saturday)myDate.getDay()
// Get the current minute (0 to 59)myDate.getMinutes()
// Get the current hour (0 to 23)myDate.getHours()Document Object Model (DOM) Manipulation
Section titled “Document Object Model (DOM) Manipulation”Types of Messages
alert("Hello") // Shows an alert popupconsole.log("Hello") // Prints in the consoleconsole.error("Hello") // Logs error in the consoleElement Selection
document.querySelector(".button1") // Selects first element with class "button1"document.getElementById("navbar1") // Selects element with id "navbar1"document.getElementsByTagName("h1") // Selects all <h1> elements (HTMLCollection)Click Implementation
document.querySelector(".button1").click() // Clicks on element with class "button1"Select from Array of Elements
document.getElementsByTagName("h1")[0] // Selects first <h1> elementApply CSS Style
document.getElementsByTagName("h1")[0].style.fontSize = "99px" // Changes font size of first <h1>Embedded Script
<script> console.log("Hello World"); </script>External Script
<script src="index.js"></script>