JavaScript is a programming language that’s used to create dynamic content on websites.
Take a moment to think about the web features you use every day. Think about how new content loads when you keep scrolling on Twitter, or how YouTube updates when you click on the like
button. This is JavaScript at work. JavaScript can be used to create interactive forms, animate images, create responsive elements, and more depending on your needs.
When you’re developing a website, there are three main web technologies you’ll use: HTML
, CSS
, and JavaScript
. You will use HTML
to determine the structure of a webpage, and CSS
to control how a web page appears. JavaScript
is the third element of web development that you can use to make your site dynamic.
And that’s not all JavaScript can do. If you want to build more than a static web page, you’ll want to use JS. But JavaScript can also be used in back-end web development, or to develop games, or to create mobile applications.
In this guide, we are going to break down some of the most common operations you may encounter as you learn JavaScript. We’ll discuss JavaScript fundamentals, including substrings, testing your code with try...catch
blocks, using if statements, and more. After we’ve covered the basics, we’ll also go onto explore some more advanced JavaScript functions.
If you have just started to learn JavaScript and are looking for an introductory tutorial, look no further than this guide! We have provided a list of some of the best online JavaScript courses to help you. Let’s start exploring some of the most common operations in JavaScript.
JavaScript Filter and Reduce
When you’re working with an array in JavaScript, you may want to filter your objects or run a calculation on items within the array. That’s where the filter()
and reduce()
functions come in, respectively.
The filter()
function can be used to get values that meet particular criteria from an array. Here’s an example of a filter function that returns all students in First Grade
:
var firstGradeStudents = students.filter(function (student) { return student.class === “First Grade”; });
The reduce()
method can be used to reduce an array down to a single value. For example, if we want to get the total age of students in a class, we could use this code:
var firstGradeStudents = students.filter(function (student) { return student.class === “First Grade”; });
Check out our full guide on these functions to learn more about how they work, and how you can use them in your code.
JavaScript String Contains
Strings are used in programming to display and work with text. When you’re working with a string, you may want to check whether or not that string contains a certain value. For example, you may want to check whether or not someone’s name contains Jones
.
You can use the built-in includes()
method in JavaScript to check whether a string contains a substring. Here’s an example of the includes()
method being used to check if a string contains a substring:
let str = “Example String!”; let ourSubstring = “Example”; str.includes(ourSubstring);
JavaScript Split and Slice
Often, you may have a string that you want to split up into a substring or an array. To do this, you can use the split()
and slice()
JavaScript functions.
The split()
function allows you to split a string into an array. For example, if you wanted to convert a user’s full name into an array of strings, you could use the split()
function. Here’s an example of split()
in action:
var fullName = “Forename Surname”; var fullNameSplit = fullName.split(“ “); console.log(fullNameSplit);
The slice()
method returns all characters between two index numbers in a string, allowing you to create a substring. Here’s an example of slice in action:
"John Appleseed".slice(5, 10);
JavaScript Splice
The JavaScript splice()
method can be used to add or remove an item from any place within an array. For example, if you have a list of employee names and you want to remove the second one on the list, you could use splice()
.
Here’s an example of splice()
being used to remove the name Paul
, which has the index value 3
, from an array:
var students = [“Alex”, “Fred”, “Molly”, “Paul”] students.splice(3, 1); console.log(students);
JavaScript Substring
The substring()
JavaScript method allows you to extract parts of a string and create a substring out of those parts. For example, if you wanted to get the last two characters in someone’s surname, you could use the substring()
method.
Here’s an example of substring being used to remove the first two characters from a string:
const catName = “Pickles”; const newCatName = catName.substring(2); console.log(newCatName);
JavaScript Try Catch
Every developer makes mistakes when they are coding, and it’s very important to make sure that if an error appears, it’s handled appropriately. Try/catch blocks are used in JavaScript to handle errors.
When a try/catch block is used, your code will be run and will return a custom response if an error is encountered in your code. Here is an example of a try/catch procedure in action:
try { // Your code here console.log("The code works!"); } catch (e) { console.log("There is a problem in my code!"); }
JavaScript If Else
Conditional statements are used when you want code to run only when a certain set of criteria are met. For example, you may want your program to print out a user’s name if they have entered a valid name and return a message to the user in the web browser if their name is invalid.
The if/else
statement can be used to run certain code if a statement is true, and run a different block of code if a statement is false. Here’s the syntax of an if/else
statement:
if (ourCondition) { // Code will execute if the condition is true } else { // Code will execute if the condition is false }
JavaScript String Replace
The JavaScript replace()
function can be used to replace certain characters—or sequences of characters—in a string of text. For example, you could use replace()
to change every occurrence of a user’s email address in a string if the user has changed their email.
Here’s an example of how you can use replace()
in JavaScript to replace text:
var ourInterestingString = "This string is interesting."; var ourIntriguingString = ourInterestingString.replace("interesting", "intriguing"); console.log(ourIntriguingString);
JavaScript Onclick
When you’re creating a webpage, you may want an element to do something when a user clicks on it. For example, you may want a user to receive a message if they click on a button, or for an image to enlarge it’s clicked. That’s where the onclick()
function comes in.
The onclick()
event allows you to make a web page interactive so that if a user clicks on an element, something will happen. Read our guide on the onclick()
event to learn more about how it works and how you can use it in your code.
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
JavaScript Sort Array
When you’re working with an array, you may decide that you want to order the array in a particular way. For example, you may want to order a list of names in alphabetical order, or a list of grades in ascending order.
The JavaScript sort()
function can be used to arrange an array in a particular way. Here’s an example of the sort()
function being used to arrange an array of student names in alphabetical order:
var students = ['Alex', 'Cathy', 'Lincoln', 'Jeff']; var sorted_students = students.sort(); console.log(sorted_students);
The sort()
function can also be used to perform advanced sorts if you define a custom function within the sort.
JavaScript Ternary Operator
JavaScript ternary operators are if...else
statements that check if a condition is met, and run a block of code. For example, if you want to check a user’s age and return true
if they are over 18 and false
if they are under 18, you could use a ternary operator.
Ternary operators are often used in place of simple if...else
statements because they are compact and fit on one line.
Here’s the syntax for a ternary operator in JavaScript:
(condition) ? if true, then run : if false, then run
JavaScript forEach
When you’re programming in JavaScript, you may want to loop through all the items within a list. For example, you may have a list of supplier names that you want to print out to the user. You can use the forEach
loop to build this function.
A forEach
loop is a form of for
loop that executes a function once on each item in an array. Here’s the syntax for a forEach
statement that loops through a list of companies and prints each one out on a new line:
const companies = ['Apple', 'Google', 'Facebook']; companies.forEach(company => { console.log(company); });
JavaScript Functions
Functions, which are part of most major programming languages, allow you to write code once for common processes and use that code multiple times within your program.
For example, if you have a block of code that checks if a form field is valid, you may want to make it a function, so you don’t have to repeat a block of code for every form field on a web page.
Here’s an example of a function in JavaScript:
function printGoogle() { console.log("Google"); }
By itself, our function does not do anything, but when we call it, the function will print out Google
to the console. To call our function, we use the following code:
printGoogle();
JavaScript Let
The JavaScript let
keyword is used to declare a block-scope, local variable that can be reassigned. Unlike var
variables, let
variables can only be accessed in a certain block of code, but they can be reassigned like var
variables.
Declaring a variable using let
works in the same way as var
:
let name = "John Appleseed";
Read our full article on JavaScript let
to learn about the differences between var
, const
, and let
, along with how to use them all correctly.
JavaScript Array Push
When you’re working with an array, you may want to add an item to that array. That’s where the JavaScript push()
method comes in. You can use push()
to add an item to the end of an array. Here’s an example of the push()
method being used:
var fruits = ["Melon", "Apple", "Strawberry", "Banana"]; fruits.push("Avocado"); console.log(fruits);
Output:
["Melon", "Apple", "Strawberry", "Banana", "Avocado"]
You can also use unshift()
to add an item to the start of an array. unshift()
works in the same way as push()
, and accepts the same argument.
Conclusion
JavaScript is a programming language used to create dynamic web pages. In this guide, we have discussed a number of the most common JavaScript operations used by beginners. We’ve covered everything from the onClick
function to replacing strings, to slicing data based on your needs.
This handbook isn’t just for beginners, though. As you continue your journey learning JavaScript, you should keep coming back to this guide and use it to help you if you get lost. We’ll keep this article updated so that if you have a question about a common JavaScript operation, you’ll be likely to find it here.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.