JavaScript Cheatsheet - Coding Torque


JavaScript Cheatsheet

JavaScript Cheatsheet

Hello Guys! Welcome to Coding Torque. In this blog, I shared an amazing JavaScript Cheatsheet for you. JavaScript is a lightweight and cross-platform programming language. In simple term, javascript is used to implement logic in a webpage. Here we go 🚀.

Basic

On Page Script

Write JS inside HTML Code

<script type="text/javascript"> 
// JavaScript Code Here... 
</script>

Include external JS file

Import JavaScript File in HTML

<script src="filename.js"/>

Functions

Function Syntax

function addition(a, b) { 
    return a + b; 
} 
x = addition(1, 2); 

DOM Element

Edit DOM element

document.getElementById("elementID").innerHTML = "Coding Torque";

Output

Print output in browser console.

console.log(" ");

Comments

Syntax

/* Multi line 
comment */ 
// Single Line comment

Conditional Statements

If-else Statement

Block of code inside if statement is executed, if the condition true.

if (condition) {
    // block of code to be executed if the condition is true
} else {                           
    // block of code to be executed if the condition is true
}

Else-if Statement

if-else ladder

if (condition-1) {
    // Code...
} else if (condition-2) {
    // Code...
} else {
    // Code...
}

Switch Statement

Switch case syntax

switch (expression) {
    case x:
        // code block
        break;
    case y:
        // code block
        break;
    default:
        // code block
}

String Methods

Declaration

A String stores sequence of characters like "Piyush".

let txt = "Coding Torque"

Length

Returns the length of string

let len = txt.length;

Index of

Returns index of given string. if doesn't match then returns -1.

txt.indexOf("Tor");

Slice

Cuts the string.

txt.slice(3, 6);

Replace

Replace the string.

txt.replace("Torque","Science");

Uppercase and Lowercase

Conversion of text into upper and lowecase.

txt.toUpperCase();
txt.toLowerCase();

Concat

Joins texts together.

txt.concat(" ", str2); 

Char At

Returns charater found at given index

txt.charAt(2);

Split

Split by commas and returns an array.

txt.split(",");

Number Methods

Numbers

JS provides several constants and methods to perform mathematical operations.

let pi = 3.14;

toFixed

pi.toFixed(0);  // returns 3

toPrecision

pi.toPrecision(2)

valueOf

pi.valueOf();

toString

converts object to string.

pi.toString();

Math Methods

Pow

Returns power.

Math.pow(2,4);

SQRT

Returns square root of given number.

Math.sqrt(49); 

Absolute value

Returns positive value.

Math.abs(-3.14);

Ceil

Returns the highest possible integer.

Math.ceil(3.14);

Floor

Returns the lowest possible integer.

Math.floor(3.99);

Random

Returns random number between 0 and 1.

Math.random();

Errors

Errors are thrown by a compiler or interpreter if they found any fault in the code. They can be any like logical error, syntax error, run-time error, etc.

Try and Catch Blocks

JS Provides Try and Catch Blocks to handle the errors.

try {
    // Block of code that may throw error
}
catch (err) {
    // Block of code to handle errors
}

Variables

Declarations

Three ways to declare variables

var a;  // variable
const PI = 3.14;  // constant variable
let ct = 'Coding Torque'; // block scope local variable

Operators

a = b + c - d;  // addition, substraction
a = b * (c / d);  // multiplication, division
x = 100 % 48;  // modulo. 100 / 48 remainder = 4
a++; b--;  // postfix increment and decrement

Data Types

var age = 18;  // number 
var name = "Piyush";  // string
var nameObj = {first:"Piyush", last:"Patil"};  // object
var isStarted = false;  // boolean
var languages = ["HTML","CSS","JS", "Python"];  // array
var a; typeof a;  // undefined
var a = null;  

var student = {
firstName: "Piyush",           // list of keys and values
lastName: "Patil",
age:18,
height:160,
fullName : function() {     // object function
    return this.firstName + " " + this.lastName;
}
}; 
student.age = 19;           // setting value
student[age]++;             // incrementing
name = student.fullName();  // call object function

Iteartive (Loop) Statements

For Loop

Example

for (let i = 0; i < 10; i++) {
console.log(i + ": " + i*2);
}

While Loop

Syntax

while(condition){
    // code
}

Do While Loop

Syntax

do {
    // code run atleast once
} while (condition)

Break

Stop and exits the loop

for (let i = 0; i < 10; i++) {
    if (i == 5) { break; }   
    console.log(i + ", ");
}

Continue

Skips the loop to next iteration, if condition is true

for (var i = 0; i < 10; i++) {
    if (i == 5) { continue; }       
    console.log(i + ", ");
}

Array Methods

Declaration

Array is a collections of items of same type.

let lang = ["HTML", "CSS", "JavaScript"];

toString

Converts array element to string.

lang.toString();

Join

Joins the array elements and convert to string

lang.join(" | ");

Pop

Delete the last element from the array.

lang.pop();

Push

Add new element to the array.

lang.push("Python");

Sort

Sorts string alphabetically.

lang.sort();  

Reverse

Sort string in descending order.

lang.reverse();

Date Methods

Date object is used to get the year, month and day.

let d = new Date();
a = d.getDay();     // getting the weekday
 

Get Date

Returns date

getDate();

Get Day

Returns weekday from date object.

getDay();

Get Full Year

Returns year from date object.

getFullYear();

Get Month

Returns month from date object.

getMonth();

Get Time

Returns time from date object.

getTime();

Get Hours

Returns Hours from date object.

getHours();

Get Mintutes

Returns minutes from date object.

getMinutes();

Get Seconds

Returns Seconds from date object.

getSeconds();

Get milliseconds

Returns milliseconds from date object.

getMilliseconds();

Mouse Events

Event that occurs due to the user interactng with devices. For example click, hover, etc.

click

Occurs when user clicks on an element.

element.addEventListener('click', () => {
    // Code
});

contextmenu

Occurs when user right-clicks on an element.

element.addEventListener('contextmenu', () => {
    // Code
});

dblclick

Occurs when user double-click on an element.

element.addEventListener('dblclick', () => {
    // Code
});

mouse enter

Occurs when mouse is hovered on an element.

element.addEventListener('mouseenter', () => {
    // Code
});

mouse leave

Occurs when mouse is hovered and leaved from an element.

element.addEventListener('mouseleave', () => {
    // Code
});

Written by: Piyush Patil

If you want me to code any project or post any specific post, feel free to DM me at IG @code.scientist or @codingtorque

If you have any doubt or any project ideas feel free to Contact Us 

Hope you find this post helpful💖 
 

 Follow us on Instagram for more projects like this👨‍💻 

Post a Comment

Previous Post Next Post