Javascript Cheat Sheet

Table of Contents What is JavaScript?What is a Cheat Sheet in programming?Download JavaScript Cheat SheetAdd internal JavaScriptComments in JavaScriptData Types in JavaScriptFunctions in JavaScriptVariables in JavaScriptArray Function in JavaScriptLoops  in JavaScript if-else statements in JavaScriptString functions …

Javascript Cheat Sheet

What is JavaScript?

Javascript is a scripting language that is used to interact with users. It can run on web browsers and non-browsing environments as well. It is a client-side language that makes web pages dynamic that engages the users. Most client-side functions, such as submitting forms, scrolling, hovering the mouse, etc., are performed by JavaScript. It is a case-sensitive language. It makes web pages dynamic and more interactive to the user. ECMAScript (ES 6) is the official name of JavaScript. Organization named JavaScript to make it popular as Java.

What is a Cheat Sheet in programming?

As described by name, a small sheet contains all essential vital points, formulas, and theories that take into Exam. All information should occupy a small a space as possible. A cheat sheet in programming language means the compilation of syntax, key tricks, mostly used library function, methods, and data types.

Download JavaScript Cheat Sheet

Here is a quick guide to using JavaScript tricks.

Add internal JavaScript

To add JavaScript code on a page, use <script> tag in HTML file. The syntax is:

<script type = “text/javascript”> 
// Code inside it
</script>

For neat code, commonly developer creates a separate file of JavaScript by using the .js extension and call the file on the page as:

<script src="myJavaScriptfile.js"></script>

Comments in JavaScript

There are two types of comments:  

// single line comment 
/* multiple line comment when you write a lot of things */

Data Types in JavaScript

Data typeDescription and Examples
NumberIt is a primitive data type that initializes numbers. e.g.: var x = 10;
BooleanIt declares two conditions, and the user can select only one at one time; it can be true or false. e.g.: var window open = false;
StringIt declares values that make text. e.g., var name = “This  is JS example.”;
VariableIt stores changeable ( mutable) data. e.g.:var money;
undefinedIt is a particular data type in which value is not assigned.
ObjectIt is a composite data type that key-value pair stores a combination of data.
var student ={ name: “ Sam”;
       yearOfBirth = 1998;
      calculateAge = function() {
//Code to calculate age
}

Functions in JavaScript

The function is a callable method that can be reused in your program once it is created. In JavaScript, the function is declared by a function keyword that has a unique function name with parameter list and statement block inside curly braces.

<script type = "text/javascript">
     <!-- function functionname(parameter_list) { statements } //-->
</script>

Variables in JavaScript

Three keywords that can initialize the variables:

  • var: widely used to initialize data. Easily accessible and can be reassigned. 
  • const: initialize variable once cannot be reassigned.
  • let:  can be reassigned but only used inside the block of code where it is declared.

Array Function in JavaScript

MethodDescription
isFinite()If the number is finite, it returns true
concat()Concatenate multiple arrays into a single array.
sort()Sort a list of array alphabetical sequences.
join()Merging the elements of the list of an array in a string.
reverse()Elements categorize in reverse order.
pop()It erases the endmost element from the list of an array
push()It adds a new element in the last array.
shift()It erases the initial element of the array.
unshift()At the start of an array, a new element will append
slice()Extract the segment/ chunk of an array and provide it to a new array.
splice()Arrange the elements in a specific manner and position.
lastIndexOf()A case-sensitive function returns the location of a specified value where that last occurs.
tostring ()It displays on the output screen all the array elements converted into a string separated by commas.

Loops  in JavaScript

  • for:  block of code executes iteratively as the condition is true.
for( var a=0; a<n; a++)
{
console.log(a);
}
  • while: Code execution process remains to continue until the condition goes false. In this loop, the Developer is unsure how many times the loop iterates; it stops when the specified condition goes to end or wrong.
while(a<n)
{
      console.log(a);
          a++;
}
do
{
         console.log(a)
          i++;
}      while(a<n)

Break: It stops and exits the iteration of the loop. Continue: It is used to end the statement in the current iteration of the loop and start with the next upcoming iteration of the loop.

 if-else statements in JavaScript

if-else if-else condition

if (first condition )
{
        //execute this code
} 
else if (second condition )
{
       // execute new code
}
 else
{
       // execute if no above conditions are  true

String functions in JavaScript

MethodDescriptionCode Snippet
lengthFind out the length of the stringvar a = “MyScript”;
a.length;
indexOf()Determine the position of character or text in the stringvar a = “It is a scripting language”;
var b = a.indexof(“scripting”);
concat()Combine two or more strings into one stringvar a = “JavaScript is a ”;
var b = “scripting language”;
var c = a.concat(“: ”, b);
trim()Cut whitespaces from the codevar a = “              hi, there is John!         ”;
a.trim();
charat()Determine the position of charactersvar a = “javaScript”;
a.charat(1) will return a
split()Split string into arrayvar a = “script”;
var arr = a.split(“”);
will return an array of characters s, c, r, i, p, t, and so on…
search()Search the value and returns the position in a stringvar a = “It is a scripting language”; var b = a.search(“scripting”);
lastindexof()returns last index of text in a stringvar a = “W3school is nice website”;
var b = a.indexof(“nice”, 6);
replace()Replace the value with another valuevar a = “W3school is nice website”;
var b = a.replace(“nice”, “amazing”);
touppercase()Convert all characters into uppercasevar a = “It is a scripting language”;
var b = a.touppercase (a);
tolowercase()Convert all characters into lowercasevar a = “It is a scripting language”;
var b = a.tolowercase(a);

Operators in JavaScript

It is an action that is performed on variables and values.

Arithmetic operatorsIn addition, by using the ‘ +’ sign
Subtraction by using the ‘ -’ sign
Multiply   by using the ‘ *’ sign
Divide by using the ‘ /’ sign
Remainder  by using the ‘ %’ sign
Increment by using  ‘ ++’ sign
Decrement by using  ‘ –’ sign
Logical operatorsAnd by using  ‘ &&’ sign
OR by using  ‘ ||’ sign
Not by using the ‘ |’ sign
Comparison operatorsEqual to by using  ‘ ==’ sign
Equal value and type  by using  ‘ ===’ sign
 Not equal by using  ‘ !=’ sign
Not equal value or type by using  ‘!==’ sign

Greater than by using  ‘>’ sign
 
Less than by using  ‘ <’ sign

Greater than or equal to by using  ‘>=’ sign
Less than or equal to by using  ‘ <=’ sign
Ternary operator by using  ‘ ?’ sign

Mathematical Method in JavaScript

Math MethodsDescription
abs()As abs stand for absolute, that returns the static absolute value of a number.
acos()A static method that returns the numeric value for inverse cosine between 0 and π
asin()Returns inverse of sine of the number in radians
atan()Returns inverse of the tangent of n in numeric value
cos()Returns Cosine value of a degree or radian.
exp()It returns Ex, where E stands for Euler’s number
ceil()It returns round up the value
floor()Returns round down value of n
log()It returns the natural logarithm function value
max(3, 4, 5, 15, 19, 55, 90)Returns maximum value from the specified list
min(3, 4, 5, 15, 19, 55, 90)Return the minimum value from the specified list
pow(a, b)b is the  power of a
random()Returns a random number between 1 or 0.
sin()Returns value of sine of a degree or radian.
sqrt()It returns the square root of a number.
tan()Returns tangent value with the help of angle value.

Numbers in JavaScript

NaN = Not a Number. It indicates that value is not a legal number.

Number MethodsDescription
toExponential()It converts the number into exponential notation.
toFixed()Returns the string of a number with a specified number of decimals
toPrecision() It is a method used to arrange a particular number to a specified length. If the original number length is shorter than the arranged number, add decimals and nulls to create the required size.
toString()Returns a number in a string manner

JavaScript Events

Mouse Event

  • onclick
  • oncontextmenu
  • ondblclick
  • onmousedown
  • onmouseenter
  • onmouseeleave
  • onmousemove
  • onmouseover

Keyboard Event

  • onkeydown
  • onkeypress
  • onkeyup

DOM in JavaScript

Document Object Model dynamically allows programs and scripts to access the document, manipulate its style and structure.

Node MethodsDescription
appendChid()Reposition or insert a node as the last child of the parent node.
cloneNode()Create the replica of the node and returns the clone
compareDocumentPosition()Returns the position number of the specified node relative to another node
in the same  document
attributes()True if the specified node contains any attributes; else, it returns false.
has child node()True if the specified node contains any child node else, it returns false.
insertBefore()Add a new child node right before the existing child node
isDefaultNamespace()Work a Boolean, true when specified namespace URI is default else false
removeChild()Returns remove node object after removing a child node from an element.
replaceChild()exchange or replace a child node with an existing or new node.

Statement

It is a group of words, operators, variables, and values that perform a declared task.

Output in JavaScript

JavaScript can “display” output in different ways:

  • document.write(): write output into HTML
  • innerHTML : Writing into an HTML element. It allows access to the inner HTML element.
  • console.log(): perform debugging and display output in browser console.
  • window.alert(): display output in  alert window . Here we can skip the window keyword.
  • prompt() : Prompt dialog box for user input .

JavaScript Top Frameworks

  • React.js: JavaScript front-end category framework that is developed by Facebook developers.
  • Vue.js: Lightweight front-end framework used to create user interface single page applications with high performance.
  • Angular.js: It is a client-side single web page application Developed by Google Engineers.
  • Express.js: It is an open-source back-end category framework used in Node.JS
  •  Next.js: It is an end-to-end framework used with React and developed by Dutch company Vercel.

Date Function in JavaScript

Date MethodsDescription
setDate()Establish the date as a number
setFullYear()establish the year in complete four digits (yyyy)
setHoursEstablish hours among 0 to 23
setMinutesSet minutes among 0 to 59
setMonths()Set months  among 0 to 11
setSeconds()Set seconds among 0 to 59
setTime()Establish time since January 1, 1970
setUTCDate()Sets Universal Date
getDate()Returns the current day from the date object
getDay()Returns  the weekday
getFullYear()Returns the year
getHours()Returns the time in hour(0-23)
getMinutes()Returns the time in minutes
getSeconds()Returns the second
getTime()Returns the time since January 1, 1970
getUTCDate()Returns universal time
getMonth()Returns the month(0-11)

Bitwise Operators in JavaScript

SignNameDescription
&ANDSets result in bits as 1 if and only if both bits are 1.
|ORSets result as 1 bit if anyone bit from both is 1.
^XORSets result in 1 bit if only one of two bits is 1
~NOTInvert
<<Zero fill left shift.Bits shifted into the left and zeroed filled into the right side.
>>>Zero fill right shift.Bits shifted into the right and zeroed filled into the left side.

JavaScript Errors

  • try: This statement tests the error in block of code
  • catch: This statement allows you to handle the error.
  • throw: This statement uses the try or catch statement to let you create custom error messages.
  • finally: This statement allows the execution of code after try and catch, regardless of the output.

JavaScript Class

A class keyword in JavaScript is used to create a class. It is Template, not an object. Add a method named constructor() inside the class.

Syntax

class JsClassName {
  constructor() { ...
           }
}

Conclusion

JavaScript is a scripting language that is used to make web pages dynamic to interact with users. Most client-side functions such as scrolling, and hovering the mouse, etc., are performed by JavaScript. In this JavaScript Cheatsheet, we collect all important JavaScript methods, functions, attributes, data types, operators, Loops, conditions, etc., in one place. This cheat sheet is a concise overview of JavaScript language that will probably be useful when you start working with this language.

Leave a Comment