The Online Coding & Design School With A

  • Entry Level Tech Jobs
  • Front End Developer
  • Full Stack Developer
  • UI/UX Designer
  • Learn to Code
  • Get Hired in Tech

21 Easy JavaScript Projects for Beginners (Code included!)

Looking to get some practice with JavaScript or to build your portfolio to impress hiring managers? You can level up your JavaScript skills with our instructor approved, curated project tutorials.

21 JavaScript Projects for Beginners (Code included!)

According to the 2023 Stack Overflow Developer Survey, JavaScript has spent eleven years in a row as the most commonly used programming language, with 66% of developers using it extensively. If you’re interested in becoming a web developer ( front end, back end, or full stack ), JavaScript is one of the best programming languages you can learn. One way to do that is to do some JavaScript projects for beginners.

Vanilla JavaScript, also known as “plain” JavaScript — meaning without any frameworks — is one of the foundations of coding and web development. Most web pages you see are built using a combination of HTML, CSS, vanilla JavaScript, and API calls.

Getting familiar with JavaScript basics means using those JavaScript skills to build JavaScript practice projects. Luckily, we know some fun JavaScript beginner projects you can do to hone your skills from the thousands of students we’ve trained in our front end development job training program, Break into Tech .

What we see with our successful students who have landed jobs at companies like GoDaddy, Toast, Asics Digital, 1Password, Figure and Apple is that they all have JavaScript practice projects, portfolios that show off their front end developer skills , and are very well versed in JavaScript. Doing JavaScript projects for beginners is a great way to get some practice and build your portfolio.

If you want to practice your front end developer skills, we’ve put together a list of 20+ JavaScript beginner projects you can start working on right now. When you find a JavaScript practice project that piques your interest, follow the project link. Each of these open source JavaScript projects for beginners (and above) have their source code listed on their homepage for you to use as a guide.

Lisa Savoie, one of Skillcrush’s JavaScript instructors, recommends reading the source code out loud to understand it better, looking for features to incorporate into other projects , or even retyping it to work on your muscle memory of how to write functions, variables, and loops.

She says, “You can Google methods you’re unfamiliar with to learn more about them or even break the code and fix it — It’s fun to break things😀.”

Table of Contents

  • JavaScript Projects Common Mistakes
  • Beginner JavaScript Projects
  • Mouseover Element
  • Magic 8 Ball
  • Build a To-Do List
  • Epic Mix Playlist
  • Speech Detection
  • Sticky Navigation
  • Geolocation

Intermediate JavaScript Projects

  • Election Map
  • Login Authentication
  • Guess the Word
  • Terminalizer
  • Tic Tac Toe Game
  • Hotel Booking App
  • Advanced JavaScript Project

woman in glasses with hand on face, thinking

Want to learn to code? Join our FREE Coding Camp!

You Will Learn: HTML & CSS JavaScript User Experience Design Python—the language of AI 🤖 PLUS How to decide what tech job role is right for you!

LET'S GO

JavaScript Beginner Projects Common Mistakes

  • Read what the console is telling you, especially if you keep getting error messages
  • Are you working with the right type of variable? Is var, let, or const the right choice?
  • Is your logic sound? Are you properly using your array methods (when those are appropriate)?
  • Are you factoring in edge cases like empty inputs or negative integers?
  • Are you passing the right kind/type of argument to a function?

JavaScript Projects for Beginners

1. mouseover element.

Why do this project?

  • You’ll see how JavaScript functions work and practice your JavaScript logic
  • It’s a fun beginner JavaScript project to do to liven up your user experience
  • Learn more about using random, functions, and event listeners.

colorful dots on a blue background

Mouseover Element Source Code

Key concepts covered:

  • Functions and if-else statements
  • Event listeners

What to do:

  • Copy the source code from CodePen.
  • Implement the JavaScript code so that when you hover your mouse over a colored ball, it gets bigger.

Bonus Challenge:

To test your understanding of the concepts behind the mouseover element, your bonus challenge is this custom cursor project .

2. JavaScript Clock

  • You get hands-on with the kind of actual work you’ll be doing as a JavaScript developer
  • You’ll apply key JavaScript concepts and have an adorable project for your portfolio
  • Practice concepts like variables, conditional logic, and date API

lolcat meme on a Skillcrush pink background with clock elements

JavaScript Clock Source Code

  • Conditional logic
  • Program flow
  • DOM elements
  • Implement the JavaScript code so that every time you click the “Party Time!” button in the time range that you specify, you get a different LOLcat. You can set different times to see different images — there are four images total.

Bonus challenge: Now that you’ve mastered the Lolcat JavaScript clock, challenge yourself by building your own countdown timer.

3. Magic 8 Ball

  • It gives you a solid foundation for how to use Math.random to produce randomized results for JavaScript projects
  • You can use this project to impress your friends and make small life decisions
  • Learn more about how to use the random function, nested functions, and event listeners

Magic 8 Ball with hands on a light pink background

Magic 8 Ball Source Code

  • Math.random
  • Nested functions
  • Copy the source code from GitHub for HTML and CSS.
  • Implement the JavaScript code so that you can grab the 8 ball, ask it a question, shake it, and have the 8 ball respond with a somewhat enigmatic, somewhat applicable answer.

To test your understanding of the concepts behind the Magic 8 Ball, your bonus challenge is this dad joke generator.

4. To-Do List

  • You’ll beef up your skills at coding interactive lists, which lets users add, remove, and group items
  • You can use this beginner JavaScript project in your daily life and add it to your portfolio
  • Learn more about how to use arrays, nested functions, and local storage API

work to do list on a turquoise background

To-Do List Source Code

  • Local storage API
  • DOM manipulation
  • Implement the JavaScript code so that you can add new items and use the buttons to toggle completed items, edit items, or delete items.

To test your understanding of the concepts behind the To-Do list, your bonus challenge is this JavaScript grocery list.

5. Epic Mix Playlist

  • It helps you practice core JavaScript skills, such as forEach loops and event listeners, and work with functions and lists
  • You can use this project to show people looking at your portfolio your great taste in music
  • Learn more about how to classList, innerHTML, forEach, and template literals

the words "epic mix" with a "show me" button on a dark purple background

Epic Mix Playlist Source Code

  • Array loops (forEach)
  • document.createElement
  • Append to an array
  • Template literals
  • Copy the source code from CodeSandbox.
  • Implement the JavaScript code so that you can create an auto-generated list of your favorite songs and their indexes.

To test your understanding of the concepts behind the epic mix playlist, your bonus challenge is this favorite movie list.

6. Pet Rescue

  • It gives you a solid foundation for understanding factory function patterns and parameters
  • You can use this project to contribute to pet rescues or display inventory for products on a ecommerce site
  • Learn more about how to use factory functions, parameters, methods, and objects

"Sharon's Pet Rescue" text with light purple button and cat image on a white background

Pet Rescue Source Code

  • Factory functions
  • Object methods and properties
  • Implement the JavaScript code so that you can accept an animal’s name, species, and energy level as a parameter and indicate each animal’s status (whether they are sleeping or awake).

To test your understanding of the concepts behind Pet Rescue, your bonus challenge is this inventory system.

7. Drum Kit

  • You can see the interaction between seeing elements on the page and listening to sound and learning how to add and remove elements
  • You can use this project to practice your drum skills with your JavaScript skills
  • Learn more about how to use audio tags and document.querySelector

Grey keyboard letters on a white background

Drum Kit Source Code

  • Event Listener
  • document.querySelector
  • Clone the GitHub repo.
  • Implement the JavaScript code so that you can play the drums by pressing specific keys in the browser.

To test your understanding of the concepts behind the drum kit, your bonus challenge is this JavaScript piano player.

8. Speech Detection

  • It gives you a basis for understanding how speech detection works, which is good (and very cool!) to know
  • You’ll have a nifty notetaking method straight in your browser
  • Learn more about speech recognition, text content, and event listeners

white notebook paper in front of yellow background

Speech Detection Source Code

  • Window.SpeechRecognition
  • .textContent
  • Copy the source code from GitHub.
  • Implement the JavaScript code so that when you speak, whatever you say is transcribed on the lined paper on your screen.

To test your understanding of the concepts behind speech detection, your bonus challenge is this text to speech in different languages.

9. Sticky Navigation

  • It teaches you how to keep your elements in a fixed position on a page, which is a skill you might need in your front end developer role
  • You can use this to upgrade the design of your website or portfolio
  • Learn more about how to use query electors, event listeners, and offsetting

Blog header with water background on top of blog page

Sticky Navigation Source Code

  • .querySelector
  • Implement the JavaScript code so that when you scroll up or down the page, your navigation bar remains in a fixed and visible position.

To test your understanding of the concepts behind sticky navigation, your bonus challenge is to create a sliding navigation.

10. Geolocation

  • You can learn more about how to develop for mobile, how geolocation works, and how to test your code using simulators or a different device
  • You can use this project in your daily life (if you get lost easily)
  • Learn more about how to use query selectors, watch position, and coordinates

white compass on black background

Geolocation Source Code

  • .watchPosition
  • Install packages with npm and run your local server.
  • Implement the JavaScript code so that you see your location in real time. You will need iOS or an iOS simulator to test whether or not your code works.

To test your understanding of the concepts behind geolocation, your bonus challenge is this weather forecast tool.

11. Movie App

  • It gives you a solid foundation of how JavaScript works with HTML, CSS, and other tools
  • You can use this project to make your own custom movie app
  • Learn more about how to use JavaScript with jQuery, Bootstrap, and API calls

Window with the poster for The Fate of the Furious and movie times

Movie App Source Code

  • On click event
  • You’ll need to get yourself an API key!
  • Implement the JavaScript code so that you can make your own movie app that lets you view the most popular movies, sort them by genre, and search for other movies.

To test your understanding of the concepts behind the movie app, your bonus challenge is to build an ecommerce landing page.

12. Name Tags

  • As a beginner JavaScript project, it lets you practice using React to create a practical and useful tool
  • You can use this project to hone your React skills and key concepts
  • Learn more about how to handle user input, work with stateful components, and render array data models

12 red name tag stickers with names on them

Name Tag Generator Source Code

  • Handling user input
  • Stateful components
  • Render array data models
  • Implement the JavaScript code so that you can build a text box and button to let users input text and have it respond to the input by generating a new name tag!

To test your understanding of the concepts behind the name tag generator, your bonus challenge is this Pokemon React generator.

(Back to top.)

13. Tone.js

  • You’ll learn how to create interactive web browser music with advanced scheduling capabilities, synths and effects, and intuitive musical abstractions built on top of the Web Audio API
  • You can use this project to be your own personal DJ and music producer, for free!
  • Learn more about how to use event listeners, triggerAttack, triggerRelease, and different kinds of synths

grey bars on a white background

Tone.js Source Code

  • triggerAttack and triggerRelease
  • Copy the source code from the Tone.js GitHub.io page.
  • Implement the JavaScript code so that you can create interactive music in your own browser.

14. Election Map

  • It gives you a solid foundation of the difference between JavaScript, HTML, and CSS, especially what JavaScript does and how it does it
  • You can use this project in your daily life and add it to your portfolio
  • Learn more about how to use arrays and nested functions

US election map text with red and blue states and a counter at the bottom

Election Map Source Code

  • If-else and function practice
  • Parent-child relationships
  • getElementById
  • Copy the source code from JSBin.
  • Implement the JavaScript code so that you can add two candidates running for president and display the number of votes they received from each state, both in a table on the bottom right and when you mouse over a state.

To test your understanding of the concepts behind the election map, your bonus challenge is this interactive map.

15. Login Authentication

  • It introduces you to Angular JS and more advanced JavaScript concepts
  • You can see how login authentication works behind the scenes
  • Learn more about how to use function states, app controllers, and dependencies

AngularJS Login Sample text with green login button

Login Authenticator Source Code

  • State management
  • App controller
  • Dependencies
  • Implement the JavaScript code so that you can enter an email address and password, and have the system tell you if the email address is invalid when you press the “Submit” button.

To test your understanding of the concepts behind the Login Authenticator, your bonus challenge is this password generator.

16. Guess the Word

  • It gives you a solid foundation for methods, creating global variables, and working with event listeners
  • You can use this project as a party game or challenge with your friends and coworkers
  • Learn more about how to use methods, functions, and regular expressions

Guess the Word in a white box with light blue background and an orange Guess button

Guess the Word Source Code

  • Methods like match(), split(), trim(), and join()
  • Regular expressions
  • Implement the JavaScript code so that players start by entering a letter. If they guess correctly, the letter appears in the word. If they guess incorrectly, they learn how many guesses they have remaining. The player can also see which letters they’ve already guessed. The game lets the player know if they’ve already guessed a letter or entered a non-alphabetic character!

To test your understanding of the concepts behind the Guess the Word game, your bonus challenge is this Wordled game.

Warning: the difficulty level for this is advanced, so if you’re having trouble with it, it’s not you!

17. Terminalizer

  • It teaches you how to record your terminal screen and share your work with others
  • You can use this project to debug and work on coding projects with friends
  • Learn more about how to use recording files, frame delays, and set idle times

Terminalizer terminal screen with colorful text

Terminalizer Source Code

  • Recording files
  • Using frameDelay
  • Setting idle time
  • Implement the JavaScript code so that you can record your terminal and generate animated GIF images or share web player links.

To test your understanding of the concepts behind Terminalizer, your bonus challenge is to figure out how to play/pause GIFs.

18. Chat App

  • It gives you a solid foundation of how JavaScript and its front and back end libraries can be used to create applications
  • You can add this project to your portfolio to show your knowledge of programming concepts as a full stack developer
  • Learn more about how to use ReactJS, NodeJS, and sockets along with JavaScript

blue and white chat application windows with Real Time Chat Application text

Chat App Source Code and YouTube tutorial link

  • You won’t be able to clone and run the project straight from GitHub because there is no package.json file, but you can build this using the YouTube tutorial
  • Implement the JavaScript code so that you can build a real time chat application that lets you send and receive messages using web sockets

To test your understanding of the concepts behind the chat application, your bonus challenge is this React text editor.

19. Tic Tac Toe Game

  • This project will test your HTML semantics and your JavaScript logic skills
  • You can use this as a practice project and for something to do while your code compiles
  • Learn more about how to use arrays, grid methods, and event listeners

white tic tac toe game on black background with win loss tie record

Tic-Tac-Toe Source Code

  • Implement the JavaScript code so that the player can set difficulty level as easy or hard, choose whether to play as X or O, play a game with the computer, have it remember who won or drew, and play again.

To test your understanding of the concepts behind the Tic-Tac-Toe game, your bonus challenge is this hangman game.

20. Hotel Booking App

  • You’ll get to practice key concepts in JavaScript ES6 and React JSX
  • You can use this project to practice building sites with more functionality and use some of your creativity by making it look really spiffy
  • Learn more about how to manage data flow and manipulate the DOM

hotel booking app screen with room pictures and number of rooms remaining

Hotel Booking App Source Code

  • ES6 and React JSX practice
  • Managing data flow
  • Implement the JavaScript code so that you can create a sample booking on a hotel site, complete with filtered search results, room inventory display, and hotel ratings.

To test your understanding of the concepts behind the Hotel Booking App, your bonus challenge is this ticket booking app.

Advanced JavaScript Projects

21. maze game.

  • It gives you a solid idea of how JavaScript core skills and functions can be used to create interactive games
  • You can put this project in your portfolio and challenge friends
  • Learn more about how to use JavaScript math concepts, create elements, and use loops

Maze game with Pickle Rick and lettuce

Maze Game Source Code

  • Random and Floor
  • Element creation
  • Implement the JavaScript code so that you can get the pickle from one end of the maze to another using the arrow functions (or AWSD) on your keyboard, have it display the number of steps it took to complete the maze, and be able to set the difficulty level.

To test your understanding of the concepts behind the maze game, your bonus challenge is this Tetris game.

Author Image

Justina Hwang

Category: Blog , Coding Languages and Tools , Entry Level Tech Jobs , Front End Developer , Full Stack Developer , JavaScript , Learn to Code

Related Articles

task in javascript example

  • Jeremias Menichelli
  • Oct 25, 2019

Writing Asynchronous Tasks In Modern JavaScript

  • 11 min read
  • JavaScript , Coding
  • Share on Twitter ,  LinkedIn

About The Author

His interest for web development started back when he opened a website for the first time as a child and asked himself why it was so slow. Through his career he … More about Jeremias ↬

Email Newsletter

Weekly tips on front-end & UX . Trusted by 200,000+ folks.

JavaScript has two main characteristics as a programming language, both important to understand how our code will work. First is its synchronous nature, which means the code will run line after line, almost as you read it, and secondly that it is single-threaded , only one command is being executed at any time.

As the language evolved, new artifacts appeared in the scene to allow asynchronous execution; developers tried different approaches while solving more complicated algorithms and data flows, which led to the emergence of new interfaces and patterns around them.

Synchronous Execution And The Observer Pattern

As mentioned in the introduction, JavaScript runs the code you write line by line, most of the time. Even in its first years, the language had exceptions to this rule, though they were a few and you might know them already: HTTP Requests, DOM events and time intervals.

If we add an event listener, for example the click of an element and the user triggers this interaction, the JavaScript engine will queue a task for the event listener callback but will continue executing what is present in its current stack. After it’s done with the calls present there, it will now run the listener’s callback.

This behavior is similar to what happens with network requests and timers, which were the first artifacts to access to asynchronous execution for web developers.

Though these were exceptions of common synchronous execution in JavaScript, it’s crucial to understand that the language is still single-threaded and though it can queue taks, run them asynchronously and then go back to the main thread, it can only execute one piece of code at a time.

For example, let’s check out a network request.

When the server comes back, a task for the method assigned to onreadystatechange is queued (code execution continues in the main thread).

Note : Explaining how JavaScript engines queue tasks and handle execution threads is a complex topic to cover and probably deserves an article of its own. Still, I recommend watching “ What The Heck Is The Event Loop Anyway? ” by Phillip Roberts to help you get a better understanding.

In each case mentioned, we are responding to an external event. A certain interval of time reached, a user action or a server response. We weren’t able to create an asynchronous task per se, we always observed occurrences happening outside of our reach.

This is why code shaped this way is called the Observer Pattern , which is better represented by the addEventListener interface in this case. Soon event emitters libraries or frameworks exposing this pattern flourished.

Node.js And Event Emitters

A good example is Node.js which page describes itself as “an asynchronous event-driven JavaScript runtime”, so event emitters and callback were first-class citizens. It even had an EventEmitter constructor already implemented.

This was not only the to-go approach for asynchronous execution but a core pattern and convention of its ecosystem. Node.js opened a new era of writing JavaScript in a different environment — even outside the web. As a consequence, other asynchronous situations were possible, like creating new directories or writing files.

You might notice that callbacks receive an error as a first argument, if a response data is expected, it goes as a second argument. This was called Error-first Callback Pattern , which became a convention that authors and contributors adopted for their own packages and libraries.

Promises And The Endless Callback Chain

As web development faced more complex problems to solve, the need for better asynchronous artifacts appeared. If we look at the last code snippet, we can see a repeated callback chaining which doesn’t scale well as the number tasks increase.

For example, let’s add only two more steps, file reading and styles preprocessing.

We can see how as the program we are writing gets more complex the code becomes harder to follow for the human eye due to multiple callback chaining and repeated error handling.

Promises, Wrappers And Chain Patterns

Promises didn’t receive much attention when they were first announced as the new addition to the JavaScript language, they aren’t a new concept as other languages had similar implementations decades before. Truth is, they turned out to change a lot the semantics and structure of most of the projects I worked on since its appearance.

Promises not only introduced a built-in solution for developers to write asynchronous code but also opened a new stage in web development serving as the construction base of later new features of the web spec like fetch .

Migrating a method from a callback approach to a promise-based one became more and more usual in projects (such as libraries and browsers), and even Node.js started slowly migrating to them.

Let’s, for example, wrap Node’s readFile method:

Here we obscure the callback by executing inside a Promise constructor, calling resolve when the method result is successful, and reject when the error object is defined.

When a method returns a Promise object we can follow its successful resolution by passing a function to then , its argument is the value which the promise was resolved, in this case, data .

If an error was thrown during the method the catch function will be called, if present.

Note : If you need to understand more in-depth how Promises work, I recommend Jake Archibald’s “ JavaScript Promises: An Introduction ” article which he wrote on Google’s web development blog.

Now we can use these new methods and avoid callback chains.

Having a native way to create asynchronous tasks and a clear interface to follow up its possible results enabled the industry to move out of the Observer Pattern. Promise-based ones seemed to solve the unreadable and prone-to-error code.

As a better syntax highlighting or clearer error messages help while coding, a code that is easier to reason becomes more predictable for the developer reading it, with a better picture of the execution path the easier to catch a possible pitfall.

Promises adoption was so global in the community that Node.js rapidly release built-in versions of its I/O methods to return Promise objects like importing them file operations from fs.promises .

It even provided a promisify util to wrap any function which followed the Error-first Callback Pattern and transform it into a Promise-based one.

But do Promises help in all cases?

Let’s re-imagine our style preprocessing task written with Promises.

There is a clear reduction of redundancy in the code, especially around the error handling as we now rely on catch , but Promises somehow failed to deliver a clear code indentation that directly relates to the concatenation of actions.

This is actually achieved on the first then statement after readFile is called. What happens after these lines is the need to create a new scope where we can first make the directory, to later write the result in a file. This causes a break into the indentation rhythm, not making it easy to determinate the instructions sequence at first glance.

A way to solve this is to pre-baked a custom method that handles this and allows the correct concatenation of the method, but we would be introducing one more depth of complexity to a code that already seems to have what it needs to achieve the task we want.

Note : Take in count this is an example program, and we are in control around some of the methods and they all follow an industry convention, but that’s not always the case. With more complex concatenations or the introduction of a library with a different shape, our code style can easily break.

Gladly, the JavaScript community learned again from other language syntaxes and added a notation that helps a lot around these cases where asynchronous tasks concatenation is not as pleasant or straight-forward to read as synchronous code is.

Async And Await

A Promise is defined as an unresolved value at execution time, and creating an instance of a Promise is an explicit call of this artifact.

Inside an async method, we can use the await reserved word to determinate the resolution of a Promise before continuing its execution.

Let’s revisit or code snippet using this syntax.

Note : Notice that we needed to move all our code to a method because we can’t use await outside the scope of an async function today.

Every time an async method finds an await statement, it will stop executing until the proceeding value or promise gets resolved.

There’s a clear consequence of using async/await notation, despite its asynchronous execution, the code looks as if it was synchronous , which is something we developers are more used to see and reason around.

What about error handling? For it, we use statements that have been present for a long time in the language, try and catch .

We rest assured any error thrown in the process will be handled by the code inside the catch statement. We have a centric place that takes care of error handling, but now we have a code that is easier to read and follow.

Having consequent actions that returned value doesn’t need to be stored in variables like mkdir that don’t break the code rhythm; there’s also no need to create a new scope to access the value of result in a later step.

It’s safe to say Promises were a fundamental artifact introduced in the language, necessary to enable async/await notation in JavaScript, which you can use on both modern browsers and latest versions of Node.js.

Note : Recently in JSConf, Ryan Dahl, creator and first contributor of Node, regretted not sticking to Promises on its early development mostly because the goal of Node was to create event-driven servers and file management which the Observer pattern served better for.

The introduction of Promises into the web development world came to change the way we queue actions in our code and changed how we reason about our code execution and how we author libraries and packages.

But moving away from chains of callback is harder to solve, I think that having to pass a method to then didn’t help us to move away from the train of thought after years of being accustomed to the Observer Pattern and approaches adopted by major vendors in the community like Node.js.

As Nolan Lawson says in his excellent article about wrong uses in Promise concatenations , old callback habits die hard ! He later explains how to escape some of these pitfalls.

I believe Promises were needed as a middle step to allow a natural way to generate asynchronous tasks but didn’t help us much to move forward on better code patterns, sometimes you actually need a more adaptable and improved language syntax.

As we try to solve more complex puzzles using JavaScript, we see the need for a more mature language and we experiment with architectures and patterns we weren’t used to seeing on the web before. “

We still don’t know how the ECMAScript spec will look in years as we are always extending the JavaScript governance outside the web and try to solve more complicated puzzles.

It’s hard to say now what exactly we will need from the language for some of these puzzles to turn into simpler programs, but I’m happy with how the web and JavaScript itself are moving things, trying to adapt to challenges and new environments. I feel right now JavaScript is a more asynchronous friendly place than when I started writing code in a browser over a decade ago.

Further Reading

  • “ JavaScript Promises: An Introduction ,” Jake Archibald
  • “ Promise Anti-Patterns ”, a Bluebird library documentation
  • “ We Have A Problem With Promises ,” Nolan Lawson

Smashing Newsletter

Tips on front-end & UX, delivered weekly in your inbox. Just the things you can actually use.

Front-End & UX Workshops, Online

With practical takeaways, live sessions, video recordings and a friendly Q&A.

Microtasks queue

Asynchronous tasks need proper management. For that, the ECMA standard specifies an internal queue PromiseJobs , more often referred to as the “microtask queue” (V8 term).

As stated in the specification :

  • The queue is first-in-first-out: tasks enqueued first are run first.
  • Execution of a task is initiated only when nothing else is running.

Or, to put it more simply, when a promise is ready, its .then/catch/finally handlers are put into the queue; they are not executed yet. When the JavaScript engine becomes free from the current code, it takes a task from the queue and executes it.

That’s why “code finished” in the example above shows first.

Promise handlers always go through this internal queue.

If there’s a chain with multiple .then/catch/finally , then every one of them is executed asynchronously. That is, it first gets queued, then executed when the current code is complete and previously queued handlers are finished.

What if the order matters for us? How can we make code finished appear after promise done ?

Easy, just put it into the queue with .then :

Now the order is as intended.

Unhandled rejection

Remember the unhandledrejection event from the article Error handling with promises ?

Now we can see exactly how JavaScript finds out that there was an unhandled rejection.

An “unhandled rejection” occurs when a promise error is not handled at the end of the microtask queue.

Normally, if we expect an error, we add .catch to the promise chain to handle it:

But if we forget to add .catch , then, after the microtask queue is empty, the engine triggers the event:

What if we handle the error later? Like this:

Now, if we run it, we’ll see Promise Failed! first and then caught .

If we didn’t know about the microtasks queue, we could wonder: “Why did unhandledrejection handler run? We did catch and handle the error!”

But now we understand that unhandledrejection is generated when the microtask queue is complete: the engine examines promises and, if any of them is in the “rejected” state, then the event triggers.

In the example above, .catch added by setTimeout also triggers. But it does so later, after unhandledrejection has already occurred, so it doesn’t change anything.

Promise handling is always asynchronous, as all promise actions pass through the internal “promise jobs” queue, also called “microtask queue” (V8 term).

So .then/catch/finally handlers are always called after the current code is finished.

If we need to guarantee that a piece of code is executed after .then/catch/finally , we can add it into a chained .then call.

In most Javascript engines, including browsers and Node.js, the concept of microtasks is closely tied with the “event loop” and “macrotasks”. As these have no direct relation to promises, they are covered in another part of the tutorial, in the article Event loop: microtasks and macrotasks .

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

{{ activeMenu.name }}

  • Python Courses
  • JavaScript Courses
  • Artificial Intelligence Courses
  • Data Science Courses
  • React Courses
  • Ethical Hacking Courses
  • View All Courses

Fresh Articles

Want To Learn PHP Web Development? Check Out These PHP Courses

  • Python Projects
  • JavaScript Projects
  • Java Projects
  • HTML Projects
  • C++ Projects
  • PHP Projects
  • View All Projects

How To Create A Python Hangman Game With GUI for Beginners

  • Python Certifications
  • JavaScript Certifications
  • Linux Certifications
  • Data Science Certifications
  • Data Analytics Certifications
  • Cybersecurity Certifications
  • View All Certifications

The 15 Best Project Management Certifications in 2024

  • IDEs & Editors
  • View All Programming
  • Web Development
  • App Development
  • Game Development
  • Frameworks & Libraries
  • Courses, Books, & Certifications
  • View All Development
  • Data Science
  • Data Analytics
  • Artificial Intelligence (AI)
  • Machine Learning (ML)
  • View All Data, Analysis, & AI

Google Career Certificates to Help You Land a Job in 2024

  • Networking & Security
  • Cloud, DevOps, & Systems
  • Reccomendations
  • Crypto, Web3, & Blockchain
  • User-Submitted Tutorials
  • View All Blog Content
  • Certifications
  • Programming
  • Development
  • Data, Analysis, & AI

Don't have an account? Sign up

Forgot your password?

Already have an account? Login

Have you read our submission guidelines?

Go back to Sign In

task in javascript example

16 Best JavaScript Projects for Beginners [With Source Code]

If I could go back in time to help my younger self learn JavaScript, I'd tell him to build more JavaScript projects!

That's exactly why I wrote this article: to share 16 JavaScript projects to help beginners like you.

Whether you’re looking to start a career in web development or enhance your portfolio, these JavaScript projects are perfect for leveling up your JS skills.

I’ve also personally designed the first seven JavaScript projects to be step-by-step tutorials so you can follow along with me to get hands-on and code some cool stuff.

You can think of these tutorial projects as taking a free JavaScript course while growing your JavaScript portfolio!

I'm also regularly adding new JavaScript projects with step-by-step tutorials, so make sure you bookmark this page and check back for the latest JavaScript projects to grow your skills.

Without further ado, let’s dive in and start building with JavaScript !

  • 16 Best JavaScript Projects in 2024

1. JavaScript Countdown Timer

What is this JavaScript project?

In this JavaScript project, you'll build a dynamic countdown timer, which is ideal for websites featuring upcoming events or sales.

I really like this project because it's a practical example of how the JavaScript programming language brings interactivity to web pages. Plus, it's a solid addition to your portfolio if you want to break into web development, thanks to its wide applicability and real-world focus.

If you're brand new to JavaScript, grab a JavaScript book in case you need extra help, and start here!

JavaScript Skills Covered:

  • Date Object Manipulation: Utilizing JavaScript's Date object to set and manage target dates and times.
  • Dynamic HTML Content Update: Using DOM manipulation to dynamically update the web page in real-time.
  • Interval Handling: Implementing setInterval and clearInterval to create and manage a real-time countdown effect.
  • Conditional Logic: Applying conditional statements to handle different states of the countdown, such as completion.
  • Event Handling: Managing browser events to make the timer interactive and responsive to user actions.
  • JavaScript Best Practices: Writing clean, efficient, and well-structured JavaScript code.

Build This JavaScript Project Here

2. JavaScript Tic-Tac-Toe Game

In this JavaScript project idea, you'll create a Tic-Tac-Toe game, which is not only fun to play but also a classic project for basic game development.

I find this project particularly effective for showing how JavaScript enhances user experience on web pages.

It's also a great addition to your portfolio, especially if you're looking to make a mark in web development or you're eyeing up a JS certification , as it demonstrates key programming concepts in a familiar and relatable context.

  • Game Logic Implementation: Develop the core logic of a tic tac toe game, including handling player turns and determining win or draw conditions.
  • Dynamic UI Updates: Using DOM manipulation to dynamically update the game board front end and display game status messages in real-time.
  • Event Handling: Manage browser events to capture user interactions like clicking on the game board.
  • Conditional Logic: Applying conditional statements to handle game flow, such as switching between players and checking for the end of the game.
  • Array Manipulation: Manipulating arrays to represent and update the game board state.
  • JavaScript Best Practices: Writing clean, efficient, and well-structured JavaScript via best practices to enhance readability and maintainability.

3. JavaScript To-Do List

In this JavaScript project, you'll build a To-Do List app, a practical and highly useful application that is a staple in many people's daily productivity routines.

This project is not just about creating a functional tool; it’s also a brilliant demonstration of how JavaScript can be used to enhance the interactivity and responsiveness of web pages.

It's an excellent addition to your portfolio, especially if you're aiming to showcase your skills in web development, as it highlights essential programming concepts in a context that is both familiar and widely applicable.

I'd also recommend having a JavaScript cheatsheet handy in case you need some quick refreshers on rusty concepts.

  • Task Management Logic: Develop the core logic of a To-Do List, including adding, editing, deleting, and marking tasks as complete.
  • Dynamic UI Updates: Use DOM manipulation to dynamically update the list of tasks and reflect changes in real-time, enhancing the user experience.
  • Event Handling: Manage browser events to capture user inputs like adding a new task or interacting with existing tasks.
  • Conditional Logic: Apply conditional statements to handle different aspects of task management.
  • Local Storage Utilization: Implement local storage to save tasks, allowing the data to persist even after the browser is closed, demonstrating data persistence in web applications.
  • JavaScript Best Practices: Write clean, efficient, and well-structured JavaScript code, adhering to best practices for readability and maintainability.

4. JavaScript Drum Kit

In this JavaScript project, you'll create a Drum Kit app, an engaging and musical web application that lets users play drum sounds using their keyboard or mouse clicks.

This project goes beyond simply triggering sounds; it's a vibrant showcase of how JavaScript can bring dynamic content and interactivity to life on web pages.

I think this is a fantastic piece to add to your portfolio, particularly if you're keen on demonstrating your prowess in web development.

It encapsulates fundamental programming concepts within an entertaining and creative framework that's sure to capture attention.

Plus, you can do all of this with vanilla JS and without using JavaScript frameworks .

  • Sound Playback Logic: Craft the underlying logic of a Drum Kit, enabling the playing of different drum sounds in response to user actions.
  • Dynamic UI Updates: Employ DOM manipulation to provide immediate visual feedback for each interaction, making the app more intuitive and engaging.
  • Event Handling: Implement event listeners to handle user inputs, such as keyboard presses and mouse clicks, allowing for a rich, responsive user experience.
  • Animation and Effects: Integrate CSS and JavaScript animations to enhance the visual appeal and feedback of the drum pads, making the app feel more alive.
  • Responsive Design: Apply responsive design principles to ensure the Drum Kit app looks great and functions seamlessly across a variety of devices and screen sizes.
  • JavaScript Best Practices: Embrace clean, efficient, and well-organized JavaScript coding practices, emphasizing readability and maintainability, crucial for any web development project.

5. JavaScript Calculator

In this JavaScript project, you'll construct a classic calculator app. While it seems simple, calculator apps are an indispensable and universally utilized tool, in both personal and professional settings.

Plus, this project is more than just functional; it's also a fantastic way to showcase JavaScript's capability to not only elevate web page interactivity but also to build useful everyday tools that appeal to a broad user base.

If you're a beginner and you want to grow your portfolio, this is a solid starting point, especially if you want to boost your web development skills while also using fundamental programming principles in a relatable and widely relevant context.

  • Arithmetic Logic: Write the fundamental logic of a calculator by executing basic arithmetic operations like addition, subtraction, multiplication, and division.
  • Dynamic UI Updates : Leverage DOM manipulation to dynamically update the calculator's display, ensuring real-time reflection of user inputs and calculations.
  • Event Handling : Employ browser event listeners to capture and respond to user actions such as number entry and operation selection, facilitating a seamless interactive experience.
  • Input Validation and Error Handling : Implement input validation and error handling to manage user inputs, ensuring robust and fault-tolerant operation handling.
  • State Management : Manage the calculator's state, including current value, previous value, and chosen operation, to support complex calculations and continuous operations.
  • JavaScript Best Practices : Craft clean, efficient, and well-organized JavaScript code, adhering to best practices to ensure code readability and maintainability.

6. JavaScript Quiz App

In this JavaScript project, you'll create a really useful and widely applicable quiz app. This is a really engaging and interactive application that you can use to test knowledge across various subjects.

I've chosen to make my quiz about JavaScript, so feel free to take the test and check on your JavaScript progress!

This project also goes beyond merely crafting a functional tool, as it showcases the power of JavaScript in making web pages dynamic and interactive, providing immediate visual feedback and challenging users in real time.

It's also a fantastic portfolio piece, particularly if you want to highlight your real-world abilities in web development with a skill that's broadly relevant and helpful.

  • Question and Answer Logic: Develop the foundational logic of a quiz app, including presenting questions, selecting answers, and navigating questions.
  • Dynamic UI Updates: Employ DOM manipulation to dynamically update the quiz content and feedback based on user interactions
  • Event Handling: Implement browser event listeners to manage user actions like choosing an answer and moving to the next question.
  • Conditional Logic: Use conditionals to manage quiz flow, such as determining when the quiz ends and displaying results.
  • Enhancing User Experience: Integrate optional features like timers for each question and animations for transitions between questions.
  • JavaScript Best Practices : Write clean, efficient, and well-organized JavaScript code, adhering to best practices to ensure code readability and maintainability.

7. JavaScript Rock, Paper, Scissors Game

In this JavaScript project, you'll create the timeless classic Rock Paper Scissors game. It really needs no introduction, but this is an engaging and interactive application that brings a classic game to your web browser.

But this JavaScript project goes beyond merely replicating a well-known game; it's also a fantastic showcase of JavaScript's power to create dynamic and responsive web experiences.

It's also a solid portfolio piece, particularly if you want to highlight your web development prowess by using core programming principles in a context that's both enjoyable and easy to understand

  • Game Logic Development: Build the foundational logic, including processing player selections, generating computer choices, and determining the outcomes of rounds.
  • Dynamic UI Updates: Employ DOM manipulation to dynamically refresh the game interface, reflecting the ongoing actions and results.
  • Event Handling: Implement event listeners to capture and respond to user interactions, such as choosing rock, paper, or scissors, fostering an interactive gameplay environment.
  • Conditional Logic: Utilize conditional statements to navigate the various game scenarios, from comparing choices to determining round winners and managing game progression.
  • Score Tracking and Round Management: Introduce game features like scorekeeping and round-based play to add structure and competitive elements.
  • JavaScript Best Practices: Craft clean, effective, and well-organized JavaScript code, following best coding practices to ensure your project is both functional and maintainable.

8. Hangman Game

Hangman Game

Hangman is a well-known game, and one of our simple JS projects. You can develop it in a jiffy using JavaScript, HTML, and CSS. Note that the main functionality is defined using JS. HTML is for display, and CSS does the job of beautifying the contents. 

Many methods are defined in the JS code, so it may seem a bit complicated, but you will realize it is simple once you read the code thoroughly. You can also run the code and see the execution line by line.

Check the code and execution  here .

9. JavaScript Weather App

JavaScript Weather App

Weather apps are also popular JavaScript projects. Once you change the location name in this project, the weather display changes immediately without a page refresh. The UI is also quite sleek. 

Note that most weather apps use an API that gets the weather data. We will use the popular and most common API, OpenWeatherMap. 

Check out this Youtube video that explains the weather app code and functionality in detail. There are three files, as usual: index.html, main.js, and main.css. Although you can put all the code in a single file (HTML), it is more convenient to maintain separate files. 

10. Build a Shopping Cart for Order Fulfillment

Build a Shopping Cart for Order Fulfillment

So far, we have run through small projects with pure JS, HTML, and CSS. Here, the author builds a full-fledged shopping cart for order fulfillment, and the project also uses jQuery. 

You can use this as an opportunity to learn the important concepts of jQuery . This will be a good project to build because shopping websites are extremely popular today, as digital shopping has become quite popular. This project will take time, but it is worth it!

11. Single Page Application

Single Page Application

Here, the page won’t reload upon navigating the side links, but the content will change. Again, we will use eventListeners to change the view from one link to another. Check out the code and explanation on this YouTube video .

12. JavaScript Browser Code Editor

JavaScript Browser Code Editor

While you already have an ample choice of JS code editors, it’s always nice to be able to create your own. JS allows you to create an in-browser code editor, which is what this project is about. It makes use of some useful JS methods - and even features syntax highlighting!

The source code for this project is available here .

13. Real-time Chat Application

Real-time Chat Application

Chat applications are comparatively simple to make and you can create one yourself using JavaScript. This project makes use of both React and Node.js, so it might be a little intimidating. However, it’s a good way to get your hands dirty and learn how to work with these invaluable tools. 

You can view the source code on GitHub.

14. 2D Platforming Game

2D Platforming Game

Games are an excellent and fun way to learn JS. It’s why you’ll see so many projects revolving around games. This project teaches you how to create a 2D platformer game — all using JS, HTML, and CSS. You’ll make use of OOPs concepts and an API, both handy skills to have.

Check out the source code here .

15. Photo-sharing App

Photo-sharing App

Everyone knows Instagram. It has a lot of features, but fundamentally, it’s a photo-sharing application. You can create a similar but smaller-scale version of it using JS. This is a hefty project and you’ll find yourself using React, Node.js, and Postgres, among other things.

Take a look at the source code here .

16. File Sharing App

File Sharing App

Learning how to share files is another useful skill to have. You’ll be using the Virgil Crypto Library in JavaScript to create this app. It’s secure, and you’ll be able to download, decrypt, and view encrypted media files.

  • How To Setup Your JavaScript Environment

Before you start coding in JavaScript, it's essential to have your coding environment properly set up and ready for action.

Being an interpreted language that runs in web browsers, you don't need to worry about having a compiler.

That said, setting up a good development environment can really help to enhance your coding efficiency and provide you with powerful tools to debug and test your code.

If you're already equipped with a basic setup, you might want to skip this.

If not, let me walk you through how to set up a JavaScript development environment. You can even use these steps for any of the most popular operating systems.

Install a JavaScript Code Editor

First things first, you'll need a code editor that supports JavaScript syntax highlighting and potentially IntelliSense for code completion.

Visual Studio Code (VSCode) is a popular choice among developers for its extensive feature set and vast library of extensions. That's why it's one of my favorite web development IDEs .

Assuming you have VSCode installed, follow these steps to enhance your JavaScript development experience:

Open VSCode and navigate to the VSCode Extensions tab (you can use the shortcut `Ctrl+Shift+X` on Windows/Linux or `Cmd+Shift+X` on macOS) and search for JavaScript-related extensions like:

  • ESLint for linting and maintaining code quality.
  • Prettier for code formatting.
  • JavaScript (ES6) code snippets for handy code snippets.

You can install these extensions by clicking the install button next to each.

Install a Web Browser with Developer Tools

Modern web browsers like Google Chrome, Mozilla Firefox, and Microsoft Edge come with built-in developer tools, which are indispensable for web development.

These tools allow you to debug JavaScript, inspect the DOM, view network requests, and much more.

Install Node.js and npm [Optional]

While JavaScript runs in the browser, Node.js allows you to run JavaScript on your computer as a standalone application, which is particularly useful for development. You can download Node from the official website .

I'd also recommend choosing the LTS (Long-Term Support) version for stability.

Next, we have npm (Node Package Manager), and luckily for you, this comes with Node.js! The more you dive into JS development, the more npm is essential for managing JavaScript libraries and packages.    After installation, I'd also recommend verifying that Node.js and npm are correctly installed by opening your terminal (Command Prompt, PowerShell, or Terminal app) and running the following commands:

These commands should display the versions of Node.js and npm, respectively, indicating a successful installation.

Install Git [Optional but Recommended]

If you're really new to coding, you might want to skip this step, but even then, I'd really recommend becoming familiar with Git as soon as you can.

If you want the TL-DR, Git is a version control system that lets you track changes in your code and collaborate with others.

While this step is not strictly necessary for JavaScript development, it's a best practice, especially for larger projects or when working in a team.

Simply download Git from the official Git website , and during installation, you can accept most default settings. That said, you might want to choose your preferred text editor and ensure that Git is added to your system's PATH.

  • Wrapping Up

And there we have it! If you've taken the time to build these 16 JavaScript projects, you should be feeling much more competent and confident with JavaScript.

You'll also have a burgeoning JavaScript portfolio that's packed full of interesting and practical JavaScript projects, each demonstrating your dedication and abilities.

I also hope you enjoyed following along with my step-by-step tutorials in the first seven JavaScript projects! Which one was your favorite? I'll confess that I really enjoyed making all of them, especially the drum kit!

My motivation with these JavaScript tutorials was to guide you through the nuances of JavaScript development while also giving you hands-on experience that you'd usually only get when taking a JavaScript course.

Here at hackr.io , we're huge fans of project-based learning, so I hope these JavaScript projects have bolstered your confidence and sparked a deeper interest in web development or any other form of JavaScript development.

Remember, the journey doesn't end here!

With new projects and step-by-step tutorials regularly added to this page, be sure to check back often for new opportunities to refine your JS skills and expand your portfolio.

Happy coding!

Want to sharpen up your JavaScript and web development skills? Check out:

Dr. Angela Yu's Complete Web Development Bootcamp

task in javascript example

Technical Editor for Hackr.io | 15+ Years in Python, Java, SQL, C++, C#, JavaScript, Ruby, PHP, .NET, MATLAB, HTML & CSS, and more... 10+ Years in Networking, Cloud, APIs, Linux | 5+ Years in Data Science | 2x PhDs in Structural & Blast Engineering

Subscribe to our Newsletter for Articles, News, & Jobs.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

  • Top 20 Open Source Projects: Python, JavaScript, Java, and C++ Projects
  • HTML vs JavaScript: Which Should You Learn? Programming Languages JavaScript HTML
  • What is JavaScript? Introduction To JavaScript For Beginners JavaScript Programming Languages

Please login to leave comments

Always be in the loop.

Get news once a week, and don't worry — no spam.

  • Help center
  • We ❤️ Feedback
  • Advertise / Partner
  • Write for us
  • Privacy Policy
  • Cookie Policy
  • Change Privacy Settings
  • Disclosure Policy
  • Terms and Conditions
  • Refund Policy

Disclosure: This page may contain affliate links, meaning when you click the links and make a purchase, we receive a commission.

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types
  • JavaScript Operators
  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement

JavaScript for loop

  • JavaScript while loop
  • JavaScript break Statement

JavaScript continue Statement

  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype
  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String

JavaScript for...in loop

  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6
  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals
  • JavaScript Spread Operator
  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

JavaScript while and do...while Loop

JavaScript for... of Loop

  • JavaScript console.log()

In programming, loops are used to repeat a block of code.

For example, if you want to show a message 100 times, then you can use a loop. It's just a simple example; you can achieve much more with loops.

This tutorial focuses on JavaScript for loop. You will learn about the other type of loops in the upcoming tutorials.

The syntax of the for loop is:

  • The initialExpression initializes and/or declares variables and executes only once.
  • If the condition is false , the for loop is terminated.
  • If the condition is true , the block of code inside of the for loop is executed.
  • The updateExpression updates the value of initialExpression when the condition is true .
  • The condition is evaluated again. This process continues until the condition is false .

To learn more about the conditions , visit JavaScript Comparison and Logical Operators .

Working of for loop in JavaScript with flowchart

Example 1: Display a Text Five Times

Here is how this program works.

Example 2: Display Numbers from 1 to 5

Example 3: display sum of n natural numbers.

Here, the value of sum is 0 initially. Then, a for loop is iterated from i = 1 to 100 . In each iteration, i is added to sum and its value is increased by 1 .

When i becomes 101 , the test condition is false and sum will be equal to 0 + 1 + 2 + ... + 100 .

The above program to add sum of natural numbers can also be written as

This program also gives the same output as the Example 3 . You can accomplish the same task in many different ways in programming; programming is all about logic.

Although both ways are correct, you should try to make your code more readable.

JavaScript Infinite for loop

If the test condition in a for loop is always true , it runs forever (until memory is full). For example,

In the above program, the condition is always true which will then run the code for infinite times.

  • JavaScript for...of Loop
  • JavaScript for...in Loop

Table of Contents

  • Introduction
  • Working of for Loop
  • Infinite for Loop

Video: JavaScript for Loop

Sorry about that.

Related Tutorials

JavaScript Tutorial

How Functions Work in JavaScript – JS Function Code Examples

Edeh Israel Chidera

JavaScript is a widely-used programming language that is essential for web development. Its ability to run on both client-side and server-side makes it a versatile tool that has become an essential tool for web developers.

JavaScript is a high-level, interpreted language used on the client side, meaning it runs in the user's web browser. You can use it to create web and mobile applications, browser extensions, and other software.

It is supported by all major web browsers, and it is an essential technology for front-end web development.

Functions are one of the building blocks of JavaScript programming for creating web applications.

You can think of functions as a way to group a set of instructions together and execute them as a single unit.

In this article, we will explore the basics of functions in JavaScript and how you can use them effectively in your code.

Function Syntax

A function is a block of code that performs a specific task. JavaScript functions are basically used to encapsulate logic, making that code more reusable and easier to understand.

The syntax for creating a function in JavaScript is quite simple. Functions can take input in the form of parameters and can return a value or output.

Functions help you organize and structure your code. They also allow for code reuse and make it easier to understand and maintain large codebases.

How to Write a Function in JavaScript

You start by using the keyword " function ," followed by the function name and a set of parentheses.

Inside the parentheses, you can specify any input parameters that the function will take in, also known as arguments. The arguments are usually optional.

Next, you include a block of code inside curly braces that defines the instructions the function will execute when it is called.

Here is an example of a basic function that takes in two numbers and returns their sum:

The function above, named " addNumbers ," takes in two parameters, a and b . The code inside the function body simply adds these two parameters together and returns the result.

How to Declare a Function in JavaScript

Apart from the regular way of declaring a function as seen above, you can also define functions using function expressions or arrow functions .

The arrow function syntax is a shorthand version of the regular function syntax. Here is the same function as above, but written with an arrow function:

In the example above, the function is assigned to the variable addNumbers . The arrow => is used to define the function, and the code inside the curly braces is the body of the function.

Function expressions in JavaScript are similar to regular function declarations. The difference between them is that the function expression is always assigned to a variable. Here is an example of a function expression:

In this example, the function is assigned to the variable multiplyNumbers . This variable can be used to call the function, just like a regular function.

How to Use Callback Functions

Functions can also be passed as arguments to other functions, known as callback functions . Here is an example of a callback function being used to log the result of a multiplication operation:

In this example, the multiplyByTwo function takes two arguments: a number and a callback function. The function multiplies the number by 2 and then invokes the callback function, passing the result as an argument. The logResult function is then executed, which logs the result to the console.

How to Use Default Parameters

JavaScript functions also have a feature called default parameters. They allow you to set default values for parameters in case they are not passed when the function is called.

This is helpful in situations where you want to provide a default value for a parameter in case it is not passed. Here is an example:

In this example, the greet function takes in a single parameter name , which is set to "John Doe" by default. If the function is called without passing any arguments, it will use the default value "John Doe". But if an argument is passed, it will use that value instead.

How to Use the Constructor Function

JavaScript has a special type of function called a constructor function, which is used to create objects.

You define a constructor function using the keyword "function" followed by a name that starts with an uppercase letter (called using the "new" keyword).

For example, the following code defines a constructor function named "Person" that creates an object with a name and age property:

How to Use Closures

A closure is a function that has access to variables in its parent scope, even after the parent function has returned. This allows for variables to be preserved between function calls, and it is a powerful feature that allows for more advanced programming patterns such as object-oriented programming.

Here's an example of a closure function that creates a counter:

How to Use Higher-Order Functions

Functions can also be passed as arguments to other functions, which is known as a "higher-order" function. For example:

In this example, the performOperation function takes in three arguments: a , b , and operation .

The operation argument is a function that takes in two arguments and returns a result. In this case, we are passing the addNumbers function as the operation argument, so the result of the performOperation function will be the result of calling the addNumbers function with the arguments a and b .

In this article, we have covered the basics of functions in JavaScript, including how to define, call, and use them in our codes.

With a solid understanding of functions, you can write more efficient and maintainable code in JavaScript.

You can check the MDN docs to read more about functions in JavaScript. If you want to start learning the fundamentals of JavaScript, freeCodeCamp has a free JavaScript Algorithms and Data Structures Certification course for you. Happy coding!

Technical Writer and Software Developer

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Object-oriented programming

  • Overview: Objects

Object-oriented programming (OOP) is a programming paradigm fundamental to many programming languages, including Java and C++. In this article, we'll provide an overview of the basic concepts of OOP. We'll describe three main concepts: classes and instances , inheritance , and encapsulation . For now, we'll describe these concepts without reference to JavaScript in particular, so all the examples are given in pseudocode .

Note: To be precise, the features described here are of a particular style of OOP called class-based or "classical" OOP. When people talk about OOP, this is generally the type that they mean.

After that, in JavaScript, we'll look at how constructors and the prototype chain relate to these OOP concepts, and how they differ. In the next article, we'll look at some additional features of JavaScript that make it easier to implement object-oriented programs.

Object-oriented programming is about modeling a system as a collection of objects, where each object represents some particular aspect of the system. Objects contain both functions (or methods) and data. An object provides a public interface to other code that wants to use it but maintains its own private, internal state; other parts of the system don't have to care about what is going on inside the object.

Classes and instances

When we model a problem in terms of objects in OOP, we create abstract definitions representing the types of objects we want to have in our system. For example, if we were modeling a school, we might want to have objects representing professors. Every professor has some properties in common: they all have a name and a subject that they teach. Additionally, every professor can do certain things: they can all grade a paper and they can introduce themselves to their students at the start of the year, for example.

So Professor could be a class in our system. The definition of the class lists the data and methods that every professor has.

In pseudocode, a Professor class could be written like this:

This defines a Professor class with:

  • two data properties: name and teaches
  • two methods: grade() to grade a paper and introduceSelf() to introduce themselves.

On its own, a class doesn't do anything: it's a kind of template for creating concrete objects of that type. Each concrete professor we create is called an instance of the Professor class. The process of creating an instance is performed by a special function called a constructor . We pass values to the constructor for any internal state that we want to initialize in the new instance.

Generally, the constructor is written out as part of the class definition, and it usually has the same name as the class itself:

This constructor takes two parameters, so we can initialize the name and teaches properties when we create a new concrete professor.

Now that we have a constructor, we can create some professors. Programming languages often use the keyword new to signal that a constructor is being called.

This creates two objects, both instances of the Professor class.

Inheritance

Suppose in our school we also want to represent students. Unlike professors, students can't grade papers, don't teach a particular subject, and belong to a particular year.

However, students do have a name and may also want to introduce themselves, so we might write out the definition of a student class like this:

It would be helpful if we could represent the fact that students and professors share some properties, or more accurately, the fact that on some level, they are the same kind of thing . Inheritance lets us do this.

We start by observing that students and professors are both people, and people have names and want to introduce themselves. We can model this by defining a new class Person , where we define all the common properties of people. Then, Professor and Student can both derive from Person , adding their extra properties:

In this case, we would say that Person is the superclass or parent class of both Professor and Student . Conversely, Professor and Student are subclasses or child classes of Person .

You might notice that introduceSelf() is defined in all three classes. The reason for this is that while all people want to introduce themselves, the way they do so is different:

We might have a default implementation of introduceSelf() for people who aren't students or professors:

This feature - when a method has the same name but a different implementation in different classes - is called polymorphism . When a method in a subclass replaces the superclass's implementation, we say that the subclass overrides the version in the superclass.

Encapsulation

Objects provide an interface to other code that wants to use them but maintain their own internal state. The object's internal state is kept private , meaning that it can only be accessed by the object's own methods, not from other objects. Keeping an object's internal state private, and generally making a clear division between its public interface and its private internal state, is called encapsulation .

This is a useful feature because it enables the programmer to change the internal implementation of an object without having to find and update all the code that uses it: it creates a kind of firewall between this object and the rest of the system.

For example, suppose students are allowed to study archery if they are in the second year or above. We could implement this just by exposing the student's year property, and other code could examine that to decide whether the student can take the course:

The problem is, if we decide to change the criteria for allowing students to study archery - for example by also requiring the parent or guardian to give their permission - we'd need to update every place in our system that performs this test. It would be better to have a canStudyArchery() method on Student objects, that implements the logic in one place:

That way, if we want to change the rules about studying archery, we only have to update the Student class, and all the code using it will still work.

In many OOP languages, we can prevent other code from accessing an object's internal state by marking some properties as private . This will generate an error if code outside the object tries to access them:

In languages that don't enforce access like this, programmers use naming conventions, such as starting the name with an underscore, to indicate that the property should be considered private.

OOP and JavaScript

In this article, we've described some of the basic features of class-based object-oriented programming as implemented in languages like Java and C++.

In the two previous articles, we looked at a couple of core JavaScript features: constructors and prototypes . These features certainly have some relation to some of the OOP concepts described above.

  • constructors in JavaScript provide us with something like a class definition, enabling us to define the "shape" of an object, including any methods it contains, in a single place. But prototypes can be used here, too. For example, if a method is defined on a constructor's prototype property, then all objects created using that constructor get that method via their prototype, and we don't need to define it in the constructor.
  • the prototype chain seems like a natural way to implement inheritance. For example, if we can have a Student object whose prototype is Person , then it can inherit name and override introduceSelf() .

But it's worth understanding the differences between these features and the "classical" OOP concepts described above. We'll highlight a couple of them here.

First, in class-based OOP, classes and objects are two separate constructs, and objects are always created as instances of classes. Also, there is a distinction between the feature used to define a class (the class syntax itself) and the feature used to instantiate an object (a constructor). In JavaScript, we can and often do create objects without any separate class definition, either using a function or an object literal. This can make working with objects much more lightweight than it is in classical OOP.

Second, although a prototype chain looks like an inheritance hierarchy and behaves like it in some ways, it's different in others. When a subclass is instantiated, a single object is created which combines properties defined in the subclass with properties defined further up the hierarchy. With prototyping, each level of the hierarchy is represented by a separate object, and they are linked together via the __proto__ property. The prototype chain's behavior is less like inheritance and more like delegation . Delegation is a programming pattern where an object, when asked to perform a task, can perform the task itself or ask another object (its delegate ) to perform the task on its behalf. In many ways, delegation is a more flexible way of combining objects than inheritance (for one thing, it's possible to change or completely replace the delegate at run time).

That said, constructors and prototypes can be used to implement class-based OOP patterns in JavaScript. But using them directly to implement features like inheritance is tricky, so JavaScript provides extra features, layered on top of the prototype model, that map more directly to the concepts of class-based OOP. These extra features are the subject of the next article.

This article has described the basic features of class-based object oriented programming, and briefly looked at how JavaScript constructors and prototypes compare with these concepts.

In the next article, we'll look at the features JavaScript provides to support class-based object-oriented programming.

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript examples, what can javascript do.

Examples Explained

Where to Insert JavaScript

Where to Explained

JavaScript Output

Output Explained

JavaScript Syntax

Syntax Explained

Advertisement

JavaScript Statements

Statements Explained

JavaScript Comments

Comments Explained

JavaScript Variables

Variables Explained

JavaScript Arithmetic

Arithmetic Explained

JavaScript Assignment

Assignment Explained

JavaScript String Concatenation

Concatenation Explained

JavaScript Data Types

Data types Explained

JavaScript Objects

Objects Explained

JavaScript Functions

Functions Explained

JavaScript Events

Events Explained

JavaScript Strings

Strings Explained

JavaScript Numbers

Numbers Explained

JavaScript Number Methods

Numbers Methods Explained

JavaScript Maths

Maths Explained

JavaScript Random

Random Explained

JavaScript Dates

Dates Explained

JavaScript Arrays

Arrays Explained

JavaScript Array Methods

Array Methods Explained

JavaScript Array Sort

Array Sort Explained

JavaScript Array Iteration

Array Iteration Explained

JavaScript Type Conversion

Type Conversion Explained

JavaScript Booleans

Booleans Explained

JavaScript Comparisons

Comparisons Explained

JavaScript Conditionals

Conditionals Explained

JavaScript Loops

Loops Explained

JavaScript Error Handling

Errors Explained

JavaScript Regular Expressions

Javascript object properties.

Object Properties Explained

JSON Objects

JSON Object Properties Explained

JSON Arrays

JSON Arrays Explained

JSON Parse Explained

JSON Stringify

JSON Stringify Explained

JSON PHP Explained

JSON HTML Explained

JSON JSONP Explained

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

IMAGES

  1. JavaScript Modules

    task in javascript example

  2. Task Record System In JavaScript With Source Code

    task in javascript example

  3. To-Do List In HTML CSS JavaScript

    task in javascript example

  4. Task Management Ui Html,css And ,Javascript (Source Code)

    task in javascript example

  5. 32 Good Javascript Code Examples

    task in javascript example

  6. Task Records In JavaScript with Source Code

    task in javascript example

VIDEO

  1. JavaScript Example

  2. JavaScript Example

  3. Object in JavaScript

  4. HTML, CSS, Javascript Example explained

  5. JavaScript Accordion Tutorial in Hindi / Urdu

  6. 45. Task List App 1- Local Storage in JavaScript

COMMENTS

  1. 40 JavaScript Projects for Beginners

    40 JavaScript Projects for Beginners - Easy Ideas to Get Started Coding JS. The best way to learn a new programming language is to build projects. I have created a list of 40 beginner friendly project tutorials in Vanilla JavaScript, React, and TypeScript. My advice for tutorials would be to watch the video, build the project, break it apart ...

  2. 21 Easy JavaScript Projects for Beginners (Code included!)

    Implement the JavaScript code so that when you speak, whatever you say is transcribed on the lined paper on your screen. Bonus Challenge: To test your understanding of the concepts behind speech detection, your bonus challenge is this text to speech in different languages. 9. Sticky Navigation.

  3. How TO

    Learn how to create a simple and interactive to do list using HTML, CSS and JavaScript. Follow the step-by-step tutorial with examples and explanations on W3Schools, the world's largest web developer site.

  4. Event loop: microtasks and macrotasks

    A more detailed event loop algorithm (though still simplified compared to the specification ): Dequeue and run the oldest task from the macrotask queue (e.g. "script"). Execute all microtasks : While the microtask queue is not empty: Dequeue and run the oldest microtask. Render changes if any.

  5. Using microtasks in JavaScript with queueMicrotask()

    JavaScript. In the following code, we see a call to queueMicrotask() used to schedule a microtask to run. This call is bracketed by calls to log(), a custom function that outputs text to the screen. The code below schedules a timeout to occur in zero milliseconds, then enqueues a microtask.

  6. Introducing asynchronous JavaScript

    Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result. Many functions provided by browsers ...

  7. How to Use Async/Await in JavaScript with Example JS Code

    JavaScript is a single-threaded programming language which means that only one task can run at a time. It has a call stack and all the code is executed inside this call stack. Let's understand with an example. In the above example, we can see that we are logging two values in the console.

  8. The Modern JavaScript Tutorial

    Catastrophic backtracking. Sticky flag "y", searching at position. Methods of RegExp and String. Modern JavaScript Tutorial: simple, but detailed explanations with examples and tasks, including: closures, document and events, object oriented programming and more.

  9. Writing Asynchronous Tasks In Modern JavaScript

    Writing Asynchronous Tasks In Modern JavaScript. In this article, we are going to explore the evolution of JavaScript around asynchronous execution in the past era and how it changed the way we write and read code. We will start with the beginnings of web development, and go all the way to modern asynchronous pattern examples.

  10. In depth: Microtasks and the JavaScript runtime environment

    To run JavaScript code, the runtime engine maintains a set of agents in which to execute JavaScript code. Each agent is made up of a set of execution contexts, the execution context stack, a main thread, a set for any additional threads that may be created to handle workers, a task queue, and a microtask queue.

  11. Microtasks

    For that, the ECMA standard specifies an internal queue PromiseJobs, more often referred to as the "microtask queue" (V8 term). As stated in the specification: The queue is first-in-first-out: tasks enqueued first are run first. Execution of a task is initiated only when nothing else is running. Or, to put it more simply, when a promise is ...

  12. JavaScript Examples

    JS Examples. Factorial of a Number. All Examples. Miscellaneous. JavaScript Program To Print Hello World. JavaScript Program to Add Two Numbers. JavaScript Program to Find the Square Root. JavaScript Program to Calculate the Area of a Triangle. JavaScript Program to Swap Two Variables.

  13. 16 Best JavaScript Projects for Beginners [With Source Code]

    JavaScript Best Practices: Embrace clean, efficient, and well-organized JavaScript coding practices, emphasizing readability and maintainability, crucial for any web development project. Build This JavaScript Project Here. 5. JavaScript Calculator. What is this JavaScript project? In this JavaScript project, you'll construct a classic ...

  14. Demystifying JavaScript Event Queue: A Deep Dive into Microtasks, Tasks

    In this example, the setTimeout function adds a task to the task queue, ensuring that API requests are made only after a brief pause in typing, preventing excessive requests. Example 3: Animation ...

  15. JavaScript Exercises, Practice, Solution

    JavaScript is a cross-platform, object-oriented scripting language. It is a small and lightweight language. Inside a host environment ( a web browser), JavaScript can be connected to the objects of its environment to provide programmatic control over them. JavaScript contains a standard library of objects, such as Array, Date, and Math, and a ...

  16. Tasks in javascript?

    There are two parts of computing smth: IO and CPU. I want to make CPU computing works in time between ajax request sended and ajax request get answer from server. There is obstacle: from one function I run many tasks and this function must produce Task, that waits all runned tasks, process results of them and returns some value. That's all I want.

  17. JavaScript for loop (with Examples)

    In this tutorial, you will learn about the loops and about for loops in JavaScript with the help of examples. Courses Tutorials Examples . Try Programiz PRO. ... This program also gives the same output as the Example 3. You can accomplish the same task in many different ways in programming; programming is all about logic.

  18. How Functions Work in JavaScript

    Here is an example of a basic function that takes in two numbers and returns their sum: //index.js. function addNumbers(a, b) {. return a + b; } The function above, named " addNumbers ," takes in two parameters, a and b. The code inside the function body simply adds these two parameters together and returns the result.

  19. Object-oriented programming

    Object-oriented programming. Object-oriented programming (OOP) is a programming paradigm fundamental to many programming languages, including Java and C++. In this article, we'll provide an overview of the basic concepts of OOP. We'll describe three main concepts: classes and instances, inheritance, and encapsulation.

  20. 2,500+ JavaScript Practice Challenges // Edabit

    There is a single operator in JavaScript, capable of providing the remainder of a division operation. Two numbers are passed as parameters. The first parameter divided by the second parameter will have a remainder, possibly zero. Return that value. Examples remainder(1, 3) 1 remainder(3, 4) 3 remainder(-9, 45) -9 r …

  21. JavaScript Exercises

    Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.

  22. JavaScript Examples

    JavaScript Dates. Use Date () to display today's date and time Use getFullYear () display the year Use getTime () to calculate the number of milliseconds since 1970 Use setFullYear () to set a specific date Use toUTCString () to convert today's date (according to UTC) to a string Use getDay () to display the weekday as a number Use getDay ...