JavaScript Tutorial for Beginners

JavaScript Tutorial for Beginners
Photo by Pankaj Patel / Unsplash

JavaScript is the programming language of the web. JavaScript can add interactivity and functionality to HTML elements, such as animations, events, forms, etc. JavaScript is versatile and beginner-friendly. With more experience, you’ll be able to create games, animated 2D and 3D graphics, comprehensive database-driven apps, and much more!

Related prerequsites (optional, but recommended):

HTML Tutorial for Beginners
HTML stands for HyperText Markup Language. It is the standard language for creating web pages and web applications. HTML describes the structure and content of a web page using tags and attributes. Tags are keywords that define different elements in a web page, such as headings, paragraphs, images, links, etc.
CSS Tutorial for Beginners
CSS stands for Cascading Style Sheets. It is the language that defines the style and layout of HTML elements, such as colors, fonts, borders, backgrounds, etc. CSS can make your web pages more attractive and interactive, as well as adapt to different devices and screen sizes. Prerequsite: HTML Tutorial for

JavaScript Syntax

A JavaScript document consists of one or more statements. A statement is a command or instruction that tells the browser what to do. A statement usually ends with a semicolon (;), but there's actually no need to end it with ;' anymore. For example, console.log("Hello, world!"); is a statement that prints the message “Hello, world!” to the browser console.

A JavaScript document can also have one or more comments. A comment is a note or explanation that is ignored by the browser and does not affect the output of the document. You can use comments to add notes or descriptions to your code. You can create a comment by using the syntax // comment for a single-line comment, or /* comment */ for a multi-line comment. For example, // This is a comment or /* This is also a comment */.

A JavaScript document can also have one or more variables. A variable is a container that holds a value that can be changed or accessed later. You can use variables to store data or information that you want to use in your code. You can create a variable by using the keyword varlet, or const, followed by the name of the variable. For example, const name = "John"; creates a variable named name and assigns the value “John” to it.

💡
Never use var and only prefer const or let - var is an old style variable and should be avoided nowadays

A JavaScript document can also have one or more data types. A data type is a category of values that have certain characteristics or behaviors. JavaScript has several built-in data types, such as:

  • String: A string is a sequence of characters, such as text or words. You can create a string by enclosing the characters in single or double quotes. For example, "Hello" or 'World' are strings.
  • Number: A number is a numerical value, such as integers or decimals. You can create a number by writing the digits without quotes. For example, 42 or 3.14 are numbers.
  • Boolean: A boolean is a logical value, either true or false. You can create a boolean by using the keywords true or false. For example, true or false are booleans.
  • Undefined: Undefined is a special value that indicates the absence of a value. You can create an undefined value by using the keyword undefined. For example, undefined is undefined.
  • Null: Null is another special value that indicates the absence of a value. You can create a null value by using the keyword null. For example, null is null.

There are also other data types, such as arraysobjectsfunctions, etc. that you can learn more about later.

Here is an example of a simple JavaScript document with some statements, comments, variables, and data types:

// This is a JavaScript document

// Declare a variable named name and assign a string value to it
const name = "John";

// Declare a variable named age and assign a number value to it
const age = 25;

// Declare a variable named isMarried and assign a boolean value to it
const isMarried = false;

// Print the values of the variables to the console
console.log(name); // John
console.log(age); // 25
console.log(isMarried); // false

JavaScript Linking

To use JavaScript in your HTML document, you need to link the JavaScript document to the HTML document. There are two different ways to do that, but the most common and recommended way is to use an external script. An external script is a separate JavaScript file that can be linked to one or more HTML files. This way, you can keep your HTML and JavaScript code separate and organized, as well as reuse the same JavaScript file for multiple web pages.

To link an external script to your HTML document, you need to use the <script> element in the <head> or <body> section of your HTML document. The <script> element has one attribute: src. The src attribute specifies the location or URL of the script file. The value of this attribute should be the name or path of your JavaScript file.

Here is an example of linking an external script to an HTML document:

<!DOCTYPE html>
<html>
<head>
  <title>My First Web Page</title>
  <script src="scripts/main.js"></script> <!-- Link the script file in the head section -->
</head>
<body>
  <!-- Your HTML content goes here -->
</body>
</html>

This HTML document links to a JavaScript file named main.js in the scripts folder. You can also use relative or absolute paths to link to JavaScript files in different folders or locations.

JavaScript Examples

To see how JavaScript works in action, let’s look at some examples of using JavaScript to create interactivity and functionality in your web page. You can use our online editor below to edit the JavaScript code and see the result in the browser.

Example 1: Changing text

One of the most basic things you can do with JavaScript is to change the text of an HTML element. You can use the document.getElementById() method to select an element by its id attribute, and the innerHTML property to change the content of the element. For example, document.getElementById("demo").innerHTML = "Hello, world!"; changes the text of the element with id="demo" to “Hello, world!”.

Here is an example of changing the text of an HTML element with JavaScript:

<!DOCTYPE html>
<html>
<head>
  <title>My First Web Page</title>
  <script src="scripts/main.js"></script>
</head>
<body>
  <h1 id="demo">This is a heading</h1>
  <button onclick="changeText()">Click me</button>
</body>
</html>
// This is the script file

// Define a function that changes the text of the heading element
function changeText() {
  document.getElementById("demo").innerHTML = "Hello, world!";
}

This HTML document has a heading element with id="demo" and a button element with an onclick attribute. The onclick attribute specifies a JavaScript code that runs when the button is clicked. In this case, the code is changeText(), which is the name of the function defined in the script file. The function changes the text of the heading element to “Hello, world!” by using the document.getElementById() method and the innerHTML property.

Example 2: Changing style

Another thing you can do with JavaScript is to change the style of an HTML element. You can use the style property to access and modify the CSS properties of an element. For example, document.getElementById("demo").style.color = "red"; changes the text color of the element with id="demo" to red.

Here is an example of changing the style of an HTML element with JavaScript:

<!DOCTYPE html>
<html>
<head>
  <title>My First Web Page</title>
  <script src="scripts/main.js"></script>
</head>
<body>
  <h1 id="demo">This is a heading</h1>
  <button onclick="changeStyle()">Click me</button>
</body>
</html>
// This is the script file

// Define a function that changes the style of the heading element
function changeStyle() {
  document.getElementById("demo").style.color = "red";
  document.getElementById("demo").style.fontSize = "36px";
  document.getElementById("demo").style.fontWeight = "bold";
}

This HTML document has a heading element with id="demo" and a button element with an onclick attribute. The onclick attribute specifies a JavaScript code that runs when the button is clicked. In this case, the code is changeStyle(), which is the name of the function defined in the script file. The function changes the style of the heading element by using the style property and modifying the colorfontSize, and fontWeight properties.

Events

JavaScript events are actions or occurrences that happen in the browser, such as when a user clicks a button, moves the mouse, presses a key, etc. You can use JavaScript events to execute JavaScript code when an event occurs, such as changing the style or content of an HTML element, validating a form input, creating an animation, etc.

To use JavaScript events, you need to specify two things: the event and the event handler. The event is the type of action or occurrence that you want to respond to, such as clickmouseoverkeydown, etc. The event handler is the JavaScript code or function that runs when the event occurs. You can use the addEventListener() method to attach an event handler to an element, or use the HTML on attributes to specify an event handler inline. For example, document.getElementById("demo").addEventListener("click", changeText); attaches a click event handler to the element with id="demo", and <button onclick="changeText()">Click me</button> specifies a click event handler inline.

Here is an example of using JavaScript events to create interactivity and functionality in your web page:

<!DOCTYPE html>
<html>
<head>
  <title>My First Web Page</title>
  <script src="scripts/main.js"></script>
</head>
<body>
  <h1 id="demo">This is a heading</h1>
  <button id="btn">Click me</button>
</body>
</html>
// This is the script file

// Define a function that changes the text and style of the heading element
function changeText() {
  document.getElementById("demo").innerHTML = "Hello, world!";
  document.getElementById("demo").style.color = "red";
  document.getElementById("demo").style.fontSize = "36px";
  document.getElementById("demo").style.fontWeight = "bold";
}

// Attach a click event handler to the button element
document.getElementById("btn").addEventListener("click", changeText);

This HTML document has a heading element with id="demo" and a button element with id="btn". The script file defines a function named changeText that changes the text and style of the heading element. It also attaches a click event handler to the button element, which calls the changeText function when the button is clicked.

JavaScript Arithmetic Operators

Arithmetic operators are operators that perform mathematical calculations on numbers, such as addition, subtraction, multiplication, division, etc. You can use arithmetic operators to perform basic or complex calculations in your code. Here are some of the most common arithmetic operators in JavaScript:

  • +: This operator adds two numbers together. For example, 2 + 3 returns 5.
  • -: This operator subtracts one number from another. For example, 5 - 2 returns 3.
  • *: This operator multiplies two numbers together. For example, 2 * 3 returns 6.
  • /: This operator divides one number by another. For example, 6 / 2 returns 3.
  • %: This operator returns the remainder of the division of two numbers. For example, 7 % 2 returns 1.
  • **: This operator raises one number to the power of another. For example, 2 ** 3 returns 8.

Here is an example of using arithmetic operators to perform some calculations in JavaScript:

// This is the script file

// Declare some variables and assign some numbers to them
const a = 10;
const b = 5;
const c = 2;

// Print the values of the variables to the console
console.log(a); // 10
console.log(b); // 5
console.log(c); // 2

// Use arithmetic operators to perform some calculations and print the results to the console
console.log(a + b); // 15
console.log(a - b); // 5
console.log(a * b); // 50
console.log(a / b); // 2
console.log(a % b); // 0
console.log(a ** c); // 100

This JavaScript code declares three variables and assigns some numbers to them. It then prints the values of the variables to the console. It also uses arithmetic operators to perform some calculations and print the results to the console.

JavaScript Comparison Operators

Comparison operators are operators that compare two values and return true or false depending on the result of the comparison. You can use comparison operators to test the relationship between two values, such as equal, not equal, greater than, less than, etc. Here are some of the most common comparison operators in JavaScript:

  • ==: This operator tests if two values are equal, and returns true if they are, or false if they are not. For example, 2 == 2 returns true, and 2 == 3 returns false.
  • !=: This operator tests if two values are not equal, and returns true if they are, or false if they are not. For example, 2 != 3 returns true, and 2 != 2 returns false.
  • ===: This operator tests if two values are strictly equal, and returns true if they are, or false if they are not. Strict equality means that the values have the same type and value, without any type conversion. For example, 2 === 2 returns true, and 2 === "2" returns false.
  • !==: This operator tests if two values are strictly not equal, and returns true if they are, or false if they are not. Strict inequality means that the values have different types or values, without any type conversion. For example, 2 !== "2" returns true, and 2 !== 2 returns false.
  • >: This operator tests if the left value is greater than the right value, and returns true if it is, or false if it is not. For example, 3 > 2 returns true, and 2 > 3 returns false.
  • <: This operator tests if the left value is less than the right value, and returns true if it is, or false if it is not. For example, 2 < 3 returns true, and 3 < 2 returns false.
  • >=: This operator tests if the left value is greater than or equal to the right value, and returns true if it is, or false if it is not. For example, 3 >= 2 returns true, and 2 >= 3 returns false.
  • <=: This operator tests if the left value is less than or equal to the right value, and returns true if it is, or false if it is not. For example, 2 <= 3 returns true, and 3 <= 2 returns false.

Here is an example of using comparison operators to perform some comparisons in JavaScript:

// This is the script file

// Declare some variables and assign some values to them
const a = 10;
const b = 5;
const c = "10";

// Print the values of the variables to the console
console.log(a); // 10
console.log(b); // 5
console.log(c); // 10

// Use comparison operators to perform some comparisons and print the results to the console
console.log(a == b); // false
console.log(a == c); // true
console.log(a != b); // true
console.log(a != c); // false
console.log(a === b); // false
console.log(a === c); // false
console.log(a !== b); // true
console.log(a !== c); // true
console.log(a > b); // true
console.log(a < b); // false
console.log(a >= b); // true
console.log(a <= b); // false

This JavaScript code declares three variables and assigns some values to them. It then prints the values of the variables to the console. It also uses comparison operators to perform some comparisons and print the results to the console.

JavaScript Logical Operators

Logical operators are operators that perform logical operations on boolean values, such as true or false. There are three main logical operators in JavaScript:

  • &&: This operator returns true if both operands are true, and false otherwise. This is the logical AND operator. For example, true && true returns true, and true && false returns false.
  • ||: This operator returns true if either operand is true, and false otherwise. This is the logical OR operator. For example, true || false returns true, and false || false returns false.
  • !: This operator returns true if the operand is false, and false if the operand is true. This is the logical NOT operator. For example, !true returns false, and !false returns true.

Here is an example of using logical operators to perform some logical operations in JavaScript:

// This is the script file

// Declare some variables and assign some boolean values to them
const a = true;
const b = false;

// Print the values of the variables to the console
console.log(a); // true
console.log(b); // false

// Use logical operators to perform some logical operations and print the results to the console
console.log(a && b); // false
console.log(a || b); // true
console.log(!a); // false
console.log(!b); // true

JavaScript Loops

A loop is a control structure that repeats a block of code until a certain condition is met. You can use loops to perform tasks that require repetition, such as iterating over an array, counting numbers, generating patterns, etc. There are several types of loops in JavaScript, such as:

  • for loop: This loop executes a block of code for a specified number of times, or until a condition is false. You can use a for loop to iterate over a fixed range of values, such as numbers, characters, etc. A for loop has three parts: the starting value, the ending condition, and the increment or decrement. For example, for (var i = 0; i < 10; i++) { console.log(i); } creates a for loop that prints the numbers from 0 to 9 to the console.
  • while loop: This loop executes a block of code while a condition is true. You can use a while loop to iterate over an unknown or variable range of values, such as user input, random numbers, etc. A while loop has one part: the condition. For example, while (true) { console.log("Hello"); } creates a while loop that prints “Hello” to the console indefinitely.
  • do…while loop: This loop executes a block of code once, and then repeats it while a condition is true. You can use a do…while loop to iterate over an unknown or variable range of values, but ensure that the block of code is executed at least once. A do…while loop has two parts: the block of code and the condition. For example, do { console.log("Hello"); } while (false); creates a do…while loop that prints “Hello” to the console once, and then stops.

Here is an example of using loops to create some functionality in JavaScript:

<!DOCTYPE html>
<html>
<head>
  <title>My First Web Page</title>
  <script src="scripts/main.js"></script>
</head>
<body>
  <h1>JavaScript Loops</h1>
  <p id="demo"></p>
</body>
</html>
// This is the script file

// Declare a variable to store the output
let output = "";

// Use a for loop to generate a pattern of stars
for (let i = 1; i <= 5; i++) {
  for (let j = 1; j <= i; j++) {
    output += "*";
  }
  output += "<br>"; // add a line break
}

// Use a while loop to generate a random number between 1 and 10
let random = Math.floor(Math.random() * 10) + 1; // generate a random number between 1 and 10
while (random != 5) { // repeat until the random number is 5
  output += random + " is not 5<br>"; // add the random number and a message to the output
  random = Math.floor(Math.random() * 10) + 1; // generate a new random number
}
output += random + " is 5<br>"; // add the final random number and a message to the output

// Use a do...while loop to ask the user for their name
let name = ""; // declare a variable to store the user's name
do {
  name = prompt("What is your name?"); // ask the user for their name
} while (name == "" || name == null); // repeat until the user enters a valid name
output += "Hello, " + name + "!"; // add a greeting to the output

// Display the output in the HTML document
document.getElementById("demo").innerHTML = output;

This HTML document has a heading element and a paragraph element with id="demo". The script file declares a variable named output to store the output of the loops. It then uses a for loop to generate a pattern of stars, a while loop to generate a random number, and a do…while loop to ask the user for their name. It then displays the output in the paragraph element.

JavaScript if…else Statement

The if…else statement is the most basic conditional statement in JavaScript. It executes a block of code if a condition is true, and another block of code if the condition is false. You can use the if…else statement to perform simple or complex tests in your code, such as checking equality, inequality, greater than, less than, etc. The syntax of the if…else statement is:

if (condition) {
  // code to execute if the condition is true
} else {
  // code to execute if the condition is false
}

The condition is a boolean expression that evaluates to true or false. The code inside the curly braces {} is the block of code that is executed depending on the condition. The else part is optional, and can be omitted if there is no code to execute if the condition is false.

Here is an example of using the if…else statement to perform a simple test in JavaScript:

// This is the script file

// Declare a variable and assign a number to it
let age = 18;

// Use the if...else statement to check if the age is greater than or equal to 18
if (age >= 18) {
  // Print a message to the console if the condition is true
  console.log("You are an adult.");
} else {
  // Print a message to the console if the condition is false
  console.log("You are a minor.");
}

This JavaScript code declares a variable named age and assigns a number to it. It then uses the if…else statement to check if the age is greater than or equal to 18. If the condition is true, it prints “You are an adult.” to the console. If the condition is false, it prints “You are a minor.” to the console.

JavaScript switch statement

The switch statement is a conditional statement that evaluates an expression and compares it with multiple cases. It executes a block of code that matches the case, and optionally a default block of code if no case matches. You can use the switch statement to perform multiple tests in your code, such as checking equality, cases, options, etc. The syntax of the switch statement is:

switch (expression) {
  case value1:
    // code to execute if the expression matches value1
    break;
  case value2:
    // code to execute if the expression matches value2
    break;
  ...
  default:
    // code to execute if no case matches
    break;
}

The expression is a value or variable that is compared with the cases. The cases are values or expressions that are compared with the expression. The code inside the curly braces {} is the block of code that is executed depending on the case. The break statement is used to end the execution of the switch statement and prevent it from falling through to the next case. The default case is optional, and can be used to specify a block of code to execute if no case matches.

Here is an example of using the switch statement to perform a simple test in JavaScript:

// This is the script file

// Declare a variable and assign a string to it
let day = "Monday";

// Use the switch statement to check the value of the variable
switch (day) {
  case "Monday":
    // Print a message to the console if the case is Monday
    console.log("Today is Monday. Ugh!");
    break;
  case "Tuesday":
    // Print a message to the console if the case is Tuesday
    console.log("Today is Tuesday. That means Taco Tuesday!");
    break;
  case "Wednesday":
    // Print a message to the console if the case is Wednesday
    console.log("Today is Wednesday. Middle of the work week!");
    break;
  case "Thursday":
    // Print a message to the console if the case is Thursday
    console.log("Today is Thursday. That's almost Friday!");
    break;
  case "Friday":
    // Print a message to the console if the case is Friday
    console.log("Today is Friday, Friday!");
    break;
  case "Saturday":
    // Print a message to the console if the case is Saturday
    console.log("Today is Saturday. The best day.");
    break;
  case "Sunday":
    // Print a message to the console if the case is Sunday
    console.log("Today is Sunday. The day before Monday :(");
    break;
  default:
    // Print a message to the console if no case matches
    console.log("Invalid day.");
    break;
}

This JavaScript code declares a variable named day and assigns a string to it. It then uses the switch statement to check the value of the variable. If the value matches one of the cases, it prints a message to the console. If the value does not match any of the cases, it prints a default message to the console. 

JavaScript Function Declaration

A function declaration is a statement that defines a function in JavaScript. It consists of the keyword function, followed by the name of the function, followed by a pair of parentheses (), followed by a pair of curly braces {}. The parentheses () can contain one or more parameters, which are variables that receive the values passed to the function when it is called. The curly braces {} contain the body of the function, which is the block of code that is executed when the function is called. The syntax of a function declaration is:

function name(parameter1, parameter2, ...) {
  // code to execute
}

Here is an example of a function declaration in JavaScript:

// This is the script file

// Declare a function named add that takes two parameters and returns their sum
function add(a, b) {
  return a + b;
}

This JavaScript code declares a function named add that takes two parameters named a and b, and returns their sum. The return statement is used to specify the value that the function returns to the caller.

JavaScript Function Expression

A function expression is an expression that defines a function in JavaScript. It consists of the keyword function, followed by an optional name of the function, followed by a pair of parentheses (), followed by a pair of curly braces {}. The parentheses (), the parameters, and the body of the function are the same as in a function declaration. The difference is that a function expression is not a statement, but a value that can be assigned to a variable, passed as an argument, or returned from another function. The syntax of a function expression is:

var name = function(parameter1, parameter2, ...) {
  // code to execute
};

Here is an example of a function expression in JavaScript:

// This is the script file

// Assign a function expression to a variable named multiply that takes two parameters and returns their product
var multiply = function(a, b) {
  return a * b;
};

This JavaScript code assigns a function expression to a variable named multiply that takes two parameters named a and b, and returns their product. The function expression does not have a name, so it is called an anonymous function.

JavaScript Function Call

A function call is an expression that invokes or executes a function in JavaScript. It consists of the name of the function, followed by a pair of parentheses (). The parentheses () can contain one or more arguments, which are values that are passed to the function when it is called. The function call evaluates to the value that the function returns, or undefined if the function does not return anything. The syntax of a function call is:

name(argument1, argument2, ...);

Here is an example of a function call in JavaScript:

// This is the script file

// Declare a function named add that takes two parameters and returns their sum
function add(a, b) {
  return a + b;
}

// Assign a function expression to a variable named multiply that takes two parameters and returns their product
var multiply = function(a, b) {
  return a * b;
};

// Call the add function with two arguments and print the result to the console
console.log(add(2, 3)); // 5

// Call the multiply function with two arguments and print the result to the console
console.log(multiply(2, 3)); // 6

This JavaScript code declares a function named add and assigns a function expression to a variable named multiply. It then calls the add and multiply functions with two arguments each, and prints the results to the console. 

JavaScript Array Creation

An array is a collection of values that are ordered and indexed. You can create an array by using the array literal syntax, which consists of a pair of square brackets [], and optionally one or more values separated by commas ,. For example, var fruits = ["apple", "banana", "orange"]; creates an array named fruits and assigns three values to it.

You can also create an array by using the array constructor syntax, which consists of the keyword new, followed by the name of the array object Array, followed by a pair of parentheses (). The parentheses () can contain one or more arguments, which can be either the length of the array, or the values of the array. For example, var numbers = new Array(10); creates an array named numbers and assigns a length of 10 to it.

Here is an example of creating arrays in JavaScript:

// This is the script file

// Create an array using the array literal syntax
let fruits = ["apple", "banana", "orange"];

// Create an array using the array constructor syntax
let numbers = new Array(10);

// Print the arrays to the console
console.log(fruits); // ["apple", "banana", "orange"]
console.log(numbers); // [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]

This JavaScript code creates two arrays using different syntaxes. It then prints the arrays to the console.

JavaScript Array Methods

An array method is a function that is attached to the array object and can be called on any array. You can use the dot notation . to access and invoke an array method. For example, fruits.push("mango"); calls the push method on the fruits array and adds the value “mango” to the end of the array.

There are many array methods in JavaScript, each with a specific purpose and functionality. Here are some of the most common and useful array methods in JavaScript:

  • push(): This method adds one or more elements to the end of an array and returns the new length of the array. For example, fruits.push("mango", "kiwi"); adds “mango” and “kiwi” to the end of the fruits array and returns 5.
  • pop(): This method removes the last element from an array and returns that element. For example, fruits.pop(); removes “orange” from the end of the fruits array and returns "orange".
  • shift(): This method removes the first element from an array and returns that element. For example, fruits.shift(); removes “apple” from the beginning of the fruits array and returns "apple".
  • unshift(): This method adds one or more elements to the beginning of an array and returns the new length of the array. For example, fruits.unshift("strawberry", "watermelon"); adds “strawberry” and “watermelon” to the beginning of the fruits array and returns 6.
  • splice(): This method adds or removes elements from an array at a specified index and returns the removed elements. For example, fruits.splice(2, 1, "pineapple"); removes one element from the fruits array at index 2 and replaces it with “pineapple”, and returns ["banana"].
  • slice(): This method returns a shallow copy of a portion of an array into a new array. For example, fruits.slice(1, 3); returns a new array with the elements from index 1 to index 2 of the fruits array, which is ["banana", "pineapple"].
  • sort(): This method sorts the elements of an array in place and returns the sorted array. For example, fruits.sort(); sorts the fruits array in ascending alphabetical order and returns ["apple", "banana", "kiwi", "mango", "orange", "pineapple"].
  • reverse(): This method reverses the order of the elements of an array in place and returns the reversed array. For example, fruits.reverse(); reverses the order of the fruits array and returns ["pineapple", "orange", "mango", "kiwi", "banana", "apple"].
  • concat(): This method returns a new array that is the result of concatenating two or more arrays. For example, var vegetables = ["carrot", "potato", "onion"]; and var salad = fruits.concat(vegetables); returns a new array that is the combination of the fruits and vegetables arrays, which is ["apple", "banana", "pineapple", "orange", "mango", "kiwi", "carrot", "potato", "onion"].
  • join(): This method returns a string that is the result of joining the elements of an array with a specified separator. For example, fruits.join(", "); returns a string that is the combination of the fruits array elements with a comma and a space as the separator, which is "apple, banana, pineapple, orange, mango, kiwi".
  • indexOf(): This method returns the first index at which a given element can be found in an array, or -1 if it is not present. For example, fruits.indexOf("banana"); returns 1, which is the index of “banana” in the fruits array, and fruits.indexOf("pear"); returns -1, which means “pear” is not in the fruits array.
  • lastIndexOf(): This method returns the last index at which a given element can be found in an array, or -1 if it is not present. For example, fruits.lastIndexOf("banana"); returns 1, which is the last index of “banana” in the fruits array, and fruits.lastIndexOf("pear"); returns -1, which means “pear” is not in the fruits array.
  • includes(): This method returns a boolean value that indicates whether an array includes a certain element or not. For example, fruits.includes("banana"); returns true, which means “banana” is in the fruits array, and fruits.includes("pear"); returns false, which means “pear” is not in the fruits array.
  • find(): This method returns the first element in an array that satisfies a given testing function, or undefined if no element satisfies the function. For example, fruits.find(function(element) { return element.length > 5; }); returns "banana", which is the first element in the fruits array that has a length greater than 5, and fruits.find(function(element) { return element.length > 10; }); returns undefined, which means no element in the fruits array has a length greater than 10.
  • filter(): This method returns a new array with the elements that pass a given testing function. For example, fruits.filter(function(element) { return element.length > 5; }); returns a new array with the elements in the fruits array that have a length greater than 5, which is ["banana", "pineapple", "orange", "mango"].
  • map(): This method returns a new array with the results of calling a given function on every element in the array. For example, fruits.map(function(element) { return element.toUpperCase(); }); returns a new array with the elements in the fruits array converted to uppercase, which is ["APPLE", "BANANA", "PINEAPPLE", "ORANGE", "MANGO", "KIWI"].
  • reduce(): This method returns a single value that is the result of applying a given function to each element in the array and accumulating the result. For example, numbers.reduce(function(accumulator, element) { return accumulator + element; }); returns the sum of the elements in the numbers array, which is 55.

Here is an example of using array methods to manipulate and process arrays in JavaScript:

<!DOCTYPE html>
<html>
<head>
  <title>My First Web Page</title>
  <script src="scripts/main.js"></script>
</head>
<body>
  <h1>JavaScript Array Methods</h1>
  <p id="demo"></p>
</body>
</html>
// This is the script file

// Create an array using the array literal syntax
let fruits = ["apple", "banana", "orange", "mango", "kiwi"];

// Create an array using the array constructor syntax
let numbers = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// Declare a variable to store the output
let output = "";

// Use array methods to manipulate and process the arrays and add the results to the output
output += "The fruits array is: " + fruits.join(", ") + "<br>";
output += "The numbers array is: " + numbers.join(", ") + "<br>";
output += "The length of the fruits array is: " + fruits.length + "<br>";
output += "The length of the numbers array is: " + numbers.length + "<br>";
output += "The first element of the fruits array is: " + fruits[0] + "<br>";
output += "The last element of the fruits array is: " + fruits[fruits.length - 1] + "<br>";
output += "The third element of the numbers array is: " + numbers[2] + "<br>";
output += "The ninth element of the numbers array is: " + numbers[8] + "<br>";
output += "Adding 'pineapple' to the end of the fruits array: " + fruits.push("pineapple") + "<br>";
output += "Removing 'kiwi' from the end of the fruits array: " + fruits.pop() + "<br>";
output += "Adding 'strawberry' and 'watermelon' to the beginning of the fruits array: " + fruits.unshift("strawberry", "watermelon") + "<br>";
output += "Removing 'apple' from the beginning of the fruits array: " + fruits.shift() + "<br>";
output += "Replacing 'banana' with 'pear' in the fruits array: " + fruits.splice(1, 1, "pear") + "<br>";

Conclusion

This is the end of the JavaScript tutorial for beginners. I hope you learned something new and useful about JavaScript! It's the workhorse of the web and introduces all of the interaction (minus CSS, of course).

There's a lot more to this topic, such as TypeScript, UI libraries, JS bundlers, UI frameworks (React, Svelte, Vue, Angular etc), tests, as well as JavaScript outside of the web (Node)! Once you're comfortable, be sure to look those up! 😊

Read more