Ready to learn JavaScript quickly?
If yes, then you need this JavaScript cheat sheet. It covers the basics of JavaScript in a clear, concise, and beginner-friendly way.
Use it as a reference or a guide to improve your JavaScript skills.
Letâs dive in.
What Is JavaScript?
JavaScript (JS) is a programming language primarily used for web development.
It allows developers to add interactivity and dynamic behavior to websites.
For example, you can use JavaScript to create interactive forms that validate usersâ inputs in real time. Making error messages pop up as soon as users make mistakes.
Like this:

JavaScript can also be used to enable features like accordions that expand and collapse content sections.
Hereâs one example with the âSEOâ section expanded:

In the example above, clicking on each element in the series shows different content.
JavaScript makes this possible by manipulating the HTML and CSS of the page in real time.
JavaScript is also extremely useful in web-based applications like Gmail.
When you receive new emails in your Gmail inbox, JavaScript is responsible for updating the inbox and notifying you of new messages without the need for manually refreshing.

So, in other words:Â
JavaScript empowers web developers to craft rich user experiences on the internet.
Understanding the Code Structure
To leverage JavaScript effectively, it's crucial to understand its code structure.Â
JavaScript code often sits in your webpagesâ HTML.
Itâs embedded using the <script> tags.
<script>
// Your JavaScript code goes here
</script>You can also link to external JavaScript files using the src attribute within the <script> tag.Â
This approach is preferred for larger JavaScript codebases. Because it keeps your HTML clean and separates the code logic from the page content.
<script src="mycode.js"></script>Now, let's explore the essential components that you can use in your JavaScript code.
List of JavaScript Components (Cheat Sheet Included)
Below, youâll find the most essential components used in JavaScript.
As you become more familiar with these building blocks, you'll have the tools to create engaging and user-friendly websites.
(Hereâs the cheat sheet, which you can download and keep as a handy reference for all these components. )
Variables
Variables are containers that store some value. That value can be of any data type, such as strings (meaning text) or numbers.
There are three keywords for declaring (i.e., creating) variables in JavaScript: âvar,â âlet,â and âconst.â
var Keyword
âvarâ is a keyword used to tell JavaScript to make a new variable.
After we make a variable with âvar,â it works like a container to store things.Â
Consider the following example.
var name = "Adam";Here, weâve created a variable called ânameâ and put the value âAdamâ in it.
This value is usable. Meaning we can use the variable "name" to get the value "Adam" whenever we need it in our code.
For example, we can write:
var name = "Adam";
console.log("Hello, " + name);This means the second line will show âHello, Adamâ in your console (a message window for checking the output of your program).
Values in the variables created using the keyword var can be changed. You can modify them later in your code.
Hereâs an example to illustrate this point:
var name = "Adam";
name = "John";
console.log("Hello, " + name);First, weâve put âAdamâ in the ânameâ variable. Later, we changed the value of the same variable to âJohn.â This means that when we run this program, the output we will see in the console is âHello, John.â
But, remember one thing:
In modern JavaScript, people often prefer using âletâ and âconstâ keywords (more on those in a moment) over âvar.â Because âletâ and âconstâ provide improved scoping rules.
let Keyword
An alternative to âvar,â âletâ is another keyword for creating variables in JavaScript.
Like this:
let name = "Adam";Now, we can use the variable ânameâ in our program to show the value it stores.
For example:
let name = "Adam";
console.log("Hello, " + name);This program will display "Hello, Adam" in the console when you run it.
If you want to override the value your variable stores, you can do that like this:
var name = "Adam";
name = "Steve";
console.log("Hello, " + name);const Keyword
âconstâ is similar to âlet,â but declares a fixed variable.
Which means:
Once you enter a value in it, you can't change it later.
Using âconstâ for things like numeric values helps prevent bugs by avoiding unintended changes later in code.
âconstâ also makes the intent clear. Other developers can see at a glance which variables are meant to remain unchanged.
For example:
let name = "Adam";
const age = 30;Using âconstâ for "age" in this example helps prevent unintentional changes to a person's age.Â
It also makes it clear to other developers that "age" is meant to remain constant throughout the code.
Operators
Operators are symbols that perform operations on variables.Â
Imagine you have some numbers and you want to do math with them, like adding, subtracting, or comparing them.
In JavaScript, we use special symbols to do this, and these are called operators. The main types of operators are:
Arithmetic OperatorsÂ
Arithmetic operators are used to perform mathematical calculations on numbers. These include:
| Operator Name | Symbol | Description |
| âAdditionâ operator | + | The âadditionâ operator adds numbers together |
| âSubtractionâ operator | - | The âsubtractionâ operator subtracts the right-hand value from the left-hand value |
| âMultiplicationâ operator | * | The âmultiplicationâ operator multiplies numbers together |
| âDivisionâ operator | / | The âdivisionâ operator divides the left-hand number by the right-hand number |
| âModulusâ operator | % | The âmodulusâ operator returns a remainder after division |
Letâs put all of these operators to use and write a basic program:Â
let a = 10;
let b = 3;
let c = a + b;
console.log("c");
let d = a - b;
console.log("d");
let e = a * b;
console.log("e");
let f = a / b;
console.log("f");
let g = a % b;
console.log("g");Here's what this program does:
- It sets two variables, âaâ and âb,â to 10 and 3, respectively
- Then, it uses the arithmetic operators:
- â+â to add the value of âaâ and âbâ
- â-â to subtract the value of âbâ from âaâ
- â*â to multiply the value of âaâ and âbâ
- â/â to divide the value of âaâ by âbâ
- â%â to find the remainder when âaâ is divided by âbâ
- It displays the results of each arithmetic operation using âconsole.log()â
Comparison Operators
Comparison operators compare two values and return a boolean resultâi.e., either true or false.
Theyâre essential for writing conditional logic in JavaScript.
The main comparison operators are:
| Operator Name | Symbol | Description |
| âEqualityâ operator | == | Compares if two values are equal, regardless of data type. For example, â5 == 5.0â would return âtrueâ even though the first value is an integer and the other is a floating-point number (a numeric value with decimal places) with the same numeric value. |
| âStrict equalityâ operator | === | Compares if two values are equal, including the data type. For example, â5 === 5.0â would return âfalseâ because the first value is an integer and the other is a floating-point number, which is a different data type. |
| âInequalityâ operator | != | Checks if two values are not equal. It doesnât matter what type of values they are. For example, â5 != 10â would return âtrueâ because 5 does not equal 10. |
| âStrict inequalityâ operator | !== | Checks if two values are not equal, including the data type. For example, â5 !== 5.0â would return âtrueâ because the first value is an integer and the other is a floating-point number, which is a different data type. |
| âGreater thanâ operator | > | Checks if the left value is greater than the right value. For example, â10 > 5â returns âtrue.â |
| âLess thanâ operator | < | Checks if the left value is less than the right value. For example, â5 < 10â returns âtrue.â |
| âGreater than or equal toâ operator | >= | Checks if the left value is greater than or equal to the right value. For example, â10 >= 5â returns âtrue.â |
| âLess than or equal toâ operator | <= | Checks if the left value is less than or equal to the right value. For example, â5 <= 10â returns âtrue.â |
Letâs use all these operators and write a basic JS program to better understand how they work:
let a = 5;
let b = 5.0;
let c = 10;
if (a == b) {
console.log('true');
} else {
console.log('false');
}
if (a === b) {
console.log('true');
} else {
console.log('false');Â
}
if (a != c) {
console.log('true');
} else {
console.log('false');
}
if (a !== b) {
console.log('true');
} else {
console.log('false');
}
if (c > a) {
console.log('true');
} else {
console.log('false');
}
if (a < c) {
console.log('true');Â
} else {
console.log('false');
}
if (c >= a) {
console.log('true');
} else {
console.log('false');
}
if (a <= c) {
console.log('true');
} else {
console.log('false');
}Hereâs what this program does:
- It sets three variables: âaâ with a value of 5, âbâ with a value of 5.0 (a floating-point number), and âcâ with a value of 10
- It uses the â==â operator to compare âaâ and âb.â Since âaâ and âbâ have the same numeric value (5), it returns "true."
- It uses the â===â operator to compare âaâ and âb.â This time, it checks not only the value but also the data type. Although the values are the same, âaâ is an integer and âbâ is a floating-point number. So, it returns "false."
- It uses the â!=â operator to compare âaâ and âc.â As âaâ and âcâ have different values, it returns "true."
- It uses the â!==â operator to compare âaâ and âb.â Again, it considers the data type, and since âaâ and âbâ are of different types (integer and floating-point), it returns "true."
- It uses the â>â operator to compare âcâ and âa.â Since âcâ is greater than âa,â it returns "true."
- It uses the â<â operator to compare âaâ and âc.â As âaâ is indeed less than âc,â it returns "true."
- It uses the â>=â operator to compare âcâ and âa.â Since c is greater than or equal to a, it returns "true."
- It uses the â<=â operator to compare âaâ and âc.â As âaâ is less than or equal to âc,â it returns "true."
In short, this program uses the various comparison operators to make decisions based on the values of variables âa,â âb,â and âc.â
You can see how each operator compares these values and determines whether the conditions specified in the if statements are met. Leading to different console outputs.
Logical Operators
Logical operators allow you to perform logical operations with values.Â
These operators are typically used to make decisions in your code, control program flow, and create conditions for executing specific blocks of code.
There are three main logical operators in JavaScript:Â
| Operator Name | Symbol | Description |
| âLogical ANDâ operator | && | The âlogical ANDâ operator is used to combine two or more conditions. It returns âtrueâ only if all the conditions are true. |
| âLogical ORâ operator | | | | The âlogical ORâ operator is used to combine multiple conditions. And it returns âtrueâ if at least one of the conditions is true. If all conditions are false, the result will be âfalse.â |
| âLogical NOTâ operator | ! | The âlogical NOTâ operator is used to reverse the logical state of a single condition. If a condition is true, â!â makes it âfalse.â And if a condition is false, â!â makes it âtrue.â |
To better understand each of these operators, letâs consider the examples below.
First, a â&&â (logical AND) operator example:
let age = 25;
let hasDriverLicense = true;
if (age >= 18 && hasDriverLicense) {
console.log("You can drive!");
} else {
console.log("You cannot drive.");
}In this example, the code checks if the age is greater than or equal to 18 and if the person has a driver's license. Since both conditions are true, its output is "You can drive!"
Second, a â| |â (logical OR) operator example:
let isSunny = true;
let isWarm = true;
if (isSunny || isWarm) {
console.log("It's a great day!");
} else {
console.log("Not a great day.");
}In this example, the code outputs "It's a great day!" because one or both of the conditions hold true.
And third, a â!â (logical NOT) operator example:
let isRaining = true;
if (!isRaining) {
console.log("It's not raining. You can go outside!");
} else {
console.log("It's raining. Stay indoors.");
}Here, the â!â operator inverts the value of isRaining from true to false.
So, the âifâ condition â!isRainingâ evaluates to false. Which means the code in the else block runs, returning "It's raining. Stay indoors."
Assignment Operators:
Assignment operators are used to assign values to variables. The standard assignment operator is the equals sign (=). But there are other options as well.
Hereâs the complete list:
| Operator Name | Symbol | Description |
| âBasic assignmentâ operator | = | The âbasic assignmentâ operator is used to assign a value to a variable |
| âAddition assignmentâ operator | += | This operator adds a value to the variable's current value and assigns the result to the variable |
| âSubtraction assignmentâ operator | -= | This operator subtracts a value from the variable's current value and assigns the result to the variable |
| âMultiplication assignmentâ operator | *= | This operator multiplies the variable's current value by a specified value and assigns the result to the variable |
| âDivision assignmentâ operator | /= | This operator divides the variable's current value by a specified value and assigns the result to the variable |
Letâs understand these operators with the help of some code:
let x = 10;
x += 5;Â
console.log("After addition: x = ", x);
x -= 3;Â
console.log("After subtraction: x = ", x);
x *= 4;
console.log("After multiplication: x = ", x);
x /= 6;
console.log("After division: x = ", x);In the code above, we create a variable called âxâ and set it equal to 10. Then, we use various assignment operators to modify its value:
- âx += 5;â adds 5 to the current value of âxâ and assigns the result back to âx.â So, after this operation, âxâ becomes 15.
- âx -= 3;â subtracts 3 from the current value of âxâ and assigns the result back to âx.â After this operation, âxâ becomes 12.
- âx *= 4;â multiplies the current value of âxâ by 4 and assigns the result back to âx.â So, âxâ becomes 48.
- âx /= 6;â divides the current value of âxâ by 6 and assigns the result back to âx.â After this operation, âxâ becomes 8.
At each operation, the code prints the updated values of âxâ to the console.
if-else
The âif-elseâ statement is a conditional statement that allows you to execute different blocks of code based on a condition.
Itâs used to make decisions in your code by specifying what should happen when a particular condition is true. And what should happen when itâs false.
Here's an example to illustrate how âif-elseâ works:
let age = 21;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");In this example, the âageâ variable is compared to 18 using the â>=â operator.Â
Since âage >= 18â is true, the message "You are an adult." is displayed. But if it werenât, the message "You are a minor." wouldâve been displayed.
Loops
Loops are programming constructs that allow you to repeatedly execute a block of code as long as a specified condition is met.
Theyâre essential for automating repetitive tasks.
JavaScript provides several types of loops, including:
for Loop
A âforâ loop is a loop that specifies "do this a specific number of times."Â
It's well-structured and has three essential components: initialization, condition, and increment. This makes it a powerful tool for executing a block of code a predetermined number of times.
Here's the basic structure of a âforâ loop:
for (initialization; condition; increment) {
// Code to be executed as long as the condition is true
}The loop starts with the initialization (this is where you set up the loop by giving it a starting point), then checks the condition, and executes the code block if the condition is true.
After each iteration, the increment is applied, and the condition is checked again.
The loop ends when the condition becomes false.
For example, if you want to count from 1 to 10 using a âforâ loop, hereâs how you would do it:
for (let i = 1; i <= 10; i++) {
console.log(i);
}In this example:
- The initialization part sets up a variable âiâ to start at 1
- The loop keeps running as long as the condition (in this case, âi <= 10â) is true
- Inside the loop, it logs the value of âiâ using âconsole.log(i)âÂ
- After each run of the loop, the increment part, âi++â, adds 1 to the value of âiâ
Here's what the output will look like when you run this code:
1
2
3
4
5
6
7
8
9
10As you can see, the âforâ loop starts with âiâ at 1. And incrementally increases it by 1 in each iteration.Â
It continues until âiâ reaches 10 because the condition âi <= 10â is satisfied.Â
The âconsole.log(i)â statement prints the current value of âiâ during each iteration. And that results in the numbers from 1 to 10 being displayed in the console.
while Loop
A âwhileâ loop is a loop that indicates "keep doing this as long as something is true."Â
It's a bit different from the âforâ loop because it doesn't have an initialization, condition, and increment all bundled together. Instead, you write the condition and then put your code block inside the loop.
For example, if you want to count from 1 to 10 using a âwhileâ loop, hereâs how you would do it:
let i = 1;
while (i <= 10) {
console.log(i);
i++;
}In this example:
- You initialize âiâ to 1
- The loop keeps running as long as âiâ is less than or equal to 10
- Inside the loop, it logs the value of âiâ using âconsole.log(i)âÂ
- âiâ incrementally increases by 1 after each run of the loop
The output of this code will be:
1
2
3
4
5
6
7
8
9
10So, with both âforâ and âwhileâ loops, you have the tools to repeat tasks and automate your code
doâŠwhile Loop
A âdo...whileâ loop works similarly to âforâ and âwhileâ loops, but it has a different syntax.
Here's an example of counting from 1 to 10 using a âdo...whileâ loop:
let i = 1;
do {
console.log(i);
i++;
} while (i <= 10);In this example:
- You initialize the variable "i" to 1 before the loop starts
- The âdo...whileâ loop begins by executing the code block, which logs the value of "i" using âconsole.log(i)â
- After each run of the loop, "i" incrementally increases by 1 using âi++â
- The loop continues to run as long as the condition "i <= 10" is true
The output of this code will be the same as in the previous examples:
1
2
3
4
5
6
7
8
9
10forâŠin Loop
The âfor...inâ loop is used to iterate over the properties of an object (a data structure that holds key-value pairs).Â
It's particularly handy when you want to go through all the keys or properties of an object and perform an operation on each of them.
Here's the basic structure of a âfor...inâ loop:
for (variable in object) {
// Code to be executed for each property
}And hereâs an example of a âfor...inâ loop in action:
const person = {
name:Â "Alice",
age:Â 30,
city: "New York"
};
for (let key in person) {
console.log(key, person[key]);
}In this example:
- You have an object named âpersonâ with the properties âname,â âage,â and âcityâ
- The âfor...inâ loop iterates over the keys (in this case, "name," "age," and "city") of the âpersonâ object
- Inside the loop, it logs both the property name (key) and its corresponding value in the âpersonâ object
The output of this code will be:
name Alice
age 30
city New YorkThe âfor...inâ loop is a powerful tool when you want to perform tasks like data extraction or manipulation.
Functions
A function is a block of code that performs a particular action in your code. Some common functions in JavaScript are:
alert() Function
This function displays a message in a pop-up dialog box in the browser. It's often used for simple notifications, error messages, or getting the user's attention.
Take a look at this sample code:
alert("Hello, world!");When you call this function, it opens a small pop-up dialog box in the browser with the message âHello, world!â And a user can acknowledge this message by clicking an "OK" button.
prompt() Function
This function displays a dialog box where the user can enter an input. The input is returned as a string.
Hereâs an example:
let name = prompt("Please enter your name: ");
console.log("Hello, " + name + "!");In this code, the user is asked to enter their name. And the value they provide is stored in the name variable.
Later, the code uses the name to greet the user by displaying a message, such as "Hello, [user's name]!"
confirm() Function
This function shows a confirmation dialog box with "OK" and "Cancel" buttons. It returns âtrueâ if the user clicks "OK" and âfalseâ if they click "Cancel."
Letâs illustrate with some sample code:
const isConfirmed = confirm("Are you sure you want to continue?");
if (isConfirmed) {
console.log("true");
} else {
console.log("false");
}When this code is executed, the dialog box with the message "Are you sure you want to continue?" is displayed, and the user is presented with "OK" and "Cancel" buttons.
The user can click either the "OK" or "Cancel" button to make their choice.
The âconfirm()â function then returns a boolean value (âtrueâ or âfalseâ) based on the user's choice: âtrueâ if they click "OK" and âfalseâ if they click "Cancel."
console.log() Function
This function is used to output messages and data to the browser's console.
Sample code:
console.log("This is the output.");You probably recognize it from all our code examples from earlier in this post.
parseInt() Function
This function extracts and returns an integer from a string.
Sample code:
const stringNumber = "42";
const integerNumber = parseInt(stringNumber);In this example, the âparseInt()â function processes the string and extracts the number 42.
The extracted integer is then stored in the variable âintegerNumber.â Which you can use for various mathematical calculations.
parseFloat() Function
This function extracts and returns a floating-point number (a numeric value with decimal places).
Sample code:
const stringNumber = "3.14";
const floatNumber = parseFloat(stringNumber);In the example above, the âparseFloat()â function processes the string and extracts the floating-point number 3.14.
The extracted floating-point number is then stored in the variable âfloatNumber.â
Strings
A string is a data type used to represent text.Â
It contains a sequence of characters, such as letters, numbers, symbols, and whitespace. Which are typically enclosed within double quotation marks (" ").
Here are some examples of strings in JavaScript:
const name = "Alice";
const number = "82859888432";
const address = "123 Main St.";There are a lot of methods you can use to manipulate strings in JS code. These are most common ones:Â
toUpperCase() Method
This method converts all characters in a string to uppercase.
Example:
let text = "Hello, World!";
let uppercase = text.toUpperCase();
console.log(uppercase);In this example, the âtoUpperCase()â method processes the text string and converts all characters to uppercase.
As a result, the entire string becomes uppercase.
The converted string is then stored in the variable uppercase, and the output in your console is "HELLO, WORLD!"
toLowerCase() Method
This method converts all characters in a string to lowercase
Hereâs an example:
let text = "Hello, World!";
let lowercase = text.toLowerCase();
console.log(lowercase);After this code runs, the âlowercaseâ variable will contain the value "hello, world!" Which will then be the output in your console.
concat() Method
The âconcat()â method is used to combine two or more strings and create a new string that contains the merged text.
It does not modify the original strings. Instead, it returns a new string that results from the combination of the original strings (called the concatenation).Â
Here's how it works:
const string1 = "Hello, ";
const string2 = "world!";
const concatenatedString = string1.concat(string2);
console.log(concatenatedString);In this example, we have two strings, âstring1â and âstring2.â Which we want to concatenate.
We use the âconcat()â method on âstring1â and provide âstring2â as an argument (an input value within the parentheses). The method combines the two strings and creates a new string, stored in the âconcatenatedStringâ variable.
The program then outputs the end result to your console. In this case, thatâs âHello, world!â
match() Method
The âmatch()â method is used to search a string for a specified pattern and return the matches as an array (a data structure that holds a collection of valuesâlike matched substrings or patterns).
It uses a regular expression for that. (A regular expression is a sequence of characters that defines a search pattern.)
The âmatch()â method is extremely useful for tasks like data extraction or pattern validation.
Hereâs a sample code that uses the âmatch()â method:
const text = "The quick brown fox jumps over the lazy dog";
const regex = /[A-Za-z]+/g;
const matches = text.match(regex);
console.log(matches);In this example, we have a string named âtext.â
Then, we use the âmatch()â method on the âtextâ string and provide a regular expression as an argument.
This regular expression, â/[A-Za-z]+/g,â does two things:
- It matches any letter from âAâ to âZ,â regardless of whether it's uppercase or lowercase
- It executes a global search (indicated by âgâ at the end of the regular expression). This means the search doesn't stop after the first match is found. Instead, it continues to search through the entire string and returns all matches.
After that, all the matches are stored in the âmatchesâ variable.
The program then outputs these matches to your console. In this case, it will be an array of all the words in the sentence "The quick brown fox jumps over the lazy dog."
charAt() Method
The âcharAt()â method is used to retrieve the character at a specified index (position) within a string.
The first character is considered to be at index 0, the second character is at index 1, and so on.
Hereâs an example:
const text = "Hello, world!";
const character = text.charAt(7);
console.log(character);In this example, we have the string âtext,â and we use the âcharAt()â method to access the character at index 7.Â
The result is the character "w" because "w" is at position 7 within the string.Â
replace() Method
The âreplace()â method is used to search for a specified substring (a part within a string) and replace it with another substring.
It specifies both the substring you want to search for and the substring you want to replace it with.
Here's how it works:
const text = "Hello, world!";
const newtext = text.replace("world", "there");
console.log(newtext);In this example, we use the âreplace()â method to search for the substring "world" and replace it with "there."
The result is a new string (ânewtextâ) that contains the replaced text. Meaning the output is, âHello, there!â
substr() Method
The âsubstr()â method is used to extract a portion of a string, starting from a specified index and extending for a specified number of characters.Â
It specifies the starting index from which you want to begin extracting characters and the number of characters to extract.
Here's how it works:
const text = "Hello, world!";
const substring = text.substr(7, 5);
console.log(substring);In this example, we use the âsubstr()â method to start extracting characters from index 7 (which is âwâ) and continue for five characters.
The output is the substring "world."
(Note that the first character is always considered to be at index 0. And you start counting from there on.)
Events
Events are actions that happen in the browser, such as a user clicking a button, a webpage finishing loading, or an element on the page being hovered over with a mouse.
Understanding these is essential for creating interactive and dynamic webpages. Because they allow you to respond to user actions and execute code accordingly.
Here are the most common events supported by JavaScript:Â
onclick Event
The âonclickâ event executes a function or script when an HTML element (such as a button or a link) is clicked by a user.
Hereâs the code implementation for this event:
<button id="myButton" onclick="changeText()">Click me</button>
<script>
function changeText() {
let button = document.getElementById("myButton");
button.textContent = "Clicked!";
}
</script>Now, let's understand how this code works:
- When the HTML page loads, it displays a button with the text "Click me"
- When a user clicks on the button, the âonclickâ attribute specified in the HTML tells the browser to call the âchangeTextâ function
- The âchangeTextâ function is executed and selects the button element using its id ("myButton")
- The âtextContentâ property of the button changes to "Clicked!"
As a result, when the button is clicked, its text changes from "Click me" to "Clicked!"
It's a simple example of adding interactivity to a webpage using JavaScript.
onmouseover Event
The âonmouseoverâ event occurs when a user moves the mouse pointer over an HTML element, such as an image, a button, or a hyperlink.
Hereâs how the code that executes this event looks:
<img id="myImage" src="image.jpg" onmouseover="showMessage()">
<script>
function showMessage() {
alert("Mouse over the image!");
}
</script>In this example, we have an HTML image element with the âidâ attribute set to "myImage."Â
It also has an âonmouseoverâ attribute specified, which indicates that when the user hovers the mouse pointer over the image, the "showMessage ()" function should be executed.
This function displays an alert dialog with the message "Mouse over the image!"
The âonmouseoverâ event is useful for adding interactivity to your web pages. Such as providing tooltips, changing the appearance of elements, or triggering actions when the mouse moves over specific areas of the page.
onkeyup Event
The âonkeyupâ is an event that occurs when a user releases a key on their keyboard after pressing it.Â
Hereâs the code implementation for this event:
<input type="text" id="myInput" onkeyup="handleKeyUp()">
<script>
function handleKeyUp() {
let input = document.getElementById("myInput");
let userInput = input.value;
console.log("User input: " + userInput);
}
</script>In this example, we have an HTML text input element <input> with the âidâ attribute set to "myInput."
It also has an âonkeyupâ attribute specified, indicating that when a key is released inside the input field, the "handleKeyUp()" function should be executed.
Then, when the user types or releases a key in the input field, the âhandleKeyUp()â function is called.
The function retrieves the input value from the text field and logs it to the console.
This event is commonly used in forms and text input fields to respond to a userâs input in real time.
Itâs helpful for tasks like auto-suggestions and character counting, as it allows you to capture usersâ keyboard inputs as they type.
onmouseout Event
The âonmouseoutâ event occurs when a user moves the mouse pointer out of the area occupied by an HTML element like an image, a button, or a hyperlink.
When the event is triggered, a predefined function or script is executed.
Hereâs an example:
<img id="myImage" src="image.jpg" onmouseout="hideMessage()">
<script>
function hideMessage() {
alert("Mouse left the image area!");
}
</script>In this example, we have an HTML image element with the âidâ attribute set to "myImage."Â
It also has an âonmouseoutâ attribute specified, indicating that when the user moves the mouse cursor out of the image area, the "hideMessage()" function should be executed.
Then, when the user moves the mouse cursor out of the image area, a JavaScript function called âhideMessage()â is called.Â
The function displays an alert dialog with the message "Mouse left the image area!"
onload Event
The âonloadâ event executes a function or script when a webpage or a specific element within the page (such as an image or a frame) has finished loading.
Hereâs the code implementation for this event:
<body onload="initializePage()">
<script>
function initializePage() {
alert("Page has finished loading!");
}
</script>In this example, when the webpage has fully loaded, the âinitializePage()â function is executed, and an alert with the message "Page has finished loading!" is displayed.
onfocus Event
The âonfocusâ event triggers when an HTML element like an input field receives focus or becomes the active element of a userâs input or interaction.
Take a look at this sample code:
<input type="text" id="myInput" onfocus="handleFocus()">
<script>
function handleFocus() {
alert("Input field has received focus!");
}
</script>In this example, we have an HTML text input element <input> with the âidâ attribute set to "myInput."Â
It also has an âonfocusâ attribute specified. Which indicates that when the user clicks on the input field or tabs into it, the "handleFocus()" function will be executed.
This function displays an alert with the message "Input field has received focus!"
The âonfocusâ event is commonly used in web forms to provide visual cues (like changing the background color or displaying additional information) to users when they interact with input fields.
onsubmit Event
The âonsubmitâ event triggers when a user submits an HTML form. Typically by clicking a "Submit" button or pressing the "Enter" key within a form field.Â
It allows you to define a function or script that should be executed when the user attempts to submit the form.
Hereâs a code sample:
<form id="myForm" onsubmit="handleSubmit()">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
<script>
function handleSubmit() {
let form = document.getElementById("myForm");
alert("Form submitted!");
}
</script>In this example, we have an HTML form element with the âidâ attribute set to "myForm."Â
It also has an âonsubmitâ attribute specified, which triggers the "handleSubmit()" function when a user submits the form.
This function shows an alert with the message "Form submitted!"
Numbers and Math
JavaScript supports lots of methods (pre-defined functions) to deal with numbers and do mathematical calculations.Â
Some of the methods it supports include:
Math.abs() Method
This method returns the absolute value of a number, ensuring the result is positive.
Here's an example that demonstrates the use of the âMath.abs()â method:
let negativeNumber = -5;
let positiveNumber = Math.abs(negativeNumber);
console.log("Absolute value of -5 is: " + positiveNumber);In this code, we start with a negative number (-5). By applying âMath.abs(),â we obtain the absolute (positive) value of 5.Â
This method is helpful for scenarios where you need to ensure that a value is non-negative, regardless of its initial sign.
Math.round() Method
This method rounds a number up to the nearest integer.
Sample code:
let decimalNumber = 3.61;
let roundedUpNumber = Math.round(decimalNumber);
console.log("Ceiling of 3.61 is: " + roundedUpNumber);In this code, we have a decimal number (3.61). Applying âMath.round()â rounds it up to the nearest integer. Which is 4.
This method is commonly used in scenarios when you want to round up quantities, such as when calculating the number of items needed for a particular task or when dealing with quantities that can't be fractional.
Math.max() Method
This method returns the largest value among the provided numbers or values. You can pass multiple arguments to find the maximum value.
Here's an example that demonstrates the use of the âMath.max()â method:
let maxValue = Math.max(5, 8, 12, 7, 20, -3);
console.log("The maximum value is: " + maxValue);In this code, we pass several numbers as arguments to the âMath.max()â method.Â
The method then returns the largest value from the provided set of numbers, which is 20 in this case.
This method is commonly used in scenarios like finding the highest score in a game or the maximum temperature in a set of data points.
Math.min() Method
The âMath.min()â method returns the smallest value among the provided numbers or values.
Sample code:
let minValue = Math.min(5, 8, 12, 7, 20, -3);
console.log("The minimum value is: " + minValue);In this code, we pass several numbers as arguments to the âMath.min()â method.Â
The method then returns the smallest value from the given set of numbers, which is -3.
This method is commonly used in situations like identifying the shortest distance between multiple points on a map or finding the lowest temperature in a set of data points.Â
Math.random() Method
This method generates a random floating-point number between 0 (inclusive) and 1 (exclusive).
Hereâs some sample code:
const randomValue = Math.random();
console.log("Random value between 0 and 1: " + randomValue);In this code, we call the âMath.random()â method, which returns a random value between 0 (inclusive) and 1 (exclusive).Â
It's often used in applications where randomness is required.
Math.pow() Method
This method calculates the value of a base raised to the power of an exponent.
Letâs look at an example:
let base = 2;
let exponent = 3;
let result = Math.pow(base, exponent);
console.log(`${base}^${exponent} is equal to: ${result}`)In this code, we have a base value of 2 and an exponent value of 3. By applying âMath.pow(),â we calculate 2 raised to the power of 3, which is 8.
Math.sqrt() Method
This method computes the square root of a number.
Take a look at this sample code:
let number = 16;
const squareRoot = Math.sqrt(number);
console.log(`The square root of ${number} is: ${squareRoot}`);In this code, we have the number 16. By applying âMath.sqrt(),â we calculate the square root of 16. Which is 4.
Number.isInteger() Method
This method checks whether a given value is an integer. It returns true if the value is an integer and false if not.
Here's an example that demonstrates the use of the âNumber.isInteger()â method:
let value1 = 42;
let value2 = 3.14;
let isInteger1 = Number.isInteger(value1);
let isInteger2 = Number.isInteger(value2);
console.log(`Is ${value1} an integer? ${isInteger1}`);
console.log(`Is ${value2} an integer? ${isInteger2}`);In this code, we have two values, âvalue1â and âvalue2.â We use the âNumber.isInteger()â method to check whether each value is an integer:
- For âvalue1â (42), âNumber.isInteger()â returns âtrueâ because it's an integer
- For âvalue2â (3.14), âNumber.isInteger()â returns âfalseâ because it's not an integerâit contains a fraction
Date Objects
Date objects are used to work with dates and times.
They allow you to create, manipulate, and format date and time values in your JavaScript code.
Some common methods include:
getDate() Method
This method retrieves the current day of the month. The day is returned as an integer, ranging from 1 to 31.
Here's how you can use the âgetDate()â method:
let currentDate = new Date();
let dayOfMonth = currentDate.getDate();
console.log(`Day of the month: ${dayOfMonth}`);In this example, âcurrentDateâ is a âdateâ object representing the current date and time.
We then use the âgetDate()â method to retrieve the day of the month and store it in the âdayOfMonthâ variable.Â
Finally, we display the day of the month using âconsole.log().â
getDay() Method
This method retrieves the current day of the week.
The day is returned as an integer, with Sunday being 0, Monday being 1, and so on. Up to Saturday being 6.
Sample code:
let currentDate = new Date();
let dayOfWeek = currentDate.getDay();
console.log(`Day of the week: ${dayOfWeek}`);Here, âcurrentDateâ is a date object representing the current date and time.Â
We then use the âgetDay()â method to retrieve the day of the week and store it in the âdayOfWeekâ variable.Â
Finally, we display the day of the week using âconsole.log().â
getMinutes()Method
This method retrieves the minutes portion from the present date and time.
The minutes will be an integer value, ranging from 0 to 59.
Sample code:
let currentDate = new Date();
let minutes = currentDate.getMinutes();
console.log(`Minutes:Â ${minutes}`);In this example, âcurrentDateâ is a âdateâ object representing the current date and time.Â
We use the âgetMinutes()â method to retrieve the minutes component and store it in the minutes variable.Â
Finally, we display the minutes using âconsole.log().â
getFullYear() Method
This method retrieves the current year. Itâll be a four-digit integer.
Hereâs some sample code:
let currentDate = new Date();
let year = currentDate.getFullYear();
console.log(`Year:Â ${year}`);Here, âcurrentDateâ is a date object representing the current date and time.Â
We use the âgetFullYear()â method to retrieve the year and store it in the year variable.Â
We then use âconsole.log()â to display the year.
setDate() Method
This method sets the day of the month. By changing the day of the month value within the âdateâ object.
Sample code:
let currentDate = new Date();
currentDate.setDate(15);
console.log(`Updated date: ${currentDate}`);In this example, âcurrentDateâ is a âdateâ object representing the current date and time.Â
We use the âsetDate()â method to set the day of the month to 15. And the âdateâ object is updated accordingly.Â
Lastly, we display the updated date using âconsole.log().â
How to Identify JavaScript Issues
JavaScript errors are common. And you should address them as soon as you can.
Even if your code is error-free, search engines may have trouble rendering your website content correctly. Which can prevent them from indexing your website properly.
As a result, your website may get less traffic and visibility.
You can check to see if JS is causing any rendering issues by auditing your website with Semrushâs Site Audit tool.
Open the tool and enter your website URL. Then, click âStart Audit.â

A new window will pop up. Here, set the scope of your audit.Â

After that, go to âCrawler settingsâ and enable the âJS renderingâ option. Then, click âStart Site Audit.â

The tool will start auditing your site. After the audit is complete, navigate to the âJS Impactâ tab.
Youâll see whether certain elements (links, content, title, etc.) are rendered differently by the browser and the crawler.

For your website to be optimized, you should aim to minimize the differences between the browser and the crawler versions of your webpages.Â
This will ensure that your website content is fully accessible and indexable by search engines .
To minimize the differences, you should follow the best practices for JavaScript SEO and implement server-side rendering (SSR).
Even Google recommends doing this.
Why?Â
Because SSR minimizes the disparities between the version of your webpages that browser and search engines see.
You can then rerun the audit to confirm that the issues are resolved.
Get Started with JavaScript
Learning how to code in JavaScript is a skill. Itâll take time to master it.
Thankfully, weâve put together a handy cheat sheet to help you learn the basics of JavaScript and get started with your coding journey.
You can download the cheat sheet as a PDF file or view it online.Â
We hope this cheat sheet will help you get familiar with the JavaScript language. And boost your confidence and skills as a coder.
