What is JavaScript?
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. It is one of the core technologies of the World Wide Web, alongside HTML and CSS, and the powerhouse behind the rapidly evolving internet by helping create beautiful and crazy fast websites.
What is JavaScript Cheat Sheet?
We have come up with a cheat sheet to help our readers learn JavaScript in the easiest way possible. It is a documentation of the basics and concepts of JavaScript, quick, correct, and ready-to-use code snippets for common circumstances in JavaScript on one page. It is helpful to both beginner and professional coders of JavaScript.
Table of Content:
Fundamentals: To use JavaScript on website we need to attach the JavaScript file to the HTML file. To do the better codewe should also do the commenting during the code. There are two types of commenting sinle-line and multiline.
Variables: Variables in JavaScript are containers for storing data. JavaScript allows the usage of variables in the following three ways:
Variable | Description | Example |
var | var is the most commonly used variable in JavaScript. It can be initialized to a value, redeclared and its value can be reassigned, but only inside the context of a function. It can be function scoped or globally scoped. | var x= value; |
let | let in JavaScript is similar to var only difference lies in the scope. var is function scoped, let is block scoped. It cannot be redeclared but can be reassigned a value. | let y= value; |
const | const in JavaScript is used to declare a fixed value that cannot be changed over time once declared. They can neither be redeclared nor be reassigned. They cannot be hoisted either. | const z= value; |
JavaScript
|
Datatypes: There are different types of values and data that can be stored in JavaScript variables. For the machine to be able to operate on variables, and correctly evaluate the expressions it is important to know about the type of variables involved. There are following primitive and non-primitive datatypes in JavaScript:
Datatype | Description | Example |
Number | These are just numeric values. They can be real or integers. | var x= number; |
String | It is of series of multiple characters written within double or single quotes. | var x= “characters”; |
Boolean | It can have only two values true or false. | var x= true/false; |
Null | It is a special value that represents that the variable is empty or has an unknown value. it is Equivalent to an empty string or 0. | var x= null; |
Undefined | It represents that the variable is declared but not assigned any value. A variable can also be emptied by setting the value to undefined. | let x; / let x= undefined; |
Object | It is a complex data type that allows us to store a collection of data. It contains properties defined as key-value pair. |
var x= { key: “value”; key: “value”;} |
Array | It is a datatype used to store multiple values in a single variable. each value(element) has a numeric position(index) which starts from 0 , and it may contain data of any data type and even other arrays. | |
Function | In JavaScript all functions are objects that can be called to execute a block of code. Since functions are objects, so it is possible to assign them to variables. They can be stored in variables, objects, and arrays and also can be passed as arguments to other functions and returned from functions. |
JavaScript
|
Operators: JavaScript operators are symbols used to perform various operations on variables (operands). Following are the different types of operators:
Operators | Description | Symbols |
Arithmetic | Arithmetic operators are used to perform basic arithmetic operations like addition, subtraction, multiplication, division, modulus, increment, and decrement on the variables(operands). | +,-,*,/,%,++,– |
Comparison | The JavaScript comparison operator compares the two operands as equal, not equal, identical, greater than, less than, greater than equal to, less than equal to. | ==, ===,!=,>,<,>=,<= |
Bitwise | The bitwise operators perform bitwise operations like bitwise OR, bitwise AND, XOR, NOT, right shift, and left shift on variables(operands). | &, | , ^,~,<<, >>, >>> |
Logical |
There are three logical operators in javascript.
|
exp1&&exp2,exp1 ||exp2, !exp |
Assignment | Assignment operators assign values to JavaScript variables. These are assign, add and assign, subtract and assign, divide and assign, modulus and assign. | =, +=,-=,*=,/=,%= |
JavaScript
|
-
Scope: Scope defines the accessibility or visibility of variables in JavaScript. That is, which sections of the program can access a given variable and where the variable can be seen. Using scope, we can avoid unintended modifications to the variables from other parts of the program. There are usually three types of scopes:
Scope chain: The scope chain is used to resolve the value of variable names in JavaScript. Without a scope chain, the JavaScript engine wouldn’t know which value to pick for a certain variable name if there are multiply defined at different scopes. If the JavaScript engine could not find the variable in the current scope, it will look into the outer scope and will continue to do so until it finds the variable or reaches the global scope. If it still could not find the variable, it will either implicitly declare the variable in the global scope (if not in strict mode) or return an error.
scope | Description |
function | Variables declared inside a function is inside the function scope also known as local scope. Variables function scoped can only be accessed from within that function, which means they can’t be accessed from the outside code.globalThe variables in global scope variables |
global | The variables in global scope can be accessed from anywhere in the program. Any variable that’s not inside any function or block (a pair of curly braces), is inside the global scope. |
block | This scope restricts the variable that is declared inside a specific block, from access by the outside of the block and scopes it to the nearest pair of curly brackets. The let and const keyword introduced in ES6 facilitates the variable to be block scoped. |
JavaScript
|
Functions: A JavaScript function is a block of code designed to perform a particular task. It is executed when invoked or called. Instead of writing the same piece of code again and again you can put it in a function and invoke the function when required. JavaScript function can be created using the functions keyword. Some of the functions in JavaScript are:
Function | Description |
parseInt() | This function is used for parsing the argument passed to it and returning an integral number. |
parseFloat() | This function is used for parsing the argument passed to it and returning a floating-point number. |
isNaN() | This function is used for determining if a given value is Not a Number or not. |
Number() | This function is used for returning a number converted from what is passed as an argument to it. |
eval() | This function is used for evaluating JavaScript programs presented as strings. |
prompt() | This function is used for creating a dialogue box for taking input from the user. |
encodeURI() | This function is used for encoding a URI into a UTF-8 encoding scheme. |
match() | This is an inbuilt function in JavaScript used to search a string for a match against any regular expression. |
JavaScript
|
Arrays: In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. Arrays use numbers as index to access its “elements”.
Declaration of an Array: There are basically two ways to declare an array.
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() | This method adds a new element at the very end of an array. |
pop() | This method removes the last element of an array. |
concat() | This method joins various arrays into a single array. |
shift() | This method removes the first element of an array |
unShift() | This method adds new elements at the beginning of the array |
reverse() | This method reverses the order of the elements in an array. |
slice() | This method pulls a copy of a part of an array into a new array. |
splice() | This method adds elements in a particular way and position. |
toString() | This method converts the array elements into strings. |
valueOf() | This method returns the primitive value of the given object. |
indexOf() | This method returns the first index at which a given element is found in an array. |
lastIndexOf() | This method returns the final index at which a given element appears in an array. |
join() | This method combines elements of an array into one single string and then returning it |
sort() | This method sorts the array elements based on some condition. |
JavaScript
|
Loops: Loops are a useful feature in most programming languages. With loops you can evaluate a set of instructions/functions repeatedly until certain condition is reached. They let you run code blocks as many times as you like with different values while some condition is true. Loops can be created in the following ways in JavaScript:
Loop | Description | Syntax |
for | For statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping. | for (initialization condition; testing condition;increment/decrement) { statement(s) } |
while | It in an Entry control loop. It starts with the checking of condition. If it evaluated to true, then the loop body statements are executed otherwise first statement following the loop is executed. | while (boolean condition) { loop statements… } |
do-while | do while loop is similar to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of Exit Control Loop. | do { statements.. } while (condition); |
for-in | This is another version of for loop used by javascript to provide a simpler way to iterate through the properties of an object. Its very useful while working with objects. | for (variableName in Object) { statement(s) } |
JavaScript
|
If-else: If-else is used in JavaScript to execute a block of codes conditionally. These are used to set conditions for your code block to run. If certain condition is satisfied certain code block is executed otherwise else code block is executed. JavaScript allows us to nest if statements within if statements as well. i.e, we can place an if statement inside another if statement.
if (condition) { // Executes this block if // condition is true } else { // Executes this block if // condition is false }
JavaScript
|
Strings: Strings in JavaScript are primitive and immutable data types used for storing and manipulating text data which can be zero or more characters consisting of letters, numbers or symbols. JavaScript provides a lot of methods to manipulate strings. Some most used ones are:
Methods | Description |
concat() | This method is used for concatenating or joining multiple strings into a single string. |
match() | This method is used for finding the matches of a string against a provided pattern string. |
replace() | This method is used for finding and replacing a given text in the string. |
substr() | This method is used to extract length characters from a given string , counting from the start index. |
slice() | This method is used for extracting an area of the string and returning it |
lastIndexOf() | This method is used to return the index (position) of the last occurrence of a specified value in a string. It is case-sensitive and it searches the string from the end to the beginning. |
charAt() | This method is used for returning the character at a particular index of a string |
valueOf() | This method is used for returning the primitive value of a string object. It does not change the original string. |
split() | This method is used for splitting a string object into an array of strings at a particular index |
toUpperCase() | This method is used for converting strings to upper case. |
toLoweCase() | This method is used for converting strings to lower case. |
JavaScript
|
Regular Expressions: A regular expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text to replace operations. A regular expression can be a single character or a more complicated pattern.
Syntax:
/pattern/modifiers;
You can also use regEx() to create regular expression in javascript:
const regex1 = /^ab/; const regex2 = new Regexp('/^ab/');
Let us look at how JavaScript allows 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 |
. | This is used for finding a single character, except newline or line terminator |
d | This is used to find a digit. |
s | This is used to find a whitespace character |
uxxxx | This is used to find the Unicode character specified by the hexadecimal number xxxxx |
Quantifiers define quantities. 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+ | This is used to match any string that contains at least one n |
n* | This is used to match any string that contains zero or more occurrences of n |
n? | This is used to matches any string that contains zero or one occurrences of n |
n{x} | This is used for matching strings that contain a sequence of X n’s |
^n | This is used for matching strings with n in the first place |
Here is an example to help you understand regular expression better.
JavaScript
|
Data Transformation: Data transformation is the process of converting data from one format to another. Data Transformation in JavaScript can be done with the usage of higher-order functions which can accept one or more functions as inputs and return a function as the result. All higher-order functions that take a function as input are map(), filter(), and reduce().
Method | Description | Syntax |
map() | The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. map() is a non-mutating method used to iterate over an array and calling function on every element of array. | array.map(function(currentValue, index, arr), thisValue) |
filter() | The arr.filter() method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a given condition or criteria. | array.filter(callback(element, index, arr), thisValue) |
reduce() | The arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. | array.reduce( function(total, currentValue, currentIndex, arr), initialValue ) |
JavaScript
|
Date objects: The Date object is an inbuilt datatype of JavaScript language. It is used to deal with and change dates and times. There are four different way to declare a date, the basic things is that the date objects are created by the new Date() operator.
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() | This is used to return the month’s day as a number (1-31) |
getTime() | This is used to get the milliseconds since January 1, 1970 |
getMinutes() | This is used to return the current minute (0-59) |
getFullYear() | This is used to return the current year as a four-digit value (yyyy) |
getDay() | This is used to return a number representing the weekday (0-6) to |
parse() | This is used to return the number of milliseconds since January 1, 1970 from a string representation of a date. |
setDate() | Returns the current date as a number (1-31) |
setTime() | This is used to set the time (milliseconds since January 1, 1970) |
JavaScript
|
DOM: DOM stands for Document Object Model. It defines the logical structure of documents and the way a document is accessed and manipulated. JavaScript can not understand the tags in HTML document but can understand objects in DOM. There are many different ways to build and alter HTML elements with JavaScript called nodes. Below are some of the methods provided by JavaScript to manipulate these nodes and their attributes in the DOM:
Method | Description |
appendChild() | It adds a new child node as the last child node to an element. |
cloneNode() | It is a function that duplicates an HTML element. |
hasAttributes() | It returns true If an element has any attributes otherwise, it returns false. |
removeChild() | It removes a child node from an element using the Child() method. |
getAttribute() | It returns the value of an element node’s provided attribute. |
getElemetsByTagName() | It returns a list of all child elements whose tag name is supplied. |
isEqualNode() | It determines whether two elements are the same. |
JavaScript
|
Numbers and Math: JavaScript provides various properties and methods to deal with Numbers and Maths.
Number Properties include MAX value, MIN value, NAN(not a number), negative infinity , positive infinity etc. Some of the methods in JavaScript to deal with numbers are:
Method | Description |
valueOf() | It returns a number in its original form. |
toString() | It returns a string representation of an integer. |
toFixed() | It Returns a number’s string with a specified number of decimals. |
toPricision() | It converts a number to a string of a specified length. |
toExponential() | It returns a rounded number written in exponential notation as a string. |
JavaScript
|
Javascript provides math object which is used to perform mathematical operations on numbers. There are many math object properties which include euler’s number, PI, square root, logarithm. Some of the methods in JavaScript to deal with math properties are:
Method | Description |
max(x,y,z…n) | It Returns the highest-valued number |
min(x,y,z…n) | It returns the lowest-valued number |
exp(x) | It returns x’s exponential value. |
log(x) | It returns the natural logarithm (base E) of x. |
sqrt(x) | It returns x’s square root value. |
pow(x,y) | It returns the value of x to the power of y |
round(x) | It rounds the value of x to the nearest integer |
sin(x) | It returns the sine value of x(x is in radians). |
tan(x) | It returns the angle’s(x) tangent value. |
JavaScript
|
Events: Javascript has events to provide a dynamic interface to a webpage. When a user or browser manipulates the page events occur. These events are hooked to elements in the Document Object Model(DOM). Some of the events supported by JavaScript:
Events | Description |
onclick() | This is a mouse event. When a user clicks on an element, an event is triggered. |
onkeyup() | This event is a keyboard event and executes instructions whenever a key is released after pressing. |
onmouseover() | This mouse event corresponds to hovering the mouse pointer over the element and its children |
onmouseout() | This event is triggered when the user moves the mouse cursor away from an element or one of its descendants. |
onchange() | This event detects the change in value of any element listing to this event. |
onload() | When an element is loaded completely, this event is evoked. |
onfocus() | This event is triggered when an aspect is brought into focus. |
onblur() | This event is evoked when an element loses focus. |
onsubmit() | This event in invoked when a form is filled out and submitted. |
ondrag() | This event is invoked when an element is dragged. |
JavaScript
|
Error: When executing JavaScript code, errors will most definitely occur when the JavaScript engine encounters a syntactically invalid code. These errors can occur due to the fault from the programmer’s side or the input is wrong or even if there is a problem with the logic of the program. Javascript has a few statements to deal with these errors:
Statement | Description |
try | This statement lets you test a block of code to check for errors. |
catch | This statement lets you handle the error if any are present. |
throw | This statement lets you make your own errors. |
finally | This statement lets you execute code, after try and catch. |
JavaScript
|
Window Properties: The window object is the topmost object of DOM hierarchy. Whenever a window appears on the screen to display the contents of document, the window object is created. To access the properties of the window object, you will specify object name followed by a period symbol (.) and the property name.
Syntax:
window.property_name
The properties and methods of Window object that are commonly used are listed in the below tables:
Property | Description |
window | It returns the current window or frame. |
screen | Returns the window’s Screen object. |
toolbar | It will result the toolbar object, whose visibility can be toggled in the window. |
Navigator | Returns the window’s Navigator object. |
frames[] | Returns all <iframe> elements in the current window. |
document | It returns a reference to the document object of that window |
closed | It holds a Boolean value that represents whether the window is closed or not. |
length | It represents the number of frames in the current window. |
History | Provides the window’s History object. |
JavaScript
|
Method | Description |
alert() | Shows a message and an OK button in an alert box. |
print() | Prints the current window’s content. |
blur() | Removes the current window’s focus. |
setTimeout() | It calls a function or evaluates an expression after a specified time interval. |
clearTimeout() | Removes the timer that was set with setTimeout() |
setInterval() | Calls a function or evaluates an expression at intervals defined by the user. |
prompt() | Shows a conversation window asking for feedback from the visitor. |
close() | Closes the currently open window. |
focus() | Sets the current window’s focus. |
resizeTo() | Resizes the window to the width and height supplied. |
JavaScript
|
JavaScript is well-known for the development of web pages, and many non-browser environments also use it. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
We have a similar cheat sheet to help you with HTML & CSS concepts as well. Check it out here HTML Cheat Sheet & CSS Cheat Sheet.
Learning JavaScript is the key to becoming a good earning front-end developer. We have a self-paced JavaScript course that will help you learn JavaScript and its basics.