Javascript

JavaScript, often abbreviated JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, often incorporating third-party libraries.

JavaScript Keywords

Keywords are special words that are reserved by JavaScript and cannot be used to name things. They indicate commands to the JavaScript interpreter. The following is a complete list of JavaScript keywords:
let      const      break      continue   debugger
if       else       switch     case       default
while    do         for        in         of
function return     var        try        catch
throw    finally    class      extends    super
import   export     default    true       false
null     undefined  typeof     instanceof

JavaScript Operators

Operators are special tokens that have meaning to the JavaScript Interpreter. Using them implies some form of mathematical operation. The following is the complete list of Operators:
+	-	*	**	/	%	++
--	=	+=	-=	*=	/=
%=	==	===	!=	!==	<	>
<=	>=	? :	&&	||	!
&	|	^	~	<<	>>
>>>
&=	|=	^=	<<=	>>=	>>>=

JPunctuators and Delimiters

Punctuators, which are also known as delimiters, separate different elements in JavaScript statements and expressions. // Here is the complete list:
(	)	[	]	{	}
,	;	:	.	`	=
'	"	/	\	@

JavaScript Arithmetic Operators

// Operator	Meaning	                                Usage
+	        Addition or unary plus	                x + y
-	        Subtraction or unary minus	        x - y
*	        Multiplication	                        x * y
/	        Division (result is always a float)	x / y
%	        Modulus	                                x % y (remainder of x/y)
**	        Exponent	                        x**y (x to the power y)

JavaScript Operators Precedence Table

// Operator	                        Description
**	                                Exponentiation
++, --	                                Increment, Decrement
+, -, ~	                                Unary Plus, Unary Minus, Bitwise NOT
*, /, %	                                Multiplication, Division, Modulo
+, -	                                Addition, Subtraction
<<, >>, >>>	                        Bitwise Shifts
&	                                Bitwise AND
^	                                Bitwise XOR
|	                                Bitwise OR
<, <=, >, >=	                        Relational operators
==, ===, !=, !==	                Equality operators
&&	                                Logical AND
||	                                Logical OR
?:	                                Conditional (Ternary) operator
=, +=, -=, *=, /=, %=, <<=, >>=, >>>=	Assignment operators
,	                                Comma operator

JavaScript Relational Operators

// Operator	Meaning	                        Usage
>	        Greater than	                x > y
<	        Less than	                x < y
==	        Equal to	                x == y
===	        Strict Equal to	            x === y
!=	        Not equal to	                x != y
!==	        Strict Not equal to	        x !== y
>=	        Greater than or equal to	x >= y
<=	        Less than or equal to 	    x <= y

JavaScript Logical Operators

// Operator	Meaning	                                Usage
&&	        Logical AND	                        x && y
||	        Logical OR	                        x || y
!	        Logical NOT	                        !x

JavaScript Boolean Operators

The basic Boolean operators are: !, &&, ||. The following is the truth table for each of these operators respectively. Note that A and B in the tables below are the names of the operands that represent a Boolean Expression
A       !A
true    false
false   true

A       B       A && B
true    true    true
true    false   false
false   true    false
false   false   false

A       B       A || B
true    true    true
true    false   true
false   true    true
false   false   false

JavaScript Membership Operators

Operator	Meaning	                                                Usage
in	        Check to see if value is in the sequence	        5 in [2,5,3,7]
instanceof	Check to see if an object is an instance of a class	obj instanceof MyClass

Complete Precedence Table

The following table shows the complete precedence of JavaScript Operators: Highest to Lowest
OPERATOR	                                        DESCRIPTION
()	                                                Parenthesis (grouping)
f(args...), x[i:i], x[i], x.attr	                Function call, slicing, subscript, dot
++, --	                                                Increment, Decrement
+, -, ~	                                                Unary Plus, Unary Minus, Bitwise NOT
*, /, %	                                                Multiplication, Division, Modulo
+, -	                                                Addition, Subtraction
<<, >>, >>>	                                        Bitwise Shifts
&	                                                Bitwise AND
^	                                                Bitwise XOR
|	                                                Bitwise OR
<, <=, >, >=, instanceof	                        Relational operators
==, ===, !=, !==	                                Equality operators
&&	                                                Logical AND
||	                                                Logical OR
?:	                                                Conditional (Ternary) operator
=, +=, -=, *=, /=, %=, <<=, >>=, >>>=	                Assignment operators
,	                                                Comma operator

Functions

Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output

Object Methods

Object.assign(target, ...sources): Copies the values of all enumerable own properties from one or more source objects to a target object.

Object.create(proto, [propertiesObject]): Creates a new object with the specified prototype object and properties.

Object.entries(obj): Returns an array of key-value pairs for an object's enumerable string-keyed properties.

Object.keys(obj): Returns an array of a given object's own enumerable property names.

Object.values(obj): Returns an array of a given object's own enumerable property values.

Object.freeze(obj): Freezes an object, preventing new properties from being added and existing properties from being removed or changed.

Object.seal(obj): Seals an object, preventing new properties from being added and marking all existing properties as non-configurable.

Object.is(obj1, obj2): Compares two values for equality. Returns true if they are the same value.

Object.hasOwnProperty(prop): Returns a boolean indicating whether an object has the specified property as its own property.

Object.getOwnPropertyNames(obj): Returns an array of all properties (enumerable or not) found directly upon a given object.

Object.getPrototypeOf(obj): Returns the prototype (i.e., the value of the internal [[Prototype]] property) of the specified object.

Object.setPrototypeOf(obj, prototype): Sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null.

Object.isPrototypeOf(obj): Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.

Object.toString(): Returns a string representing the object.

Object.valueOf(): Returns the primitive value of the specified object.

Object.defineProperty(obj, prop, descriptor): Adds the named property or modifies the attributes of the named property of an object.

Object.defineProperties(obj, props): Adds the named properties to an object, or modifies the attributes of the existing properties.

Object.getOwnPropertyDescriptor(obj, prop): Returns a property descriptor for a named property on an object.

Object.getOwnPropertySymbols(obj): Returns an array of all symbol properties found directly upon a given object.

Object.getOwnPropertyDescriptors(obj): Returns an object containing all own property descriptors for an object.

Object.isExtensible(obj): Determines if an object is extensible (whether it can have new properties added to it).

Object.preventExtensions(obj): Prevents new properties from ever being added to an object.

Math methods & static properties

Math.abs()	        Math.min()	    Math.max()	    Math.ceil()	        Math.floor()
Math.random()	        Math.round()	    Math.sqrt()	    Math.pow()	        Math.log()
Math.sin()	        Math.cos()	    Math.tan()	    Math.asin()	        Math.acos()
Math.atan()	        Math.exp()	    Math.PI	        Math.E

String Methods

There are various methods available for manipulating strings in JavaScript.
str.length: Returns the length of the string.

str.charAt(index): Returns the character at the specified index in the string.

str.concat(str1, str2, ..., strN): Concatenates two or more strings.

str.indexOf(searchValue, fromIndex): Returns the index of the first occurrence of a specified substring.

str.lastIndexOf(searchValue, fromIndex): Returns the index of the last occurrence of a specified substring.

str.slice(start, end): Extracts a portion of the string, starting at the specified index and ending at another specified index.

str.substring(start, end): Returns a new string containing characters from start to end (excluding end).

str.substr(start, length): Extracts a portion of the string, starting at the specified index and extending for a given number of characters.

str.replace(searchValue, replaceValue): Replaces a specified value with another value in a string.

str.toUpperCase(): Converts a string to uppercase letters.

str.toLowerCase(): Converts a string to lowercase letters.

str.trim(): Removes whitespace from both ends of a string.

str.startsWith(searchString, position): Checks if a string starts with a specified substring.

str.endsWith(searchString, position): Checks if a string ends with a specified substring.

str.includes(searchString, position): Checks if a string contains a specified substring.

str.split(separator, limit): Splits a string into an array of substrings based on a specified separator.

str.match(regexp): Retrieves the result of matching a string against a regular expression.

str.search(regexp): Searches a string for a specified value and returns the position of the match.

str.localeCompare(compareString[, locales[, options]]): Compares two strings in the current locale.

str.repeat(count): Returns a new string with a specified number of copies of the string.

str.padStart(targetLength, padString): Pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length.

str.padEnd(targetLength, padString): Pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length.

Array Methods

There are various methods available for manipulating Arrays in JavaScript.
arr.length           // Returns the length of the array
arr.push(6)          // Adds a new element to the end of the array
arr.pop()            // Removes the last element from the array
arr.unshift(0)       // Adds a new element to the beginning of the array
arr.shift()          // Removes the first element from the array
arr.join(", ")       // Joins all elements of an array into a string
arr.indexOf(3)       // Returns the index of the first occurrence of the specified element
arr.lastIndexOf(3)   // Returns the index of the last occurrence of the specified element
arr.slice(start, end) // Extracts a portion of the array, starting at the specified index and ending at another specified index
arr.splice(start, deleteCount, item1, item2, ...) // Changes the contents of an array by removing or replacing existing elements and/or adding new elements
arr.sort()           // Sorts the elements of an array
arr.reverse()        // Reverses the order of the elements in an array
arr.concat(array1, array2 ..., arrayN)      // Returns a new array consisting of the elements of the original array followed by one or more arrays or values.
arr.forEach(callback(currentValue, index, array))       //Executes a provided function once for each array element.
arr.map(callback(currentValue, index, array))           //Creates a new array with the results of calling a provided function on every element in the array.
arr.filter(callback(element, index, array))             //Creates a new array with all elements that pass the test implemented by the provided function.
arr.reduce(callback(accumulator, currentValue, index, array), initialValue //Applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
arr.reduceRight(callback(accumulator, currentValue, index, array), initialValue)        //Applies a function against an accumulator and each element in the array (from right to left) to reduce it to a single value.
arr.every(callback(element, index, array)) //Tests whether all elements in the array pass the test implemented by the provided function.
arr.some(callback(element, index, array)) // Tests whether at least one element in the array passes the test implemented by the provided function.
arr.includes(searchElement, fromIndex)// Determines whether an array includes a certain element, returning true or false as appropriate.

Date methods

let date = new Date();
date.getFullYear()    // Returns the year of a date as a four-digit number
date.getMonth()       // Returns the month of a date as a number (0-11)
date.getDate()        // Returns the day of the month of a date (1-31)
date.getHours()       // Returns the hour of a date (0-23)
date.getMinutes()     // Returns the minutes of a date (0-59)
date.getSeconds()     // Returns the seconds of a date (0-59)
date.getMilliseconds()// Returns the milliseconds of a date (0-999)
date.getDay()         // Returns the day of the week of a date (0-6, where Sunday is 0)
date.getTime()        // Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970
date.toString()       // Converts a date to a string

Regular Expression

test Method: Tests for a match in a string. Returns true if there is a match, otherwise false.
const regex = /pattern/;
const isMatch = regex.test("input string");
console.log(isMatch); // Output: true or false
exec Method: Searches a string for a specified pattern and returns an array containing information about the first match. If no match is found, it returns null.
const regex = /pattern/;
const matchInfo = regex.exec("input string");
console.log(matchInfo); // Output: Array or null
match Method (String Method): Returns an array containing all matches, or null if no match is found.
const regex = /pattern/g; // Note the 'g' flag for global matching
const matches = "input string".match(regex);
console.log(matches); // Output: Array or null
search Method (String Method): Returns the index of the first match, or -1 if no match is found.
const regex = /pattern/;
const index = "input string".search(regex);
console.log(index); // Output: Index or -1
replace Method (String Method): Replaces matched substrings with a specified string.
const regex = /pattern/;
const replacedString = "input string".replace(regex, "replacement");
console.log(replacedString); // Output: Modified string
Modifiers: Regular expressions can include modifiers to perform case-insensitive (i), global (g), or multiline (m) matching.
const caseInsensitivePattern = /pattern/i;
const globalPattern = /pattern/g;
const multilinePattern = /^pattern/m;

Promises and Async/Await

Asynchronous programming is a crucial part of JavaScript. Promises and async/await are used to handle asynchronous operations more effectively.
Promises
A Promise is an object representing the eventual completion or failure of an asynchronous operation. It provides a cleaner way to work with asynchronous code compared to using callbacks. Example using Promise:
const fetchData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = 'Async data';
      // Simulating success
      resolve(data);
      // Simulating an error
      // reject(new Error('Failed to fetch data'));
    }, 1000);
  });
};

fetchData()
  .then((result) => {
    console.log('Success:', result);
  })
  .catch((error) => {
    console.error('Error:', error.message);
  });

Async/Await:

The async keyword is used to create functions that return Promises. The await keyword is used to wait for a Promise to settle, and it can only be used inside an async function. Async/Await is particularly useful when dealing with multiple asynchronous operations or when you want to make asynchronous code look more like synchronous code, improving readability. Keep in mind that async/await is built on top of Promises and is syntactic sugar for working with them.

Async/Await Syntax:

const myAsyncFunction = async () => {
  try {
    const result = await somePromiseFunction();
    // Code here runs after the promise is resolved
    console.log(result);
  } catch (error) {
    // Handle errors
    console.error(error);
  }
};

Example Usage Async/Await

const fetchData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = 'Async data';
      // Simulating success
      resolve(data);
      // Simulating an error
      // reject(new Error('Failed to fetch data'));
    }, 1000);
  });
};

const fetchDataAsync = async () => {
  try {
    const result = await fetchData();
    console.log('Success:', result);
  } catch (error) {
    console.error('Error:', error.message);
  }
};

fetchDataAsync();