JavaScript Cheat Sheet

JavaScript is the backbone of modern web development, enabling dynamic and interactive experiences on the web. As a versatile, high-level programming language, it plays a crucial role in client-side scripting, server-side programming with Node.js, and even mobile app development with frameworks like React Native. For both novice and experienced developers, having a handy JavaScript cheat sheet can be an invaluable resource. This article provides a comprehensive overview of what you’ll find in a JavaScript cheat sheet, its significance, and how to use it effectively.

What is JavaScript Cheat Sheet?

Our comprehensive JavaScript Cheat Sheet is designed to assist both beginners and experienced coders in mastering this versatile programming language. Whether you’re building interactive web pages, creating dynamic content, or enhancing user experiences, this quick reference guide provides essential concepts, syntax, and ready-to-use code snippets.

Why Use a JavaScript Cheat Sheet?

  1. Efficiency: A cheat sheet enables you to quickly recall and implement various JavaScript functions and syntax, speeding up your coding process.
  2. Learning Aid: For beginners, it serves as an educational tool to understand and memorize core concepts without being overwhelmed by more extensive documentation.
  3. Troubleshooting: It helps in debugging by providing quick access to common methods and best practices.
  4. Best Practices: A good cheat sheet not only covers syntax but also emphasizes best practices and common pitfalls, improving code quality.

Key Sections in a JavaScript Cheat Sheet

A comprehensive JavaScript cheatsheet typically covers several key areas, each essential for effective JavaScript development:

Javascript

Introduction

JavaScript is a lightweight, interpreted programming language.

Console

// => Hello world!
console.log('Hello world!');
// => Hello HindiTutorials
console.warn('hello %s', 'HindiTutorials');
// Prints error message to stderr
console.error(new Error('Oops!'));

Variables

let x = null;
let name = "Karan";
const found = false;

// => Karan, false, null
console.log(name, found, x);

var a;
console.log(a); // => undefined

Strings

let single = 'Wheres my car?';
let double = "Wheres my car?";
// => 21
console.log(single.length);

Arithmatic Operators

5 + 5 = 10 // Addition
10 - 5 = 5 // Subtraction
5 * 10 = 50 // Multiplication
10 / 5 = 2 // Division
10 % 5 = 0 // Modulo

Comments

// This line will denote a comment
/*
The below configuration must be
changed before deployment.
*/

Assignment Operators

let number = 100;

// Both statements will add 10
number = number + 10;
number += 10;

console.log(number);
// => 120

String Interpolation

let age = 7;

// String concatenation
'Tommy is ' + age + ' years old.';

// String interpolation
`Tommy is ${age} years old.`;

let Keyword

let count;
console.log(count); // => undefined
count = 10;
console.log(count); // => 10

const Keyword

const numberOfColumns = 4;

// TypeError: Assignment to constant...
numberOfColumns = 8;

if Statement

const isMailSent = true;

if (isMailSent) {
console.log('Mail sent to recipient');
}

Ternary Operator

var x=1;

// => true
result = (x == 1) ? true : false;

Operators

true || false; // true
10 > 5 || 10 > 20; // true
false || false; // false
10 > 100 || 10 > 20; // false

Logical Operator &&
true && true; // true
1 > 2 && 2 > 1; // false
true && false; // false
4 === 4 && 3 > 1; // true

Comparison Operators
1 > 3 // false
3 > 1 // true
250 >= 250 // true
1 === 1 // true
1 === 2 // false
1 === '1' // false

Logical Operator !
let lateToWork = true;

let oppositeValue = !lateToWork;

// => false
console. log(oppositeValue);

Nullish coalescing operator ??
null ?? 'I win'; // 'I win'
undefined ?? 'Me too'; // 'Me too'
false ?? 'I lose' // false
0 ?? 'I lose again' // 0
'' ?? 'Damn it' // ''

else if

const size = 10;

if (size > 100) {
console.log('Big');
} else if (size > 20) {
console.log('Medium');
} else if (size > 4) {
console.log('Small');
} else {
console.log('Tiny');
}
// Print: Small

switch Statement

const food = 'salad';

switch (food) {
case 'oyster':
console.log('The taste of the sea');
break;
case 'pizza':
console.log('A delicious pie');
break;
default:
console.log('Enjoy your meal');
}

== vs ===

0 == false // true
0 === false // false, different type
1 == "1" // true, automatic type conversion
1 === "1" // false, different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
The == just check the value, === check both the value and the type.

Functions

// Defining the function:
function sum(num1, num2) {
return num1 + num2;
}

// Calling the function:
sum(3, 6); // 9

Anonymous Function

// Named function
function rocketToMars() {
return 'BOOM!';
}

// Anonymous function
const rocketToMars = function() {
return 'BOOM!';
}

Arrow Functions (ES6)

With two arguments
const sum = ( param1, param2) => {
return param1 + param2;
};
console. log( sum( 2, 5)); // => 7

With no arguments
const printHello = ( ) => {
console. log( 'hello'); };
printHello(); // => hello

With a single argument
const checkWeight = weight => {
console. log( `Weight : ${weight}` ); };
checkWeight( 25); // => Weight : 25

Concise arrow functions
const multiply = ( a, b) => a * b;
// => 60
console. log( multiply( 2, 30));

Arrow function available starting ES2015

Function Expressions

const dog = function() {
return 'Woof!';
}

Function Parameters

// The parameter is name
function sayHello(name) {
return `Hello, ${name}!`;
}

Function Declaration

function add(num1, num2) {
return num1 + num2;
}

Scope

function myFunction() {
var pizzaName = "Margarita";
// Code here can use pizzaName
}
// Code here can't use pizzaName

Block Scoped Variables

const isLoggedIn = true;
if (isLoggedIn == true) {
const statusMessage = 'Logged in.';
}
// Uncaught ReferenceError...
console.log(statusMessage);

Global Variables

// Variable declared globally
const color = 'blue';
function printColor() {
console.log(color);
}
printColor(); // => blue

let vs var

for (let i = 0; i < 3; i++) {
// This is the Max Scope for 'let'
// i accessible ✔️
}
// i not accessible ❌



for (var i = 0; i < 3; i++) {
// i accessible ✔️
}
// i accessible ✔️

var is scoped to the nearest function block, and let is scoped to the nearest enclosing block.

Loops with closures

// Prints 3 thrice, not what we meant.
for (var i = 0; i < 3; i++) {
setTimeout(_ => console.log(i), 10);
}



// Prints 0, 1 and 2, as expected.
for (let j = 0; j < 3; j++) {
setTimeout(_ => console.log(j), 10);
}

The variable has its own copy using let, and the variable has shared copy using var.

Arrays

const fruits = ["apple", "orange", "banana"];
// Different data types
const data = [1, 'chicken', false];

Property .length

const numbers = [1, 2, 3, 4];
numbers.length // 4

Index

// Accessing an array element
const myArray = [100, 200, 300];
console.log(myArray[0]); // 100
console.log(myArray[1]); // 200

Mutable chart

add remove start end
push ✔ ✔
pop ✔ ✔
unshift ✔ ✔
shift ✔ ✔

Method .push()

// Adding a single element:
const cart = ['apple', 'orange']; cart.push('pear');
// Adding multiple elements:
const numbers = [1, 2];
numbers.push(3, 4, 5);

Add items to the end and returns the new array length.

Method .pop()

const fruits = ["apple", "orange", "banana"];
const fruit = fruits.pop(); // 'banana'
console.log(fruits); // ["apple", "orange"]

Remove an item from the end and returns the removed item.

Method .shift()

let cats = ['Bob', 'Willy', 'Mini'];

cats.shift(); // ['Willy', 'Mini']

Remove an item from the beginning and returns the removed item.

Method .unshift()

let cats = ['Bob'];

// => ['Willy', 'Bob']
cats.unshift('Willy');

// => ['Puff', 'George', 'Willy', 'Bob']
cats.unshift('Puff', 'George');

Add items to the beginning and returns the new array length.

Method .concat()

const numbers = [3, 2, 1]
const newFirstNumber = 4

// => [ 4, 3, 2, 1 ]
[newFirstNumber].concat(numbers)

// => [ 3, 2, 1, 4 ]
numbers.concat(newFirstNumber)

if you want to avoid mutating your original array, you can use concat.

While Loop

while (condition) {
// code block to be executed
}

let i = 0;
while (i < 5) {
console.log(i);
i++;
}

Reverse Loop

const fruits = ["apple", "orange", "banana"];

for (let i = fruits.length - 1; i >= 0; i--) {
console.log(`${i}. ${fruits[i]}`);
}

// => 2. banana
// => 1. orange
// => 0. apple

Do…While Statement

x = 0
i = 0

do {
x = x + i;
console.log(x)
i++;
} while (i < 5);
// => 0 1 3 6 10

For Loop

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

// => 0, 1, 2, 3

Looping Through Arrays

for (let i = 0; i < array.length; i++){
console.log(array[i]);
}

// => Every item in the array

Break

for (let i = 0; i < 99; i += 1) {
if (i > 5) {
break;
}
console.log(i)
}
// => 0 1 2 3 4 5

Continue

for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "
"
;
}

Nested

for (let i = 0; i < 2; i += 1) {
for (let j = 0; j < 3; j += 1) {
console.log(`${i}-${j}`);
}
}

for...in loop

const fruits = ["apple", "orange", "banana"];
for (let index in fruits) {
console.log(index);
}
// => 0
// => 1
// => 2

for...of loop

const fruits = ["apple", "orange", "banana"];
for (let fruit of fruits) {
console.log(fruit);
}
// => apple
// => orange
// => banana

Best Practices

  • Use let and const Instead of var: This helps avoid issues with variable scoping and hoisting.
  • Write Clear and Descriptive Variable Names: This makes your code more readable and maintainable.
  • Avoid Global Variables: Encapsulate variables within functions or modules to prevent conflicts and unintended side effects.
  • Use Consistent Formatting: Adopt a style guide (like Airbnb’s or Google’s) and stick to it for consistency.
  • Comment Your Code: Well-placed comments help others (and future you) understand your logic.
Java Cheat SheetjQuery Cheat SheetES6 Cheat Sheet
PHP Cheat SheetHTML Cheat SheetCSS Cheat Sheet
error: Content is protected!! You are not allowed to copy.