JavaScript Cheat Sheet A Basic Guide to JavaScript (original) (raw)

JavaScript is a lightweight, open, and cross-platform programming language. It is omnipresent in modern development and is used by programmers across the world to create dynamic and interactive web content like applications and browsers

This article provides an in-depth JavaScript Cheat Sheet, a must-have for every web developer.

JavaScript Chear Sheet

JavaScript Chear Sheet

**What is JavaScript Cheat Sheet?

A **JavaScript Cheat Sheet is a concise reference guide that provides a quick overview of essential JavaScript concepts, syntax, and commands.

It is designed to help developers, especially beginners, recall important topics or features of the language without delving into detailed documentation.

**Fundamentals

**Variables

Variables in JavaScript are containers for storing data. JavaScript allows the usage of variables in the following three ways

**Variable **Description **Example
**var Used to initialize to value, redeclared and its value can be reassigned. var x= value;
**let Similar to var but is block scoped let y= value;
**const Used to declare a fixed value that cannot be changed. const z= value;

JavaScript `

console.log("Using var Keyword"); var x = 1; if (x === 1) { var x = 2; console.log(x); } console.log(x);

// Using let keyword

console.log("Using let Keyword"); let x1 = 1; if (x1 === 1) { let x1 = 2; console.log(x1); } console.log(x1);

// Using const keyword

console.log("Using const Keyword"); const number = 48;

// Changing const value will display TypeError try { const number = 42; } catch (err) { console.log(err); } console.log(number);

`

Output

Using var Keyword 2 2 Using let Keyword 2 1 Using const Keyword 48

**Datatypes

**Datatype **Description **Example
**Number Numeric values can be real number or integers. var x= number;
**String Series of multiple characters written in quotes. var x= “characters”;
**Boolean Has only two values true or false. var x= true/false;
**Null Special value that represents that the variable is empty. var x= null;
**Undefined Represents a variable which is declared but not assigned any value. let x; / let x= undefined;
**Object Complex data type that allows us to store a collection of data. var x= { key: “value”; key: “value”;}
**Array Stores multiple values of same type in a single variable. var x =[‘y1’, ‘y2′,’y3′,’y4’]; y: any datatype
**Function Functions are objects that can be called to execute a block of code. function x(arguments){ block of code }

JavaScript `

// string let s = "hello geeks"; console.log(s);

// Number const n = 10; console.log(n);

// Boolean const x = "true"; console.log(x);

// Undefined

let name; console.log(name);

// Null

const num = null; console.log(num);

// Symbol const val1 = Symbol("hello"); const val2 = Symbol("hello"); console.log(val1); console.log(val2);

// Here both values are different // as they are symbol type which // is immutable object

const obj = { firstName: "geek", lastName: null, batch: 2, }; console.log(obj);

`

Output

hello geeks 10 true undefined null Symbol(hello) Symbol(hello) { firstName: 'geek', lastName: null, batch: 2 }

**Operators

**Operators **Description **Symbols
**Arithmetic Used to perform basic arithmetic operations on variables(operands). +,-,*,/,%,++,–
**Comparison Comparison operator is used to compare two operands. ==, ===,!=,>,<,>=,<=
**Bitwise Used to perform bitwise operations. &, | , ^,~,<<, >>, >>>
**Logical There are three logical operators in javascript. logical AND: When all the operands are true.logical OR: When one or more than one operands are true.logical NOT: Converts true to false. exp1&&exp2,exp1 |
**Assignment Assignment operators assign values to JavaScript variables. =, +=,-=,*=,/=,%=

JavaScript `

let x = 5; let y = 3;

// Addition console.log("x + y = ", x); // 8

// Subtraction console.log("x - y = ", x - y); // 2

// Multiplication console.log("x * y = ", x * y); // 15

// Division console.log("x / y = ", x / y);

// Remainder console.log("x % y = ", (x % y)); // 2

// Increment console.log("++x = ", ++x); // x is now 6 console.log("x++ = ", x++); console.log("x = ", x); // 7

// Decrement console.log("--x = ", --x); // x is now 6 console.log("x-- = ", x--); console.log("x = ", x); // 5

// Exponentiation console.log("x ** y =", x ** y);

// Comparison console.log(x > y); // true

// Equal operator console.log((2 == 2)); // true

// Not equal operator console.log((3 != 2)); // true

// Strict equal operator console.log((2 === 2)); // true

// Strict not equal operator console.log((2 !== 2)); // false

// Logical Operator

// Logical AND console.log((x < 6 && y < 5)); // true

// Logical OR console.log((x < 6 || y > 6)); // true

// Logical NOT console.log(!(x < 6)); // false

`

Output

x + y = 5 x - y = 2 x * y = 15 x / y = 1.6666666666666667 x % y = 2 ++x = 6 x++ = 6 x = 7 --x = 6 x-- = 6 x = 5 x ** y = 125 true true true true false true true false

**JS scope and scope chain

**Scope determines where a variable is accessible in your program. It defines the context in which variables can be referenced or modified. JavaScript has three main types of scope:

**Scope Chain:

let a = 10;

function example() { let b = 20; // Exists in function scope

if (true) {
    var c = 30; // Exists in function scope (due to 'var')
    const d = 40; // Exists in block scope
}

console.log(a); // Accessible from global scope
console.log(b); // Accessible from function scope
console.log(c); // Accessible from function scope (due to 'var')
console.log(d); // Error: 'd' is not accessible outside block scope

}

example();

`

**Functions

**Function **Description
**parseInt() Parses an argument passed to it and returns an integral number.
**parseFloat() Parses the argument and returns a floating-point number.
**isNaN() Determines if a given value is Not a Number.
**Number() Returns an argument after converting it to number.
**eval() Used for evaluating JavaScript programs presented as strings.
**prompt() Creates a dialogue box for taking input from the user.
**encodeURI() Encodes a URI into a UTF-8 encoding scheme.
**match() Used to search a string for a match against regular expression.

JavaScript `

// JS parseInt function: const num1 = parseInt("100.45"); console.log('Using parseInt("100.45") = ' + num1);

// JS parseFloat function: const num2 = parseFloat("123.45abc"); console.log('parseFloat("123.45abc") = ' + num2);

// JS isNaN function: console.log(isNaN("hello"));

// JS Number() function: const num3 = Number("123"); console.log("Value of '123': " + num3);

// JS eval() function: function evalExample() { const expression = "2 + 3 * 4"; // Example expression to evaluate const result = eval(expression); // Evaluates '2 + 3 * 4' and returns 14 console.log(result); } evalExample();

// JS encodeURI function: const url = "https://example.com/hello world?query=javascript"; const encodedURL = encodeURI(url); // Encodes spaces as '%20' and ensures valid URL. console.log(encodedURL);

`

Output

Using parseInt("100.45") = 100 parseFloat("123.45abc") = 123.45 true Value of '123': 123 14 https://example.com/hello%20world?query=javascript

**Arrays

**Example:

var House = [ ]; // Method 1
var House = new Array(); // Method 2

There are various operations that can be performed on arrays using JavaScript methods. Some of these methods are:

**Method **Description
**push() Adds a new element at the very end of an array.
**pop() Removes the last element of an array.
**concat() Joins various arrays into a single array.
**shift() Removes the first element of an array
**unShift() Adds new elements at the beginning of the array
**reverse() Reverses the order of the elements in an array.
**slice() Pulls a copy of a part of an array into a new array.
**splice() Adds elements in a particular way and position.
**toString() Converts the array elements into strings.
**valueOf() Returns the primitive value of the given object.
**indexOf() Returns the first index at which a given element is found.
**lastIndexOf() Returns the final index at which a given element appears.
**join() Combines elements of an array into one single string and then returns it
**sort() Sorts the array elements based on some condition.

JavaScript `

// Declaring and initializing arrays

// Num Array let arr = [10, 20, 30, 40, 50]; let arr1 = [110, 120, 130, 140];

// String array let string_arr = ["Alex", "peter", "chloe"];

// push: Adding elements at the end of the array arr.push(60); console.log("After push op " + arr);

// unshift() Adding elements at the start of the array arr.unshift(0, 10); console.log("After unshift op " + arr );

// pop: removing elements from the end of the array arr.pop(); console.log("After pop op" + arr);

// shift(): Removing elements from the start of the array arr.shift(); console.log("After shift op " + arr);

// splice(x,y): removes x number of elements // starting from index y arr.splice(2, 1); console.log("After splice op" + arr);

// reverse(): reverses the order of elements in array arr.reverse(); console.log("After reverse op" + arr);

// concat(): merges two or more array console.log("After concat op" + arr.concat(arr1));

`

**Loops

**Loop **Description **Syntax
**for Loops over a block of with conditions specified in the beginning. for (initialization condition; testing condition;increment/decrement){ statement(s)}
**while Entry control loop which executes after checking the condition. while (boolean condition){ loop statements…}
**do-while Exit Control Loop which executes once before checking the condition. do{ statements..} while (condition);
**for-in Another version of for loop to provide a simpler way to iterate. for (variableName in Object){ statement(s)}

JavaScript `

// Illustration of for loop let x;

for (x = 2; x <= 4; x++) { console.log("Value of x:" + x); }

// creating an Object let languages = { first: "C", second: "Java", third: "Python", fourth: "PHP", fifth: "JavaScript", };

// Iterate through every property of the object for (itr in languages) { console.log(languages[itr]); }

// Illustration of while loop let y = 1;

// Exit when x becomes greater than 4 while (y <= 4) { console.log("Value of y:" + y); y++; }

// Illustration of do-while loop let z = 21;

do {

console.log("Value of z:" + z);

z++;

} while (z < 20);

`

Output

Value of x:2 Value of x:3 Value of x:4 C Java Python PHP JavaScript Value of y:1 Value of y:2 Value of y:3 Value of y:4 Value of z:21

**If-else

// JavaScript program to illustrate if-else statement const i = 10;

if (i < 15) console.log("Value of i is less than 10"); else console.log("Value of i is greater than 10");

`

Output

Value of i is less than 10

**Strings

**Methods **Description
**concat() Used for concatenating multiple strings into a single string.
**match() Used for finding matche of a string against a provided pattern.
**replace() Used for finding and replacing a given text in string.
**substr() Used to extract length characters from a given string.
**slice() Used for extracting an area of the string and returs it
**lastIndexOf() Used to return the index (position) of the last occurrence of a specified value.
**charAt() Used for returning the character at a particular index of a string
**valueOf() Used for returning the primitive value of a string object.
**split() Used for splitting a string object into an array of strings.
**toUpperCase() Used for converting strings to upper case.
**toLoweCase() Used for converting strings to lower case.

JavaScript `

let gfg = 'GFG '; let geeks = 'stands-for-GeeksforGeeks';

// Print the string as it is console.log(gfg); console.log(geeks);

// concat() method console.log(gfg.concat(geeks));

// match() method console.log(geeks.match(/eek/));

// charAt() method console.log(geeks.charAt(5));

// valueOf() method console.log(geeks.valueOf());

// lastIndexOf() method console.log(geeks.lastIndexOf('for'));

// substr() method console.log(geeks.substr(6));

// indexOf() method console.log(gfg.indexOf('G'));

// replace() method console.log(gfg.replace('FG', 'fg'));

// slice() method console.log(geeks.slice(2, 8));

// split() method console.log(geeks.split('-'));

// toUpperCase method console.log(geeks.toUpperCase(geeks));

// toLowerCase method console.log(geeks.toLowerCase(geeks));

`

Output

GFG stands-for-GeeksforGeeks GFG stands-for-GeeksforGeeks [ 'eek', index: 12, input: 'stands-for-GeeksforGeeks', groups: undefined ] s stands-for-GeeksforGeeks 16 -for-GeeksforGeeks 0 Gfg an...

**Regular Expressions

**Regular Expression Modifiers:

Modifiers can be used to perform multiline searches. Some of the pattern modifiers that are allowed in JavaScript:

**Modifiers **Description
**[abc] Find any of the character inside the brackets
**[0-9] Find any of the digits between the brackets 0 to 9
****(x/y)** Find any of the alternatives between x or y separated with |

**Regular Expression Patterns:

Metacharacters are characters with a special meaning. Some of the metacharacters that are allowed in JavaScript:

**Metacharacters **Description
****.** Used for finding a single character, except newline or line terminator
**\d Used to find a digit.
**\s Used to find a whitespace character
**\uxxxx Used to find the Unicode character specified by the hexadecimal number

**Quantifiers:

They provide the minimum number of instances of a character, group, or character class in the input required to find a match.

Some of the quantifiers allowed in JavaScript are:

**Quantifiers **Description
**n+ Used to match any string that contains at least one n
**n* Used to match any string that contains zero or more occurrences of n
**n? Used to matches any string that contains zero or one occurrences of n
**n{x} Matches strings that contain a sequence of X n’s
**^n Matches strings with n in the first place

Here is an example to help you understand regular expression better.

JavaScript `

// Program to validate the email address function validateEmail(email) {

// Regex pattern for email
const re = /\S+@\S+\.\S+/g;

// Check if the email is valid
let result = re.test(email);

if (result) {
    console.log("The email is valid.");
} else {
    console.log("The email is not valid.");
}

}

// Input Email Id let email = "abc@gmail.com" validateEmail(email);

email = "abc#$#@45com" validateEmail(email);

`

Output

The email is valid. The email is not valid.

**Data Transformation

**Method **Description **Syntax
**map() Iterates over an array and calls function on every element of array. array.map(function(currentValue, index, arr), thisValue)
**filter() Create a new array from a given array after applying a condition. array.filter(callback(element, index, arr), thisValue)
[****reduce()**](<a href=) Reduces the array to single value using a function array.reduce( function(total, currentValue, currentIndex, arr),initialValue )

JavaScript `

const num = [16, 25];

/* Using JS map() Method */ console.log(num.map(Math.sqrt));

const ages = [19, 37, 16, 42];

/* Using JS filter() Method */ console.log(ages.filter(checkAdult));

function checkAdult(age) { return age >= 18; }

/* Using JS reduce() Method */ const numbers = [165, 84, 35]; console.log(numbers.reduce(myFunc));

function myFunc(total, num) { return total - num; }

`

Output

[ 4, 5 ] [ 19, 37, 42 ] 46

**Date objects

Syntax

new Date()
new Date(milliseconds)
new Date(dataString)
new Date(year, month, date, hour, minute, second, millisecond)

There are various methods in JavaScript used to get date and time values or create custom date objects. Some of these methods are:

**Method **Description
**getDate() Used to return the month’s day as a number (1-31)
**getTime() Used to get the milliseconds since January 1, 1970
**getMinutes() Returns the current minute (0-59)
**getFullYear() Returns the current year as a four-digit value (yyyy)
**getDay() Returns a number representing the weekday (0-6) to
**parse() Returns the number of milliseconds since January 1, 1970
**setDate() Returns the current date as a number (1-31)
**setTime() Sets the time (milliseconds since January 1, 1970)

JavaScript `

// Here a date has been assigned by creating a date obj let DateObj = new Date("October 13, 1996 05:35:32");

// getDate() let A = DateObj.getDate();

// Printing date of the month console.log(A);

// getTime() let B = DateObj.getTime();

// Printing time in milliseconds. console.log(B);

// getMinutes() let minutes = DateObj.getMinutes();

// Printing minute. console.log(minutes);

// getFullYear() let C = DateObj.getFullYear();

// Printing year console.log(C);

// getDay() let Day = DateObj.getDay();

// Printing day of the week console.log("Number of Day: " + Day);

// setDate DateObj.setDate(15);

let D = DateObj.getDate();

// Printing new date of the month console.log(D);

// parse(), taking wrong date string as input. let date = "February 48, 2018 12:30 PM";

// calling parse function. let msec = Date.parse(date); console.log(msec);

`

Output

13 845184932000 35 1996 Number of Day: 0 15 NaN

**DOM

**Method **Description
**appendChild() Adds a new child node as the last child node.
**cloneNode() Duplicates an HTML element.
**hasAttributes() Returns true If an element has any attributes otherwise,returns false.
**removeChild() Removes a child node from an element using the Child() method.
**getAttribute() Returns the value of an element node’s provided attribute.
**getElementsByTagName() Returns a list of all child elements.
**isEqualNode() Determines whether two elements are same.

HTML `

/* CSS is used to make the output looks good */