Category: Useful Resources

  • Built in Functions 

    Here, you can find all the JavaScript’s built-in methods on the following classes:

    • Number Methods
    • Boolean Methods
    • String Methods
    • String HTML Wrappers
    • Array Methods
    • Date Methods
    • Date Static Methods
    • Math Methods
    • RegExp Methods
    JS Built-in Functions Reference

    Number Methods

    The Number object contains only the default methods that are part of every object’s definition.

    Sr.No.Method & Description
    1constructor()Returns the function that created this object’s instance. By default this is the Number object.
    2toExponential()Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation.
    3toFixed()Formats a number with a specific number of digits to the right of the decimal.
    4toLocaleString()Returns a string value version of the current number in a format that may vary according to a browser’s locale settings.
    5toPrecision()Defines how many total digits (including digits to the left and right of the decimal) to display of a number.
    6toString()Returns the string representation of the number’s value.
    7valueOf()Returns the number’s value.

    Boolean Methods

    Here is a list of each method and its description.

    Sr.No.Method & Description
    1toSource()Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object.
    2toString()Returns a string of either “true” or “false” depending upon the value of the object.
    3valueOf()Returns the primitive value of the Boolean object.

    String Methods

    Here is a list of each method and its description.

    Sr.No.Method & Description
    1charAt()Returns the character at the specified index.
    2charCodeAt()Returns a number indicating the Unicode value of the character at the given index.
    3concat()Combines the text of two strings and returns a new string.
    4indexOf()Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
    5lastIndexOf()Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
    6localeCompare()Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
    7length()Returns the length of the string.
    8match()Used to match a regular expression against a string.
    9replace()Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
    10search()Executes the search for a match between a regular expression and a specified string.
    11slice()Extracts a section of a string and returns a new string.
    12split()Splits a String object into an array of strings by separating the string into substrings.
    13substr()Returns the characters in a string beginning at the specified location through the specified number of characters.
    14substring()Returns the characters in a string between two indexes into the string.
    15toLocaleLowerCase()The characters within a string are converted to lower case while respecting the current locale.
    16toLocaleUpperCase()The characters within a string are converted to upper case while respecting the current locale.
    17toLowerCase()Returns the calling string value converted to lower case.
    18toString()Returns a string representing the specified object.
    19toUpperCase()Returns the calling string value converted to uppercase.
    20valueOf()Returns the primitive value of the specified object.

    String HTML Wrappers

    Here is a list of each method which returns a copy of the string wrapped inside the appropriate HTML tag.

    Sr.No.Method & Description
    1anchor()Creates an HTML anchor that is used as a hypertext target.
    2big()Creates a string to be displayed in a big font as if it were in a <big> tag.
    3blink()Creates a string to blink as if it were in a <blink> tag.
    4bold()Creates a string to be displayed as bold as if it were in a <b> tag.
    5fixed()Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag
    6fontcolor()Causes a string to be displayed in the specified color as if it were in a <font color=”color”> tag.
    7fontsize()Causes a string to be displayed in the specified font size as if it were in a <font size=”size”> tag.
    8italics()Causes a string to be italic, as if it were in an <i> tag.
    9link()Creates an HTML hypertext link that requests another URL.
    10small()Causes a string to be displayed in a small font, as if it were in a <small> tag.
    11strike()Causes a string to be displayed as struck-out text, as if it were in a <strike> tag.
    12sub()Causes a string to be displayed as a subscript, as if it were in a <sub> tag
    13sup()Causes a string to be displayed as a superscript, as if it were in a <sup> tag

    Array Methods

    Here is a list of each method and its description.

    Sr.No.Method & Description
    1concat()Returns a new array comprised of this array joined with other array(s) and/or value(s).
    2every()Returns true if every element in this array satisfies the provided testing function.
    3filter()Creates a new array with all of the elements of this array for which the provided filtering function returns true.
    4forEach()Calls a function for each element in the array.
    5indexOf()Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
    6join()Joins all elements of an array into a string.
    7lastIndexOf()Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
    8map()Creates a new array with the results of calling a provided function on every element in this array.
    9pop()Removes the last element from an array and returns that element.
    10push()Adds one or more elements to the end of an array and returns the new length of the array.
    11reduce()Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
    12reduceRight()Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
    13reverse()Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first.
    14shift()Removes the first element from an array and returns that element.
    15slice()Extracts a section of an array and returns a new array.
    16some()Returns true if at least one element in this array satisfies the provided testing function.
    17toSource()Represents the source code of an object
    18sort()Sorts the elements of an array.
    19splice()Adds and/or removes elements from an array.
    20toString()Returns a string representing the array and its elements.
    21unshift()Adds one or more elements to the front of an array and returns the new length of the array.

    Date Methods

    Here is a list of each method and its description.

    Sr.No.Method & Description
    1Date()Returns today’s date and time
    2getDate()Returns the day of the month for the specified date according to local time.
    3getDay()Returns the day of the week for the specified date according to local time.
    4getFullYear()Returns the year of the specified date according to local time.
    5getHours()Returns the hour in the specified date according to local time.
    6getMilliseconds()Returns the milliseconds in the specified date according to local time.
    7getMinutes()Returns the minutes in the specified date according to local time.
    8getMonth()Returns the month in the specified date according to local time.
    9getSeconds()Returns the seconds in the specified date according to local time.
    10getTime()Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.
    11getTimezoneOffset()Returns the time-zone offset in minutes for the current locale.
    12getUTCDate()Returns the day (date) of the month in the specified date according to universal time.
    13getUTCDay()Returns the day of the week in the specified date according to universal time.
    14getUTCFullYear()Returns the year in the specified date according to universal time.
    15getUTCHours()Returns the hours in the specified date according to universal time.
    16getUTCMilliseconds()Returns the milliseconds in the specified date according to universal time.
    17getUTCMinutes()Returns the minutes in the specified date according to universal time.
    18getUTCMonth()Returns the month in the specified date according to universal time.
    19getUTCSeconds()Returns the seconds in the specified date according to universal time.
    20getYear()Deprecated – Returns the year in the specified date according to local time. Use getFullYear instead.
    21setDate()Sets the day of the month for a specified date according to local time.
    22setFullYear()Sets the full year for a specified date according to local time.
    23setHours()Sets the hours for a specified date according to local time.
    24setMilliseconds()Sets the milliseconds for a specified date according to local time.
    25setMinutes()Sets the minutes for a specified date according to local time.
    26setMonth()Sets the month for a specified date according to local time.
    27setSeconds()Sets the seconds for a specified date according to local time.
    28setTime()Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.
    29setUTCDate()Sets the day of the month for a specified date according to universal time.
    30setUTCFullYear()Sets the full year for a specified date according to universal time.
    31setUTCHours()Sets the hour for a specified date according to universal time.
    32setUTCMilliseconds()Sets the milliseconds for a specified date according to universal time.
    33setUTCMinutes()Sets the minutes for a specified date according to universal time.
    34setUTCMonth()Sets the month for a specified date according to universal time.
    35setUTCSeconds()Sets the seconds for a specified date according to universal time.
    36setYear()Deprecated – Sets the year for a specified date according to local time. Use setFullYear instead.
    37toDateString()Returns the “date” portion of the Date as a human-readable string.
    38toGMTString()Deprecated – Converts a date to a string, using the Internet GMT conventions. Use toUTCString instead.
    39toLocaleDateString()Returns the “date” portion of the Date as a string, using the current locale’s conventions.
    40toLocaleFormat()Converts a date to a string, using a format string.
    41toLocaleString()Converts a date to a string, using the current locale’s conventions.
    42toLocaleTimeString()Returns the “time” portion of the Date as a string, using the current locale’s conventions.
    43toSource()Returns a string representing the source for an equivalent Date object; you can use this value to create a new object.
    44toString()Returns a string representing the specified Date object.
    45toTimeString()Returns the “time” portion of the Date as a human-readable string.
    46toUTCString()Converts a date to a string, using the universal time convention.
    47valueOf()Returns the primitive value of a Date object.

    Date Static Methods

    In addition to the many instance methods listed previously, the Date object also defines two static methods. These methods are invoked through the Date( ) constructor itself −

    Sr.No.Method & Description
    1Date.parse( )Parses a string representation of a date and time and returns the internal millisecond representation of that date.
    2Date.UTC( )Returns the millisecond representation of the specified UTC date and time.

    Math Methods

    Here is a list of each method and its description.

    Sr.No.Method & Description
    1abs()Returns the absolute value of a number.
    2acos()Returns the arccosine (in radians) of a number.
    3asin()Returns the arcsine (in radians) of a number.
    4atan()Returns the arctangent (in radians) of a number.
    5atan2()Returns the arctangent of the quotient of its arguments.
    6ceil()Returns the smallest integer greater than or equal to a number.
    7cos()Returns the cosine of a number.
    8exp()Returns EN, where N is the argument, and E is Euler’s constant, the base of the natural logarithm.
    9floor()Returns the largest integer less than or equal to a number.
    10log()Returns the natural logarithm (base E) of a number.
    11max()Returns the largest of zero or more numbers.
    12min()Returns the smallest of zero or more numbers.
    13pow()Returns base to the exponent power, that is, base exponent.
    14random()Returns a pseudo-random number between 0 and 1.
    15round()Returns the value of a number rounded to the nearest integer.
    16sin()Returns the sine of a number.
    17sqrt()Returns the square root of a number.
    18tan()Returns the tangent of a number.
    19toSource()Returns the string “Math”.

    RegExp Methods

    Here is a list of each method and its description.

    Sr.No.Method & Description
    1exec()Executes a search for a match in its string parameter.
    2test()Tests for a match in its string parameter.
    3toSource()Returns an object literal representing the specified object; you can use this value to create a new object.
    4toString()Returns a string representing the specified object.

  • Cheatsheet

    Write On-page JavaScript

    To add on-page JavaScript in an HTML document, use the following script tag −

    <script type="text/javascript">// Write your JavaScript code here</script>

    Insert an External JavaScript file

    You can insert an external JavaScript file in an HTML document using the HTML’s <script> tag by specifying the file path with the src attribute.

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

    Printing/Output

    JavaScript provides three ways to print anything on the screen.

    • Console Output
    • Alert Boxes
    • Document Write

    Console Output (console.log())

    The console.log() prints on the web console. It is used for debugging and logging purposes.

    console.log("Hello, World!");

    Alert Boxes

    JavaScript alert() method displays a pop-up alert box on the browser with a specified message such as text, values of the variables, etc.,

    alert("Hello World!");var x =10;alert("Value of x is :"+ x);

    document.write()

    The document.write() method to write content directly to the HTML document.

    document.write("Hello World!");var x =10;
    document.write("Value of x is :", x);

    Variables

    JavaScript variables can be declared using the varlet, or const keywords.

    • var − Declares function-scoped variables and these can be reassigned.
    • let − Declares block-scoped variables and these can be reassigned.
    • const − Declares constants and their values cannot be reassigned.
    var x =5;let y =10;const z =15;

    Data Types

    JavaScript data types can be categorized into the following two categories −

    1. Primitive Types

    The primitive data types are: StringNumberBooleanUndefinedNullSymbolBigInt

    2. Objects Types

    The objects data types are: {}arrays []functions () => {}

    let str ="Kelly Hu";let num =123;let bool =true;let und =undefined;let n =null;

    Operators

    The following are the JavaScript operators −

    Arithmetic Operators

    The arithmetic operators are: +, -, *, /, %, ++, —

    let a =10;let b =3;
    console.log("a =", a,", b =", b);// Addition (+)let sum = a + b;
    console.log("a + b =", sum);// Subtraction (-)let difference = a - b;
    console.log("a - b =", difference);// Multiplication (*)let product = a * b;
    console.log("a * b =", product);// Division (/)let quotient = a / b;
    console.log("a / b =", quotient);// Modulus (remainder) (%)let remainder = a % b;
    console.log("a % b =", remainder);// Increment (++)
    a++;
    console.log("After a++:", a);// Decrement (--)
    b--;
    console.log("After b--:", b);

    Assignment Operators

    The assignment operators are: =, +=, -=, *=, /=

    let x =10;
    console.log("x:", x);
    x =5;
    console.log("x:", x);
    x +=3;
    console.log("x:", x);
    x -=2;
    console.log("x:", x);
    x *=4;
    console.log("x:", x);
    x /=6;
    console.log("x:", x);
    x %=3;
    console.log("x:", x);

    Comparison Operators

    The comparison operators are: ==, ===, !=, !==, >, =,

    let x =5;let y ="5";let z =10;
    
    console.log(x == y); 
    console.log(x === y);
    console.log(x != z);
    console.log(x !== y);
    console.log(z > x);
    console.log(x < z);
    console.log(z >=10);
    console.log(x <=5);

    Logical Operators

    The logical operators are: && (AND), || (OR), and ! (NOT)

    let a =true;let b =false;let c =5;let d =10;
    
    console.log(a && c < d);
    console.log(b && c < d);
    console.log(a || b);
    console.log(b || d < c);
    console.log(!a);
    console.log(!b);

    Conditional Statements

    JavaScript conditional statements contain different types of if-else statements and ternary operators.

    If else statements

    The syntax of if-else statements are −

    if(condition){// block of code}elseif(condition){// block of code}else{// block of code}

    Below is an example of if-else statements −

    let age =20;if(age <18){
       console.log("You are a minor.");}elseif(age >=18&& age <65){
       console.log("You are an adult.");}else{
       console.log("You are a senior citizen.");}

    Ternary Operator

    The ternary operator is a replacement for a simple if else statement. Below is the syntax of the ternary operator −

    let result = condition ?'value1':'value2';

    An example of a ternary operator is as follows −

    let age =20;let message = age <18?"You are a minor.": age >=18&& age <65?"You are an adult.":"You are a senior citizen.";
    
    console.log(message);

    Loops

    JavaScript loops are −

    • The for Loop
    • The while Loop
    • The do-while Loop

    The for Loop

    The for loop is an entry control loop.

    for(let i =0; i <5; i++){
       console.log(i);}

    The while Loop

    The while loop is also an entry control loop where the condition is checked before executing the loop’s body.

    let i =0;while(i <5){
       console.log(i);
       i++;}

    The do-while loop is an exit control loop, where the condition is checked after executing the loop’s body.

    let i=0;do{
       console.log(i);
       i++;}while(i <5);

    Functions

    JavaScript functions are the code blocks to perform specific tasks.

    User-defined Function

    Here is an example of a function to add two numbers −

    // Function DeclarationfunctionaddNumbers(a, b){return a + b;// Return the sum of a and b}// Example usagelet sum =addNumbers(5,10);
    console.log("The sum is:", sum);// The sum is: 15

    Function Expression

    The function expression is as follows −

    constmultiply=function(a, b){return a * b;}

    Arrow Function

    JavaScript arrow function is used to write function expressions.

    Below is a simple statement to create an arrow function −

    constdivide=(a, b)=> a / b;

    Example of an arrow function to add two numbers −

    // Arrow functionconstaddNumbers=(a, b)=> a + b;// Callinglet sum =addNumbers(5,10);
    console.log("The sum is:", sum);

    Objects

    JavaScript objects are collections of key-value pairs and are used to store different types of data, including other objects, functions, arrays, and primitive values.

    Here is an example to create an object in JS −

    const person ={
       name:"Kelly Hu",
       age:27,display:function(){
    
      console.log("Hello, "+this.name);}};
    console.log(person.name);// Access property person.display();// Call method

    Arrays

    JavaScript arrays store multiple values of any type in a single variable.

    Array Declaration

    Syntax to declare an array is −

    let array_name =[value1, value2, value3,];

    Array Example

    The following is an example of creating an array of integers.

    let arr =[10,20,30,40,50];// Printing array
    console.log("arr:", arr);

    Array Methods

    Commonly used array methods are −

    • push() − It is used to add one or more elements in an array.
    • pop() − It is used to remove the last element and returns the deleted element.
    • shift() − It is used to remove the first element and return the delete element.
    • unshift() − It is used to add one or more elements at the beginning of an array.
    • concat() − It is used to add one or more arrays and returns a new array.
    • join() − It is used to join all elements of an array into a string.

    Below is an example demonstrating all the above methods −

    // Initialize the original arraylet students =["Kelly Hu","Peter","John"];// push()
    students.push("Bobby","Catty");
    console.log(students);// pop()
    console.log("Removed :", students.pop());// shift()
    console.log("Removed :", students.shift());// unshift()
    students.unshift("Julia","Halle");
    console.log(students);// concat()const newNames =["Emma","Reese"];const newArray = students.concat(newNames);
    console.log("After concat:", newArray);// join()const str = students.join(", ");
    console.log("Joined string:", str);

    Loop through Array Elements

    You can loop through all array elements using the forEach() method −

    var arr =[10,20,30,40,50]
    arr.forEach((item)=> console.log(item));

    DOM Manipulation

    JavaScript DOM manipulation allows you to manipulate the content and structure of web pages dynamically.

    let element = document.getElementById('myElement');
    element.innerHTML ='New Content';// Change content
    element.style.color ='red';// Change style
    document.querySelector('.class');// Select by class

    Event Listeners

    JavaScript event listeners are allowed to execute code in response to various user actions, such as clicks, key presses, mouse movements, and more.

    Below is an example of button click event −

    element.addEventListener('click',function(){alert('Clicked!');});

    Promises

    JavaScript promises represent the values that may be available now, or in the future, or never.

    // Promiseslet promise =newPromise((resolve, reject)=>{// asynchronous codeif(success)resolve('Success');elsereject('Error');});
    
    promise.then(result=> console.log(result)).catch(err=> console.log(err));

    Async/Await

    JavaScript Async/Await works with asynchronous operations.

    The following is an example of Async/Await −

    asyncfunctionfetchData(){try{let response =awaitfetch('url');let data =await response.json();
    
      console.log(data);}catch(error){
      console.log(error);}}</pre>

    Error Handling

    JavaScript error handling allows you to handle errors/exceptions that occur during runtime. The try, catch, and finally blocks are used to handle exceptions.

    Syntax of error handling is −

    try{// Code that may throw an error}catch(error){
       console.log(error.message);// Handle the error}finally{
       console.log("Finally block executed");}

    The following is a simple example demonstrating the use of try, catch, and finally in JavaScript −

    functiondivideNumbers(num1, num2){try{if(num2 ===0){thrownewError("Cannot divide by zero!");}const result = num1 / num2;
    
      console.log(Result: ${result});}catch(error){
      console.error("Error:", error.message);}finally{
      console.log("Execution completed.");}}// Calling divideNumbers(10,2);divideNumbers(10,0);</pre>

  • Questions and Answers

    Javascript Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations.

    Questions and Answers
    Sr.No.Question/Answers Type
    1JavaScript ExamplesThese JavaScript examples are organized by topics and arranged from easy to difficult questions. Solving questions based on these topics will help improve your JavaScript problem-solving capabilities.
    2JavaScript Interview QuestionsThis section provides a huge collection of Javascript Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer.
    3JavaScript Online QuizThis section provides a great collection of Javascript Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red.
    4JavaScript Online TestIf you are preparing to appear for a Java and Javascript Framework related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test.
    5JavaScript Mock TestThis section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself.