[Go to site: main page, start]

0% found this document useful (0 votes)
3 views16 pages

JavaScript Cheatsheet for Beginners

The document is a comprehensive JavaScript cheatsheet that covers various aspects of the language including writing on-page JavaScript, inserting external files, data types, operators, conditional statements, loops, functions, objects, arrays, DOM manipulation, event listeners, promises, async/await, and error handling. It provides code examples for each concept to illustrate their usage. This resource serves as a quick reference for JavaScript syntax and functionalities.

Uploaded by

vopavid620
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

JavaScript Cheatsheet for Beginners

The document is a comprehensive JavaScript cheatsheet that covers various aspects of the language including writing on-page JavaScript, inserting external files, data types, operators, conditional statements, loops, functions, objects, arrays, DOM manipulation, event listeners, promises, async/await, and error handling. It provides code examples for each concept to illustrate their usage. This resource serves as a quick reference for JavaScript syntax and functionalities.

Uploaded by

vopavid620
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Page 1 of 16

Home Whiteboard Online Compilers Practice Articles Tools

JavaScript 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="[Link]"></script>

Printing/Output
JavaScript provides three ways to print anything on the screen.

Console Output

Alert Boxes

Document Write

Console Output ([Link]())

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

[Link] 1/16
Page 2 of 16

[Link]("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);

[Link]()

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

[Link]("Hello World!");
var x = 10;
[Link]("Value of x is :", x);

Variables
JavaScript variables can be declared using the var, let, 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;

[Link] 2/16
Page 3 of 16

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

1. Primitive Types

The primitive data types are: String, Number, Boolean, Undefined, Null, Symbol,
BigInt

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;
[Link]("a =", a, ", b =", b);

// Addition (+)
let sum = a + b;
[Link]("a + b =", sum);
// Subtraction (-)
let difference = a - b;
[Link]("a - b =", difference);
// Multiplication (*)
let product = a * b;

[Link] 3/16
Page 4 of 16
[Link]("a * b =", product);
// Division (/)
let quotient = a / b;
[Link]("a / b =", quotient);
// Modulus (remainder) (%)
let remainder = a % b;
[Link]("a % b =", remainder);
// Increment (++)
a++;
[Link]("After a++:", a);
// Decrement (--)
b--;
[Link]("After b--:", b);

Assignment Operators

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

let x = 10;
[Link]("x:", x);
x = 5;
[Link]("x:", x);
x += 3;
[Link]("x:", x);
x -= 2;
[Link]("x:", x);
x *= 4;
[Link]("x:", x);
x /= 6;
[Link]("x:", x);
x %= 3;
[Link]("x:", x);

Comparison Operators

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

[Link] 4/16
Page 5 of 16

let x = 5;
let y = "5";
let z = 10;

[Link](x == y);
[Link](x === y);
[Link](x != z);
[Link](x !== y);
[Link](z > x);
[Link](x < z);
[Link](z >= 10);
[Link](x <= 5);

Logical Operators

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

let a = true;
let b = false;
let c = 5;
let d = 10;

[Link](a && c < d);


[Link](b && c < d);
[Link](a || b);
[Link](b || d < c);
[Link](!a);
[Link](!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 −

[Link] 5/16
Page 6 of 16

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

Below is an example of if-else statements −

let age = 20;

if (age < 18) {


[Link]("You are a minor.");
} else if (age >= 18 && age < 65) {
[Link]("You are an adult.");
} else {
[Link]("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."

[Link] 6/16
Page 7 of 16
: "You are a senior citizen.";

[Link](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++) {


[Link](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) {
[Link](i);
i++;
}

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

[Link] 7/16
Page 8 of 16

let i=0;
do {
[Link](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 Declaration
function addNumbers(a, b) {
return a + b; // Return the sum of a and b
}

// Example usage
let sum = addNumbers(5, 10);
[Link]("The sum is:", sum); // The sum is: 15

Function Expression
The function expression is as follows −

const multiply = function(a, b) {


return a * b;
}

Arrow Function

JavaScript arrow function is used to write function expressions.

[Link] 8/16
Page 9 of 16
Below is a simple statement to create an arrow function −

const divide = (a, b) => a / b;

Example of an arrow function to add two numbers −

// Arrow function
const addNumbers = (a, b) => a + b;
// Calling
let sum = addNumbers(5, 10);
[Link]("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() {
[Link]("Hello, " + [Link]);
}
};

[Link]([Link]); // Access property


[Link](); // Call method

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

Array Declaration

[Link] 9/16
Page 10 of 16
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
[Link]("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 array


let students = ["Kelly Hu", "Peter", "John"];
// push()
[Link]("Bobby", "Catty");
[Link](students);
// pop()
[Link]("Removed :", [Link]());
// shift()

[Link] 10/16
Page 11 of 16
[Link]("Removed :", [Link]());
// unshift()
[Link]("Julia", "Halle");
[Link](students);
// concat()
const newNames = ["Emma", "Reese"];
const newArray = [Link](newNames);
[Link]("After concat:", newArray);
// join()
const str = [Link](", ");
[Link]("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]


[Link]((item) => [Link](item));

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

let element = [Link]('myElement');


[Link] = 'New Content'; // Change content
[Link] = 'red'; // Change style
[Link]('.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 −

[Link] 11/16
Page 12 of 16

[Link]('click', function() {
alert('Clicked!');
});

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

// Promises
let promise = new Promise((resolve, reject) => {
// asynchronous code
if (success) resolve('Success');
else reject('Error');
});

[Link](result => [Link](result)).catch(err =>


[Link](err));

Async/Await
JavaScript Async/Await works with asynchronous operations.

The following is an example of Async/Await −

async function fetchData() {


try {
let response = await fetch('url');
let data = await [Link]();
[Link](data);
} catch (error) {
[Link](error);
}
}

[Link] 12/16
Page 13 of 16

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) {
[Link]([Link]); // Handle the error
} finally {
[Link]("Finally block executed");
}

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

function divideNumbers(num1, num2) {


try {
if (num2 === 0) {
throw new Error("Cannot divide by zero!");
}
const result = num1 / num2;
[Link](`Result: ${result}`);
} catch (error) {
[Link]("Error:", [Link]);
} finally {
[Link]("Execution completed.");
}
}

// Calling
divideNumbers(10, 2);
divideNumbers(10, 0);

[Link] 13/16
Page 14 of 16

TOP TUTORIALS

Python Tutorial
Java Tutorial

C++ Tutorial

C Programming Tutorial
C# Tutorial

PHP Tutorial

R Tutorial
HTML Tutorial

CSS Tutorial

JavaScript Tutorial
SQL Tutorial

TRENDING TECHNOLOGIES

Cloud Computing Tutorial


Amazon Web Services Tutorial

Microsoft Azure Tutorial

Git Tutorial
Ethical Hacking Tutorial

Docker Tutorial

Kubernetes Tutorial
DSA Tutorial

Spring Boot Tutorial

SDLC Tutorial
Unix Tutorial

CERTIFICATIONS

Business Analytics Certification

Java & Spring Boot Advanced Certification

Data Science Advanced Certification


Cloud Computing And DevOps

Advanced Certification In Business Analytics

Artificial Intelligence And Machine Learning


DevOps Certification

[Link] 14/16
Page 15 of 16
Game Development Certification

Front-End Developer Certification


AWS Certification Training

Python Programming Certification

COMPILERS & EDITORS

Online Java Compiler

Online Python Compiler


Online Go Compiler

Online C Compiler

Online C++ Compiler


Online C# Compiler

Online PHP Compiler

Online MATLAB Compiler


Online Bash Terminal

Online SQL Compiler

Online Html Editor

ABOUT US | OUR TEAM | CAREERS | JOBS | CONTACT US | TERMS OF USE |

PRIVACY POLICY | REFUND POLICY | COOKIES POLICY | FAQ'S

Tutorials Point is a leading Ed Tech company striving to provide the best learning material on
technical and non-technical subjects.

[Link] 15/16
Page 16 of 16
© Copyright 2025. All Rights Reserved.

[Link] 16/16

You might also like