Skip to content
Related Articles

Related Articles

JavaScript Cheat Sheet – A Basic Guide to JavaScript

View Discussion
Improve Article
Save Article
  • Difficulty Level :Easy
  • Last Updated :19 Sep, 2022
View Discussion
Improve Article
Save Article

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 a better code, we should also do the commenting during the code. There are two types of commenting single-line and multiline.

  • For a browser to know the code is written in JavaScript and execute it we must enclose the code within the <script> tag to include it on the HTML page.
    <script type="text/javascript"> 
     </script>
  • An external JavaScript file can also be written separately and included within our HTML file using the script tag as:
    <script src="filename.js"></script>.
  • JavaScript comments can be extremely useful to explain JavaScript code and help understand what’s going on in your code and make it more readable.
    • Single-line comments: Start a single-line comment with “//”.
    • Multi-line comments: Wrap the comment in /* and*/ if it spans multiple lines.

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

VariableDescriptionExample
varvar 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;
letlet 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;
constconst 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




<script>
    // Using var keyword
    document.write("<u>Using var Keyword</br></u>")
    varx = 1;
    if(x === 1) {
        varx = 2;
        document.write(x + "</br>"); // Output: 2
    }
    document.write(x + "</br>"); // Output: 2
      
    // Using let keyword
    document.write("<u>Using let Keyword</br></u>")
    let x1 = 1;
    if(x1 === 1) {
        let x1 = 2;
        document.write(x1 + "</br>"); // Output: 2
    }
    document.write(x1 + "</br>"); // Output: 1
      
    // Using const keyword
    document.write("<u>Using const Keyword</br></u>")
    const number = 48;
  
    // Changing const value will display TypeError
    try{
        number = 42;
    } catch(gfg) {
        document.write(gfg + "</br>");
    }
    document.write(number); // Output: 48
</script>

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:

DatatypeDescriptionExample
NumberThese are just numeric values. They can be real or integers.var x= number;
StringIt is of series of multiple characters written within double or single quotes.var x= “characters”;
BooleanIt can have only two values true or false.var x= true/false;
NullIt 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;
UndefinedIt 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;
ObjectIt 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”;}

ArrayIt 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.

var x =[‘y1’, ‘y2′,’y3′,’y4’];

y: any datatype

FunctionIn 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.

function x(arguments){

block of code

}

JavaScript




<script>
  // String
  let str = "hello geeks";
  document.write(str + "</br>");
  
  // number
  const num = 10;
  document.write(num + "</br>");
  
  // boolean
  const x = "true";
  document.write(x + "</br>");
  
  // undefined
  let name;
  document.write(name + "</br>");
  
  // null
  const number = null;
  document.write(number + "</br>");
  
  // symbol
  const value1 = Symbol("hello");
  const value2 = Symbol("hello");
  document.write(value1 + "</br>");
  document.write(value2 + "</br>");
  
  // Here both values are different as they
  // are symbol type which is immutable object
  const object = {
    firstName: "geek",
    lastName: null,
    batch: 2,
  };
  document.write(object);
</script>

Operators: JavaScript operators are symbols used to performvarious operations on variables (operands). Following are the different types of operators:

OperatorsDescriptionSymbols
ArithmeticArithmetic operators are used to perform basic arithmetic operations like addition, subtraction, multiplication, division, modulus, increment, and decrement on the variables(operands).+,-,*,/,%,++,–
ComparisonThe JavaScript comparison operator compares the two operands as equal, not equal, identical, greater than, less than, greater than equal to, less than equal to.==, ===,!=,>,<,>=,<=
BitwiseThe 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.

  • 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 ||exp2, !exp
AssignmentAssignment operators assign values to JavaScript variables. These are assign, add and assign, subtract and assign, divide and assign, modulus and assign.=, +=,-=,*=,/=,%=

JavaScript




<script>
  let x = 5;
  let y = 3;
  
  // Addition
  document.write("x + y =", x + "</br>"); // 8
  
  // Subtraction
  document.write("x - y =", x - y + "</br>"); // 2
  
  // Multiplication
  document.write("x * y =", x * y + "</br>"); // 15
  
  // Division
  document.write("x / y =", x / y + "</br>");
  
  // Remainder
  document.write("x % y =", (x % y) + "</br>"); // 2
  
  // Increment
  document.write("++x =", ++x + "</br>"); // x is now 6
  document.write("x++ =", x++ + "</br>");
  document.write("x =", x + "</br>"); // 7
  
  // Decrement
  document.write("--x =", --x + "</br>"); // x is now 6
  document.write("x-- =", x-- + "</br>");
  document.write("x =", x + "</br>"); // 5
  
  // Exponentiation
  document.write("x ** y =", x ** y + "</br>");
  
  // Comparison
  
  document.write(x > y + "</br>"); // true
  
  // Equal operator
  document.write((2 == 2) + "</br>"); // true
  
  // Not equal operator
  document.write((3 != 2) + "</br>"); // true
  
  // Strict equal operator
  document.write((2 === 2) + "</br>"); // true
  
  // Strict not equal operator
  document.write((2 !== 2) + "</br>"); // true
  
  // Logical operator
  // logical AND
  document.write((x < 6 && y < 5) + "</br>"); // true
  
  // logical OR
  document.write((x < 6 || y > 6) + "</br>"); // true
  // logical NOT
  document.write(!(x < 6) + "</br>"); // false
</script>

JS scope and scope chain:

  • 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.

scopeDescription
functionVariables 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
globalThe 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.
blockThis 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




<script>
   let z=3
   functionfoo() {
     if(true) {
        varx = '1'; // Exist in function scope
        const y = '2'; // Exist in block scope 
     }
     document.write(x);
     document.write(y);
     document.write(z); // Exist in global scope
   }
   foo();
</script>

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:

FunctionDescription
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




<script>
  // JS parseInt function
  varv1 = parseInt("3.14");
  document.write('Using parseInt("3.14") ='+ v1 + "</br>");
  
  // JS parsefloat function
  // It returns floating point Number until 
  // it encounters Not a Number character
  a = parseFloat("[email protected]");
  document.write('parseFloat("[email protected]") ='+ a + "</br>");
  
  // JS isNAN fucntion
  document.write(isNaN(12) + "<br>");
  
  // JS number() function
  functionnum() {
    vara = true;
  
    varvalue = Number(a);
    document.write(value + "</br>");
  }
  num();
  
  // JS eval() function
  functionevalfn() {
    vara = 4;
    varb = 4;
    varvalue = eval(newString(a * b));
    document.write(value + "</br>");
  }
  evalfn();
  
  // JS encode URI function
  const url = "https://www.google.com/search?q=geeks for geeks";
  const encodedURL = encodeURI(url);
  document.write(encodedURL);
</script>

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:

MethodDescription
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




<script type="text/javascript">
  // Declaring and initializing arrays
  vararr = [10, 20, 30, 40, 50]; // number array
  vararr1 = [110, 120, 130, 140];
  varstring_arr = ["Alex", "peter", "chloe"]; // string array
  
  // push: Adding elements at the end of the array
  arr.push(60);
  document.write("After push op "+ arr + "</br>");
  
  // unshift() Adding elements at the start of the array
  arr.unshift(0, 10);
  document.write("After unshift op "+ arr + "</br>");
  
  // pop: removing elements from the end of the array
  arr.pop();
  document.write("After pop op"+ arr + "</br>");
  
  // shift(): Removing elements from the start of the array
  arr.shift();
  document.write("After shift op "+ arr + "</br>");
  
  // splice(x,y): removes x number of elements starting from index y
  arr.splice(2, 1);
  document.write("After splice op"+ arr + "</br>");
  
  // reverse(): reverses the order of elements in array
  arr.reverse();
  document.write("After reverse op"+ arr + "</br>");
  
  // concat(): merges two or more array
  document.write("After concat op"+ arr.concat(arr1));
</script>   

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:

LoopDescriptionSyntax
forFor 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)
}
whileIt 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-whiledo 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-inThis 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




<script type="text/javascript">
  // Illustration of for loop
  varx;
  
  // for loop begins when x=2
  // and runs till x <=4
  for(x = 2; x <= 4; x++) {
    document.write("Value of x:"+ x + "<br />");
  }
  
  // Illustration of for..in loop
  // creating an Object
  varlanguages = {
    first: "C",
    second: "Java",
    third: "Python",
    fourth: "PHP",
    fifth: "JavaScript",
  };
  
  // Iterate through every property of 
  // the object languages and print all
  // of them using for..in loops
  for(itr inlanguages) {
    document.write(languages[itr] + "<br >");
  }
  
  // Illustration of while loop
  vary = 1;
  
  // Exit when x becomes greater than 4
  while(y <= 4) {
    document.write("Value of y:"+ y + "<br />");
  
    // Increment the value of y for next iteration
    x++;
  }
  
  // Illustration of do-while loop
  varz = 21;
  
  do{
    // The line while be printer even if the condition is false
    document.write("Value of z:"+ z + "<br />");
  
    z++;
  } while(z < 20);
</script>

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)
 {
 // condition is true
 }
 else
 {
 // condition is false
 }

JavaScript




<script type="text/javaScript">
  // JavaScript program to illustrate If-else statement
  vari = 10;
  
  if(i < 15)
  document.write("I am in the if block");
  else
  document.write("I am Not in the if block");
</script>

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:

MethodsDescription
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




<script>
   let gfg = 'GFG ';
   let geeks = 'stands-for-GeeksforGeeks';
     
   // Print the string as it is
   document.write(gfg);
   document.write(geeks + "</br>");
     
   // concat() method
   document.write(gfg.concat(geeks) + "</br>");
     
   // match() method
   document.write(geeks.match(/eek/) + "</br>");
     
   // charAt() method
   document.write(geeks.charAt(5) + "</br>");
     
   // valueOf() method
   document.write(geeks.valueOf() + "</br>");
     
   // lastIndexOf() method
   document.write(geeks.lastIndexOf('for') + "</br>");
     
   // substr() method
   document.write(geeks.str.substr(6) + "</br>");
     
   // indexOf() method
   document.write(gfg.indexOf('G') + "</br>");
     
   // replace() method
   document.write(gfg.replace('FG', 'fg') + "</br>");
     
   // slice() method
   document.write(geeks.slice(2, 8) + "</br>");
     
   // split() method
   document.write(geeks.split('-') + "</br>");
     
   // toUpperCase method
   document.write(geeks.toUpperCase(geeks) + "</br>");
     
   // toLowerCase method
   document.write(geeks.toLowerCase(geeks) + "</br>");
</script>

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:

ModifiersDescription
[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:

MetacharactersDescription
.This is used for finding a single character, except newline or line terminator
\dThis is used to find a digit.
\sThis is used to find a whitespace character
\uxxxxThis 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:

QuantifiersDescription
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
^nThis is used for matching strings with n in the first place

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

JavaScript




<script>
  // Program to validate the email address
  functionvalidateEmail(email) {
    const re = /\[email protected]\S+\.\S+/g; // Regex pattern for email
  
    let result = re.test(email); // check if the email is valid
    if(result) {
      document.write("The email is valid.");
    } else{
      let newEmail = prompt("Enter a valid email:");
      validateEmail(newEmail);
    }
  }
  // Take input
  let email = prompt("Enter an email: ");
  validateEmail(email);
</script>

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().

MethodDescriptionSyntax
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




<!DOCTYPE html>
<html>
<body>
  <h1 style="color: green">
      JavaScript Data Transformation methods
  </h1>
  <p>
    The Array.map() method creates a new
    array from the results of calling a
    functionforevery element.
  </p>
  <p id="demo"></p>
  <h3>The filter() Method</h3>
  <p>
      Get every element inthe array 
      that has a value of 18 or more:
  </p>
  <p id="demo1"></p>
  <h3>The reduce method</h3>
  <p>
      Subtract the numbers inthe array,
      starting from the left:
  </p>
  <p id="demo2"></p>
  <script>
    const num = [16, 25];
      
    /* Using JS map() Method */
    document.getElementById("demo")
    .innerHTML = num.map(Math.sqrt);
  
    const ages = [19, 37, 16, 42];
      
    /* Using JS filter() Method */
    document.getElementById("demo1")
    .innerHTML = ages.filter(checkAdult);
  
    functioncheckAdult(age) {
      returnage >= 18;
    }
      
    /* Using JS reduce() Method */
    const numbers = [165, 84, 35];
    document.getElementById("demo2")
    .innerHTML = numbers.reduce(myFunc);
  
    functionmyFunc(total, num) {
      returntotal - num;
    }
  </script>
</body>
</html>

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:

MethodDescription
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




<script>
  // Here a date has been assigned by creating a date obj
  varDateObj = newDate("October 13, 1996 05:35:32");
  
  // getDate()
  varA = DateObj.getDate();
  
  // Printing date of the month
  document.write(A + "</br>");
  
  // getTime()
  varB = DateObj.getTime();
  
  // Printing time in milliseconds.
  document.write(B + "</br>");
  
  // getMinutes()
  varminutes = DateObj.getMinutes();
  
  // Printing minute.
  document.write(minutes + "</br>");
  
  // getFullYear()
  varC = DateObj.getFullYear();
  
  // Printing year
  document.write(C + "</br>");
  
  // getDay()
  varDay = DateObj.getDay();
  
  // Printing day of the week
  document.write("Number of Day: "+ Day + "</br>");
  
  // setDate
  dateobj.setDate(15);
  
  varD = DateObj.getDate();
  
  // Printing new date of the month
  document.write(D);
  
  // parse(), taking wrong date string as input.
  vardate = "February 48, 2018 12:30 PM";
  
  // calling parse function.
  varmsec = Date.parse(date);
  document.write(msec);
</script>

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:

MethodDescription
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




<!DOCTYPE html>
<html>
<head>
  /* CSS is used to make the output looks good */
  <style>
    #sudo {
      border: 1px solid green;
      background-color: green;
      margin-bottom: 10px;
      color: white;
      font-weight: bold;
    }
    h1,
    h2 {
      text-align: center;
      color: green;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <h1>GeeksforGeeks</h1>
  <h2>DOM appendChild() Method</h2>
  <div id="sudo">
      The Good Website is learning forComputer Science is-
  </div>
  <button onclick="geeks()">Submit</button>
  <br />
  <div style="border: 3px solid green">
    <h1>GeeksforGeeks</h1>
    <h2>A computer science portal forgeeks</h2>
  </div>
  <h2>DOM cloneNode() Method</h2>
  <button onclick="nClone()">
      Click here to clone the above elements.
  </button>
  <br />
  <h2>DOM hasAttributes() Method</h2>
  <p id="gfg">
    Click on the button to check ifthat 
    body element has any attributes
  </p>
  <button type="button"
          onclick="hasAttr()">
      Submit
  </button>
  <br />
  <h2>DOM removeChild() Method</h2>
  <p>Sorting Algorithm</p>
  <ul id="listitem">
    <li>Insertion sort</li>
    <li>Merge sort</li>
    <li>Quick sort</li>
  </ul>
  <button onclick="Geeks()">
      Click Here!
   </button>
  <br />
  <h2>DOM getAttribute() Method</h2>
  <br />
  <button id="button"onclick="getAttr()">
      Submit
   </button>
  <p id="gfg1"></p>
  <br />
  <h2>DOM getElementsByTagName()</h2>
  <p>A computer science portal forgeeks.</p>
  <button onclick="getElememt()">
      Try it
  </button>
  <h3>DOM isEqualNode() method .</h3>
  <!-- 3 div elements-->
  <div>GeeksforGeeks</div>
  <div>GfG</div>
  <div>GeeksforGeeks</div>
  <button onclick="isequal()">
      Check
  </button>
  <p id="result"></p>
  <script>
    functiongeeks() {
      varnode = document.createElement("P");
      vart = document.createTextNode("GeeksforGeeks");
      node.appendChild(t);
      document.getElementById("sudo").appendChild(node);
    }
    functionnClone() {
      // Accessing div attribute using a variable geek
      vargeek = document.getElementsByTagName("DIV")[0];
   
      // Cloning geek variable into a variable named clone
      varclone = geek.cloneNode(true);
   
      // Adding our clone variable to end of the document
      document.body.appendChild(clone);
    }
    functionhasAttr() {
      vars = document.body.hasAttributes();
      document.getElementById("gfg").innerHTML = s;
    }
   
    functionGeeks() {
      vardoc = document.getElementById("listitem");
      doc.removeChild(doc.childNodes[0]);
    }
   
    /* Using getElementById */
    functiongetAttr() {
      varrk = document.getElementById("button").getAttribute("onClick");
      document.getElementById("gfg1").innerHTML = rk;
    }
      
    /* Using getElementsByTagName */
    functiongetElement() {
      vardoc = document.getElementsByTagName("p");
      doc[0].style.background = "green";
      doc[0].style.color = "white";
    }
      
    /* Cheacking the equality */
    functionisequal() {
      varout = document.getElementById("result");
      vardivele = document.getElementsByTagName("div");
      out.innerHTML +=
        "element 1 equals element 1: "+
        divele[0].isEqualNode(divele[0]) +
        "<br/>";
      out.innerHTML +=
        "element 1 equals element 2: "+
        divele[0].isEqualNode(divele[1]) +
        "<br/>";
      out.innerHTML +=
        "element 1 equals element 3: "+
        divele[0].isEqualNode(divele[2]) +
        "<br/>";
    }
  </script>
</body>
</html>

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:

MethodDescription
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




<script type="text/javascript">
  varnum = 213;
  varnum1 = 213.3456711;
  
  // JS valueof() Method
  document.write("Output : "+ num.valueOf() + "</br>");
  
  // JS tostring() Method
  document.write("Output : "+ num.toString(2) + "</br>");
  
  // JS tofixed() Method
  document.write("Output : "+ num1.toString(2) + "</br>");
  
  // JS topricision() Method
  document.write("Output : "+ num1.toPrecision(3) + "</br>");
  
  // JS toexponential() Method
  document.write("Output : "+ num1.toExponential(4) + "</br>");
</script>

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:

MethodDescription
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




<script>
   document.getElementById("GFG").innerHTML =
       "Math.LN10: "+ Math.LN10 + "<br>"+
       "Math.LOG2E: "+ Math.LOG2E + "<br>"+
       "Math.Log10E: "+ Math.LOG10E + "<br>"+
       "Math.SQRT2: "+ Math.SQRT2 + "<br>"+
       "Math.SQRT1_2: "+ Math.SQRT1_2 + "<br>"+
       "Math.LN2: "+ Math.LN2 + "<br>"+
       "Math.E: "+ Math.E + "<br>"+
       "Math.round: "+ Math.round(5.8) + "<br>"+
       "Math.PI: "+ Math.PI + "<br>"+
       "
   <p><b>Math.sin(90 * Math.PI / 180):</b> "+
       Math.sin(90 * Math.PI / 180) + "</p>
   "+
       "
   <p><b>Math.tan(90 * Math.PI / 180):</b> "+
       Math.tan(90 * Math.PI / 180) + "</p>
   "+
       "
   <p><b>Math.max(0, 150, 30, 20, -8, -200):</b> "+
       Math.max(0, 150, 30, 20, -8, -200) + "</p>
   "+
       "
   <p><b>Math.min(0, 150, 30, 20, -8, -200):</b> "+
       Math.min(0, 150, 30, 20, -8, -200) + "</p>
   "+
       "
   <p><b>Math.pow(3,4):</b> "+ Math.pow(3, 4) + "</p>
   ";
</script>

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:

EventsDescription
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




<!DOCTYPE html>
<html>
<head>
  /* CSS is used to make the output looks good */
  <style>
    #geeks {
      border: 1px solid black;
      padding: 15px;
      width: 60%;
    }
    h1 {
      color: green;
    }
  </style>
  <script>
    functionhiThere() {
      alert("Hi there!");
    }
    functionfocused() {
      vare = document.getElementById("inp");
      if(confirm("Got it?")) {
        e.blur();
      }
    }
      
    /* Mouseover event */
    document.getElementById("hID").addEventListener("mouseover", over);
      
    /* Mouseoout event */
    document.getElementById("hID").addEventListener("mouseout", out);
      
    /* Over on green */
    functionover() {
      document.getElementById("hID").style.color = "green";
    }
      
    /* Leaving Out Black */
    functionout() {
      document.getElementById("hID").style.color = "black";
    }
  
    functionGeeks() {
      varx = document.getElementById("GFG").value;
      document.getElementById("sudo").innerHTML = "Selected Subject: "+ x;
    }
  
    /* Success alert */
    functionGeek() {
      alert("Form submitted successfully.");
    }
    functionFunction() {
      document.getElementById("geeks").style.fontSize = "30px";
      document.getElementById("geeks").style.color = "green";
    }
  </script>
</head>
<body>
  <!-- onload event -->
  <img onload="alert('Image completely loaded')"
       alt="GFG-Logo"
       src=
  <br />
      
  <!-- onclick event -->
  <h2>onclick event</h2>
  <button type="button"onclick="hiThere()"on>
      Click me
  </button>
    
  <!-- onfocus event -->
  <h2>onfocus event</h2>
  <p>Take the focus into the input box below:</p>
  <input id="inp"onfocus="focused()"/>
  
  <!-- onblur Event -->
  <h2>onblur event</h2>
  <p>
    Write something inthe input box and 
    then click elsewhere inthe document
    body.
  </p>
  <input onblur="alert(this.value)"/>
  
  <!-- onmouseover and onmouseout event -->
  <h2 id="hID">onmouseover event</h2>
  <h2>onchange Event</h2>
  <p>Choose Subject:</p>
  <select id="GFG"onchange="Geeks()">
    <option value="Data Structure">
        Data Structure
     </option>
    <option value="Algorithm">
        Algorithm
     </option>
    <option value="Computer Network">
        Computer Network
     </option>
    <option value="Operating System">
        Operating System
     </option>
    <option value="HTML">
        HTML
    </option>
  </select>
  
  <p id="sudo"></p>
    
  <!-- onsubmit event -->
  <h2>onsubmit event</h2>
  <form onsubmit="Geek()">
    First Name:<input type="text"value=""/>
    <br />
    Last Name:<input type="text"value=""/>
    <br />
    <input type="submit"value="Submit"/>
  </form>
    
  <!--ondrag event -->
  <h2>ondrag event attribute</h2>
  <div id="geeks"ondrag="Function()">
    GeeksforGeeks: A computer science portal forgeeks
  </div>
</body>
</html>

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:

StatementDescription
tryThis statement lets you test a block of code to check for errors.
catchThis statement lets you handle the error if any are present.
throwThis statement lets you make your own errors.
finallyThis statement lets you execute code, after try and catch.

JavaScript




<!DOCTYPE html>
<html>
<body>
  <h2>
      JavaScript throwtrycatchfinally keywords
  </h2>
  <p>Please enter a number:</p>
  <input id="demo"type="text"/>
  <button type="button"onclick="myFunction()">
      Test Input
  </button>
  <p id="p01"></p>
  <script>
    functionmyFunction() {
      const message = document.getElementById("p01");
      message.innerHTML = "";
      let x = document.getElementById("demo").value;
  
      /* Using try.. catch.. with conditions*/
      try{
        if(x == "") throw"is empty";
        if(isNaN(x)) throw"is not a number";
        x = Number(x);
        if(x > 20) throw"is too high";
        if(x <= 20) throw"is too low";
      } catch(err) {
        message.innerHTML = "Input "+ err;
      } finally {
        document.getElementById("demo").value = "";
      }
    }
  </script>
</body>
</html>

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:

PropertyDescription
windowIt returns the current window or frame.
screenReturns the window’s Screen object.
toolbarIt will result the toolbar object, whose visibility can be toggled in the window.
NavigatorReturns the window’s Navigator object.
frames[]Returns all <iframe> elements in the current window.
documentIt returns a reference to the document object of that window
closedIt holds a Boolean value that represents whether the window is closed or not.
lengthIt represents the number of frames in the current window.
HistoryProvides the window’s History object.

JavaScript




<!DOCTYPE html>
<html>
<body>
  <h1>The Window properties</h1>
  <h2>The origin Property</h2>
  
  <p id="demo"></p>
  <br />
  <button type="button"onclick="getResolution();">
      Get Resolution
     </button>
  <br />
  <button type="button"onclick="checkConnectionStatus();">
    Check Connection Status
  </button>
  <br />
  <button type="button"onclick="getViews();">
      Get Views Count</button>
  <br />
  <p>
     <button onclick="closeWin()">
      Close "myWindow"
     </button>
  </p>
  
  <script>
    // JS location property
    let origin = window.location.origin;
    document.getElementById("demo").innerHTML = origin;
  
    // JS screen property
    functiongetResolution() {
      alert("Your screen is: "+ screen.width + "x"+ screen.height);
    }
  
    // JS toolbar property
    varvisible = window.toolbar.visible;
  
    // JS navigator property
    functioncheckConnectionStatus() {
      if(navigator.onLine) {
        alert("Application is online.");
      } else{
        alert("Application is offline.");
      }
    }
    // JS history property
    functiongetViews() {
      alert(
        "You've accessed "+ history.length + " web pages in this session."
      );
    }
    // JS close property
    let myWindow;
    functioncloseWin() {
      if(myWindow) {
        myWindow.close();
      }
    }
  </script>
</body>
</html>
MethodDescription
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




<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Window Methods</title>
  /* CSS is used to make the output looks good */
  <style>
    .gfg {
      font-size: 36px;
    }
    form {
      float: right;
      margin-left: 20px;
    }
  </style>
</head>
<body>
  <div class="gfg">JavaScript Window Methods</div>
  <br />
  <button onclick="windowOpen()">
      JavaScript window Open
  </button>
  <button onclick="resizeWin()">
      JavaScript window resizeTo
  </button>
  <button onclick="windowBlur()">
      JavaScript window Blur
  </button>
  <button onclick="windowFocus()">
      JavaScript window Focus
  </button>
  <button onclick="windowClose()">
      JavaScript window Close
  </button>
  <br />
  <br />
  <p id="g"></p>
  <form>
    <button onclick="setTimeout(wlcm, 2000);">
        Alert after 2 Second
    </button>
    <button onclick="geek()">Click me!</button>
    <input type="button" 
           value="Print" 
           onclick="window.print()"/>
  </form>
  <br /><br />
  <button id="btn" 
          onclick="fun()" 
          style="color: green">
    JavaScript Used setTimeOut
  </button>
  <button id="btn"onclick="stop()">
      JavaScript clearTimeout
  </button>
  <script>
    vargfgWindow;
      
    // Function that open the new Window
    functionwindowOpen() {
      gfgWindow = window.open(
        "https://a-arich.com",
        "_blank",
        "width=200, height=200"
      );
    }
      
    // Function that Resize the open Window
    functionresizeWin() {
      gfgWindow.resizeTo(400, 400);
      gfgWindow.focus();
    }
      
    // Function that Closes the open Window
    functionwindowClose() {
      gfgWindow.close();
    }
      
    // Function that blur the open Window
    functionwindowBlur() {
      gfgWindow.blur();
    }
      
    // Function that focus on open Window
    functionwindowFocus() {
      gfgWindow.focus();
    }
      
    // Alert function
    functionwlcm() {
      alert("Welcome to GeeksforGeeks");
    }
      
    // Prompt fucntion
    functiongeek() {
      vardoc = prompt("Please enter some text", "GeeksforGeeks");
      if(doc != null) {
        document.getElementById("g").innerHTML = "Welcome to "+ doc;
      }
    }
      
    // Fucntion setTimeout and clearTimeout
    vart;
    functioncolor() {
      if(document.getElementById("btn").style.color == "blue") {
        document.getElementById("btn").style.color = "green";
      } else{
        document.getElementById("btn").style.color = "blue";
      }
    }
    functionfun() {
      t = setTimeout(color, 3000);
    }
    functionstop() {
      clearTimeout(t);
    }
  </script>
</body>
</html>

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.


My Personal Notesarrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!