Download JavaScript Cheat Sheet PDF for Quick Guide in 2024

Posted in /   /  

Download JavaScript Cheat Sheet PDF for Quick Guide in 2024
vinaykhatri

Vinay Khatri
Last updated on November 21, 2024

    JavaScript is the most powerful tool for front-end development. Nonetheless, with continuous updates and frameworks (and NodeJS ) added to the roster, JS can also be used for the backend.

    This JavaScript cheat sheet tries to cover all the basics of JS. We have also provided the code snippets pertaining to different JS concepts, which you can use if you get confused with the syntax. Moreover, this JavaScript cheat sheet aims to serve as the perfect reference for your JS learning.

    JavaScript Cheat Sheet

    Let's start this JavaScript cheat sheet with how we can include JavaScript in an HTML file. There are 2 ways of doing so:

    1. Internal Including of Java Script

    In this, we write the JavaScript code in the HTML pages itself inside the <script> tag.

    Example

    <script type="text/javascript">
    // Code here     
       </script>

    2. External Including of JavaScript

    In this method, we create a JavaScript document with an extension of .js and include it in the HTML page.

    Example

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

    Comments in JavaScript

    Comments are used to provide additional information about the code. In JS we use // to add a single line as a comment and /* to add multiple lines as a comment.

    Example:

    Single line comments - // single line comment
    Multi-line comments - /* Multi line comment*/

    Java Script Variable

    In JS, we have 3 keywords that we can use to declare a variable:

    Variable Description Code Snippet
    var var keyword is used to assign a variable. As JavaScript is a dynamic language so we do not need to specify the specific data type. var num_1 = 10;
    const This keyword is used to assign a variable. Once we assign a variable with const we cannot modify its value. const num_2 = 20;
    let It is similar to const, but a let variable can be reassigned though it can't be re-declared. let num_2 = 30;

    Data Types in JavaScript

    Data type Code Snippet
    Number var x = 100;
    String var x = "100";
    Boolean var x =true;
    null var x = null;
    Object
    var x = { name:  "Sam",
    age:  "29"
    }

    Array in JavaScript

    var arr = [1,2,3,4,5,6]

    Array Methods

    Methods Description
    concat() Merges arrays to make a single array.
    indexOf() To get the index of a value.
    join() Combines all the elements of an array to make it a string.
    lastIndexOf() Gives the last position of the array.
    pop() Removes the last element from an array.
    push() Adds a new element at the end of an array.
    reverse() Reverses the array elements.
    shift() Removes the first element of the array.
    slice() Creates a new sequence of an array from the existing one.
    sort() Sorts the elements of the array.
    splice() Adds elements in a specified way and position.
    toString() Converts elements to string.
    unshift() Adds an element at the beginning of an array.
    valueOf() Returns the position of the element.

    Operators in JavaScript

    In JS we have many types of operators, namely arithmetic, conditional, logical, and bitwise operators. We use operators to perform a specific task, and the operators always need operands to work.

    Arithmetic Operators

    Operators Operator Name Code snippet
    + Addition 1 + 2 //3
    - Subtraction 2 – 1 //1
    * Multiplication 2*2   //2
    / Division 4/2  //2
    % Modules or remainder 10%2  //0
    ++ Increment
    x=2;
    x++  //3
    -- decrement
    x=2;
    3-- //2

    Comparison: It returns a true or false value.

    Operators Operator Name
    == Equal to
    === Equal value and data type
    != Not equal
    !== Not equal value and data type
    > Greater than
    < Less than
    >= Greater than and equal to
    <= Less than and equal to
    ? Ternary Operator

    Logical Operator: It operates on a Boolean value.

    Operators Operator Name
    && And
    || Or
    ! Not

    Bitwise Operator:

    Operators Operator Name
    & AND statement
    | OR statement
    ~ Not
    ^ XOR
    << Left shift
    >> Right Shift
    >>> Zero fill right shift

    Function

    Functions are used to perform a specific task.

    User-defined functions in JavaScript:

    function function_name (parameters)
    {
    //function task
    }

    Show Output on the Screen

    In JS, we have some inbuilt functions to display output i.e. print something on the screen.

    Output Function Description Code Snippet
    alert() An alert box shows a box. alert("Hello world")
    confirm() It is similar to alert but it returns value in the form of true or false. confirm("Are you 18+")
    console.log() It is used to write information on the browser console. console.log("Hello world")
    document.write() It can write in the HTML document. document.write("Hello world")
    prompt() It is used to take data from the user. prompt("Enter Your name")

    JavaScript Global Functions

    Global Functions Description
    decodeURI() Decodes a Uniform Resource Identifier (URI).
    decodeURIComponent() Decodes a URI component.
    endodeURI() Encodes a URI into UTF-8.
    encodeURIComponent() Encodes URI components.
    eval() Evaluates the code present in the string format.
    isFinite() Checks whether the value is finite or not.
    isNaN() Evaluates whether the value is NaN or not.
    Number() Converts the string into a number.
    parseFloat() Parses the value and returns a floating-point number.
    parseInt() Parses the value and returns an integer.

    Loops in JavaScript

    Loop is used to iterate over a block of statements again and again until a certain condition is fulfilled.

    In JS, we have 3 types of statements that can loop over a statement:

    Loop Description Code Snippet
    for We use for loop when we are certain about how many times we are going to iterate over a block of code. for( var i=0; i<10; i++) { console.log(i); }
    while When we are not certain about the number of iterations, we use the while loop. while(i<10) { console.log(i); i++; }
    do while Even if the condition is false, the do while loop will execute at least 1 time. do { console.log(i) i++; }while(i<10)

    break: It is a keyword we use in a loop to stop and exit the cycle of the loop.

    continue: Continue is used to skip a cycle of the loop.

    JavaScript If…Else:

     if (condition)
    {
        //code executed if the statement is true.
    }
    else
    {
        //executes this code if the condition is false.
    }

    Twists

    A string is a collection of characters inside the double or single inverted commas.

    var string = "This is a string"
    Escape Characters = \

    String Methods

    Methods Description
    charAt() Returns the position of the character inside a string.
    charCodeAt() Provides the Unicode of the character.
    Concat() Joins two or more strings into one.
    fromCharCode() Returns a string created from the specified sequence of UTF-16 code units.
    indexOf() Returns the position of the character.
    lastIndexOf() Provides the last index of the character if there is more than one same character in the string.
    match() Retrieves the matches of a string against a search pattern.
    replace() Replaces a text with another.
    search() Returns the position of a text in a string.
    slice() Extracts a sequence of string.
    split() Splits the string into an array.
    substr() Extracts a sequence of string depending on a specified number of characters.
    substring() Similar to slice() but does not work with -ve indices
    toLoweCase() Converts the string to lowercase.
    toUpperCase() Converts the strings to uppercase.
    valueOf() Returns the primitive value of a string object.

    Regular Expression

    Pattern Modifier Name
    e Evaluate Replacement
    i Case-insensitive matching
    g Global matching
    m Multiple line matching
    s Treat string as a single line
    x Allow comments and whitespace in the pattern.
    u Ungreedy pattern

    Brackets Description
    [abc] Finds any characters from a, b and c.
    [^abc] Searches any character except a, b and c.
    [0-9] Finds any digit from 0 to 9.
    [A-z] Finds any character from a to z and A to Z.
    (a | b | c) Searches any of the alternatives separated with |.

    Math and Numbers

    NaN = Not A Number
    Number Methods Description
    toExponential() Returns a string with a rounded number written as an exponential notation.
    toFixed() Returns the string of a number with a specified number of decimals.
    toPrecision() A string of a number written with a specified length.
    toString() Returns a number as a string.

    Math Methods Description
    abs(n) Returns a positive value of n.
    acos(n) Arccosine of n in radians.
    asin(n) Arcsine of n in radians.
    atan(n) The arctangent of n in numeric value.
    ceil(n) The rounded-up value of n.
    cos(n) Cosine of n.
    exp(n) Ex of n.
    floor(n) Rounded down value of n.
    log(n) The natural logarithm of n.
    max(1,2,3,5,12,42) Returns the maximum value.
    min(1,2,3,5,12,42) Returns the minimum value.
    pow(n,m) n to the power m.
    random() Returns a random value between 1 and 0.
    sin(n) The sine of x in radians.
    sqrt(n) The square root of n.
    tan(n) The tangent of angle n.

    Dates in JS

    Date()= Returns the current date in the form of a new date object.

    Date Declaration

    Date(yyyy,mm,dd,HH,MM,SS,MS): to create a new date object.

    yyyy = year
    mm = month
    dd = day
    HH = Hours
    MM = Minutes
    SS = seconds
    MS = Milliseconds
    Date("2019-11-29") = Date declaration as a string
    Date("2019");
    Date("2019-06-23T12:00:00-09:45");
    Date("June 23 2019");
    Date("Jun 23 2019 07:45:00 GMT+0100 (Tokyo Time)");

    Date Methods

    Get Date Methods Description
    getDate() Get the date from the date object.
    getDay() Get the weekday.
    getFullYear() Get the year.
    getHours() Get the hour(0-23).
    getMilliseconds() Get the millisecond.
    getMinutes() Get the minutes.
    getSeconds() Get the second.
    getTime() Get the milliseconds since January 1, 1970.
    getUTCDate() The day (date) of the month in the specified date according to the universal time (also available for day, month, fullyear, hours, minutes etc.).
    getMonth() Get the month(0-11).

    Set Date Methods Description
    setDate() Sets the date.
    setFullYear() Sets the year.
    setHours Sets hours.
    setMilliseconds Sets milliseconds.
    setMinutes Sets minutes.
    setMonths() Sets months.
    setSeconds() Sets seconds.
    setTime() Sets the time.
    setUTCDate() Sets the day of the month for a specified date according to the universal time (also available for day, month, fullyear, hours, minutes etc.).

    DOM in JavaScript

    Node Methods Description
    appendChid() Adds a new child node to an element as the last child node.
    cloneNode() Clones the HTML element.
    compareDocumentPosition() Compares the document position of two elements.
    getFeature() Returns an object that implements the API of a specified feature.
    hasAttributes() True if element has attributes else it return false.
    hasChildNode() Returns true if an element has any child nodes, otherwise false.
    insertBefore() Inserts a new child node before a specified existing child node.
    isDefaultNamespace() True for default specified namespaceURI else false.
    removeChild() Removes a child node from an element.
    replaceChild() Replaces a child node in an element.

    Elements Methods Description
    getAttribute() Returns the attribute value.
    getAttributeNS() Returns the string value of the attribute with namespace.
    getAttributeNode() Gets the specific attribute node.
    getAttributeNodeNS() Returns the attribute node for the attribute with the given namespace.
    getElementsByTagName() Gets all the elements with a specific tag name.
    getElemetsByTagNameNS() Returns a live HTMLCollection of elements with a certain tag name belonging to the given namespace.
    setAttribute() Sets or changes the specified attribute to a specified value.
    setAttributeNS() Adds a new attribute or changes the value of an attribute with the given namespace and name.
    setAttributeNode() Sets or changes the specified attribute node.
    setAttributeNodeNS() Adds a new namespaced attribute node to an element.

    JavaScript Events

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

    Keyboard

    • onkeydown
    • onkeypress
    • onkeyup

    Form

    • onblur
    • onchange
    • onfocus
    • onfocusin
    • onfocusout
    • oninput
    • oninvalid
    • onrest
    • onsearch
    • onselect
    • onsubmit

    Drag

    • ondrag
    • ondragend
    • ondragenter
    • ondragleave
    • ondragover
    • ondragstart
    • ondrop

    Media

    • onabort
    • oncanplay
    • oncanplaythrough
    • ondurationchange
    • onended
    • onerror
    • onloadeddata
    • onloadedmetadata
    • onloadstart
    • onpause
    • onplay
    • onplaying
    • onprogress
    • onratechange
    • onseeked
    • onseeking
    • onstalled
    • onsuspend
    • ontimeupdate
    • onvolumechange
    • onwaiting

    Conclusion

    With this JavaScript cheat sheet, we tried to cover all the basics of the popular web scripting language. You can use this as a reference whenever in doubt.

    What do you think about the JavaScript cheat sheet? Let us know in the comments.

    People are also reading:

    Leave a Comment on this Post

    0 Comments