• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Tasks in javascript?

Essence of the question.

The real reason why I ask this question - not because I want solve my problem. I want to know how to work with tasks in JavaScript. I don't need thread paralleling and other stuff. 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. Of course, if you post another way to solve my problem, I will vote for your answer and can set it as solution if there are no other answers about tasks.

Why I describe my problem, not just asking about tasks? Ask guys who minused and closed this question a time ago.

My problem: I want to traverse a tree in JavaScript to find the smallest possible parsing. I have a dictionary of words stored in the form of a trie . When a user gives an input string, I need to get a count of words that match the input string and is the shortest combination of words.

  • My dictionary contains these words: my, code, js, myj, scode
  • A user types myjscode
  • I traverse my tree of words and find that the input matches myj + scode and my + js + code
  • Since the first parsing is the shortest, my function returns 2 (the number of words in the shortest parsing)

My dictionary tree is huge, so I can't load it fully. To fix this, I want to do some lazy-loading. Each node of the tree is either loaded and points to child nodes or is not loaded yet and contains a link to the data to be loaded.

So, I need to make node look up calls while I'm traversing the tree. Since these calls are asynchronous, I want to be able to explore other traversals while loading tree nodes. This will improve the response time for the user.

How I want to solve this problem:

My lookup function will return a task. I can call that task and get its results. Once I traverse to the loaded node, I can then make multiple calls to load child nodes and each call returns a task. Since these "tasks" are individual bits of functionality, I can queue them up and execute them while I'm waiting for ajax calls to return.

So, I want to know which library I can use, or how I can emulate tasks in javascript (I'm thinking of tasks as they exist in C#).

There is restriction: no server-side code, only ajax to precompiled dictionaries in javascript. Why? It has to be used as password complexity checker.

Community's user avatar

  • github.com/caolan/async –  Deathspike Jul 9, 2013 at 15:16
  • 1 Aaaaa. Guys. What is unclear in my question? I want to get ability of creating tasks and waiting them, and processing their results. I have provided to you example, how can I do that in c#; and I want to do that same in Javascript. I asked you for a library, because I haven't googled it. What's unclear? –  Viktor Lova Jul 9, 2013 at 15:39
  • @RoelvanUden well, async.js is nice library but it describes asynchron work it terms of processFunc(what, whatAfter?) . But I need to to populate tasks and wait their end. Can you vote for reopen? –  Viktor Lova Jul 9, 2013 at 16:20
  • @RustyTheBoyRobot can you nominate question for reopen? –  Viktor Lova Jul 9, 2013 at 16:23
  • let us continue this discussion in chat –  RustyTheBoyRobot Jul 9, 2013 at 16:33

2 Answers 2

You say in your question:

Of course, if you post another way to solve my problem, I will vote for your answer and can set it as solution if there are no other answers about tasks.

Good; sorry, but I don't think that c# style tasks is the right solution here.

I'll accept (although I don't think it's correct) your assertion that for security reasons you have to do everything client-side. As an aside, might I point out that if you are scared of somebody snooping (because you have a security weakness) then passing lots of requests for part of the password is just as insecure as passing one request? Sorry, I appear to have done so without consent!

Nonetheless, I will attempt to answer with a broad outline how I would approach your problem if, indeed, you had to do it in JavaScript; I would use promises. Probably jQuery's Deferred implementation, to be specific. I'll give a very rough pseudo-code outline here.

You start with a nicely structured Trie. Using recursion I would build up a nicely structured "solution tree", which would be a nested array of arrays; this would give the flexibility of being able to respond to the user with a specific message... however, since you seem prepared to lose that bonus and only want a single digit as a solution, I will outline a slightly simpler approach that you could, if needed, adapt to return arrays of the form (from your example):

I mention this structure here also, partly, as it helps explain the approach I am adopting.

I will refer to "nodes" and "valueNodes" in your Trie. I consider "nodes" to be anything and "valueNodes" to be nodes with values.

The recursive promiseToResolveRemainder will resolve 0 for "couldn't do it"; it will only reject the promise if something went wrong (say, the webservice wasn't available).

Dodgy, hacky, untested Pseudo-code

I am not particularly proud of this untested kludgy attempt at code (and I'm not about to write your solution for you!), but I am proud of the approach and am sure that it will yield a robust, reliable and efficient solution to your problem. Unfortunately, you seem to be dependent on a lot of webService calls... I would be very tempted, therefore, to abstract away any calls to the webService and check them through a local cache first.

AndyH's user avatar

  • Nice work, Andy. Promises (in this case, jQuery's Deferred ) are exactly what @nsinreal is looking for. –  Jordan Gray Jul 17, 2013 at 15:54
  • Why thank you Jordan; I see you got there six minutes before me! But maybe not as extensively... I hope I've read the original question correctly and read between the lines where necessary... it sounds like the OP was going to build the tree and parse the tree as separate concerns... hopefully I've been able to show that one could kill two birds with one stone using recursion! :) –  AndyH Jul 17, 2013 at 16:00
  • @AndyH: well, what I must say. I haven't read your code, so don't care about it. I have read just now documentation about [ deferred object ] ( api.jquery.com/category/deferred-object ) and it seems to provide nice syntax for long async operations. Thanks. That's all. I'll mark your answer as right –  Viktor Lova Jul 17, 2013 at 17:03
  • @AndyH: the real reason, why I don't want to use server-side - I want to write library. So, cuz that is a password checker, I can't use my server, cuz that supposed to be used by many guys, on server-side there can be PHP, Node.js, ASP.NET or anything and I can't write this tool for all languages. Thanks for your answer. –  Viktor Lova Jul 17, 2013 at 17:07
  • @nsinreal I'm glad that the concept was useful to you; I still don't quite understand your non-server-side argument, but I guess it's academic. I'm going to assume that you have salts and hashes for your actual passwords and that any communication between the client and the server (especially when negotiating new passwords) is over a secure connection... if so then I don't see the problem doing the work on the server; and if not, I don't see how you can have any real security at all, and running the code on the client won't gain you a whole lot of anything! –  AndyH Jul 19, 2013 at 8:10

Not sure this is what you are looking for, but you might try WebWorkers.

A simple example is at: https://github.com/afshinm/50k but you can google for more.

Note - web workers will be highly browser dependent and do not run in a separate task on the machine.

sasbury's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct .

Not the answer you're looking for? Browse other questions tagged javascript or ask your own question .

  • The Overflow Blog
  • Like Python++ for AI developers
  • Being creative with math: The immersive artist who traded a sketchpad for a...
  • Featured on Meta
  • Alpha test for short survey in banner ad slots starting on week of September...
  • What should be next for community events?
  • OverflowAI Search is now available for alpha testing (September 13, 2023)
  • Temporary policy: Generative AI (e.g., ChatGPT) is banned
  • Expanding Discussions: Let's talk about curation
  • Update on Collectives and Discussions

Hot Network Questions

  • Can the collapse of the wave function be modelled as a quantum system on its own?
  • Is there any way to force the viewport to orbit the geometry center of the selections not the origin point
  • What happens when a sniper picks up a bigger gun in Mutants and Masterminds?
  • Understand what ee.data.getTaskStatus returns
  • How to describe the Sun's location to an alien from our Galaxy?
  • general principles of piercing the protective cover of unfrozen microwave ready meals
  • story ID question: planets in interstellar space run on "slow speed" with people awaking for a few years, then sleeping for centuries
  • History of right hand rule
  • Why does ranges::for_each return the function?
  • How would you deal with an (actual) etymology that makes no sense in-game?
  • Why would people join a bloc party?
  • Is 明朝 a typo for 早朝?
  • Buying an airplane ticket for someone without a last name/surname
  • Low consumption resistor pair
  • Geometrical verifications for Algebraic formulae
  • Can a homeowners insurance demand that I perform specific maintenance at my home?
  • I (rev)?(pal)? the source code, you (rev)?(pal)? the input!
  • I want to ask about two recursive sequences
  • What is mode borrowing?
  • Is a passenger who is flying the aircraft liable for regulations that they violate?
  • My Medieval kingdom has birth control, why is the population so high?
  • How can sleeper agents locate and count each-other?
  • Iteration counts of AMG solver changes in parallel
  • What is the purpose of this indoor crawlspace grate/vent?

task in javascript example

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Popular Tutorials

Popular examples, reference materials, learn python interactively, javascript examples.

The best way to learn JavaScript is by practicing examples. The page contains examples on basic concepts of JavaScript. You are advised to take the references from these examples and try them on your own.

JS Examples

  • Print Hello World
  • Generate a Random Number
  • Check Prime Number
  • Factorial of a Number
  • 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
  • Javascript Program to Solve Quadratic Equation
  • JavaScript Program to Convert Kilometers to Miles
  • Javascript Program to Convert Celsius to Fahrenheit
  • Javascript Program to Generate a Random Number
  • Javascript Program to Check if a number is Positive, Negative, or Zero
  • Javascript Program to Check if a Number is Odd or Even
  • JavaScript Program to Find the Largest Among Three Numbers
  • JavaScript Program to Check Prime Number
  • JavaScript Program to Print All Prime Numbers in an Interval
  • JavaScript Program to Find the Factorial of a Number
  • JavaScript Program to Display the Multiplication Table
  • JavaScript Program to Print the Fibonacci Sequence
  • JavaScript Program to Check Armstrong Number
  • JavaScript Program to Find Armstrong Number in an Interval
  • JavaScript Program to Make a Simple Calculator
  • JavaScript Program to Find the Sum of Natural Numbers
  • JavaScript Program to Check if the Numbers Have Same Last Digit
  • JavaScript Program to Find HCF or GCD
  • JavaScript Program to Find LCM
  • JavaScript Program to Find the Factors of a Number
  • JavaScript Program to Find Sum of Natural Numbers Using Recursion
  • JavaScript Program to Guess a Random Number
  • JavaScript Program to Shuffle Deck of Cards
  • JavaScript Program to Display Fibonacci Sequence Using Recursion
  • JavaScript Program to Find Factorial of Number Using Recursion
  • JavaScript Program to Convert Decimal to Binary
  • JavaScript Program to Find ASCII Value of Character
  • JavaScript Program to Check Whether a String is Palindrome or Not
  • JavaScript Program to Sort Words in Alphabetical Order
  • JavaScript Program to Replace Characters of a String
  • JavaScript Program to Reverse a String
  • JavaScript Program to Create Objects in Different Ways
  • JavaScript Program to Check the Number of Occurrences of a Character in the String
  • JavaScript Program to Convert the First Letter of a String into UpperCase
  • JavaScript Program to Count the Number of Vowels in a String
  • JavaScript Program to Remove a Property from an Object
  • JavaScript Program to Check Whether a String Starts and Ends With Certain Characters
  • JavaScript Program to Check if a Key Exists in an Object
  • JavaScript Program to Clone a JS Object
  • JavaScript Program to Loop Through an Object
  • JavaScript Program to Merge Property of Two Objects
  • JavaScript Program to Count the Number of Keys/Properties in an Object
  • JavaScript Program to Add Key/Value Pair to an Object
  • JavaScript Program to Replace All Occurrences of a String
  • JavaScript Program to Create Multiline Strings
  • JavaScript Program to Format Numbers as Currency Strings
  • JavaScript Program to Generate Random String
  • JavaScript Program to Check if a String Starts With Another String
  • JavaScript Program to Trim a String
  • JavaScript Program to Convert Objects to Strings
  • JavaScript Program to Check Whether a String Contains a Substring
  • JavaScript Program to Compare Two Strings
  • JavaScript Program to Encode a String to Base64
  • JavaScript Program to Replace all Instances of a Character in a String
  • JavaScript Program to Replace All Line Breaks with
  • JavaScript Program to Display Date and Time
  • JavaScript Program to Check Leap Year
  • JavaScript Program to Format the Date
  • Javascript Program to Display Current Date
  • JavaScript Program to Compare The Value of Two Dates
  • JavaScript Program to Create Countdown Timer
  • JavaScript Program to Remove Specific Item From an Array
  • JavaScript Program to Check if An Array Contains a Specified Value
  • JavaScript Program to Insert Item in an Array
  • JavaScript Program to Append an Object to An Array
  • JavaScript Program to Check if An Object is An Array
  • JavaScript Program to Empty an Array
  • JavaScript Program to Add Element to Start of an Array
  • JavaScript Program to Remove Duplicates From Array
  • JavaScript Program to Merge Two Arrays and Remove Duplicate Items
  • JavaScript Program to Sort Array of Objects by Property Values
  • JavaScript Program to Create Two Dimensional Array
  • JavaScript Program to Extract Given Property Values from Objects as Array
  • JavaScript Program to Compare Elements of Two Arrays
  • JavaScript Program to Get Random Item From an Array
  • JavaScript Program To Perform Intersection Between Two Arrays
  • JavaScript Program to Split Array into Smaller Chunks
  • JavaScript Program to Include a JS file in Another JS file
  • JavaScript Program to Get File Extension
  • JavaScript Program To Check If A Variable Is undefined or null
  • JavaScript Program to Set a Default Parameter Value For a Function
  • JavaScript Program to Illustrate Different Set Operations
  • Javascript Program to Generate a Random Number Between Two Numbers
  • JavaScript Program To Get The Current URL
  • JavaScript Program to Validate An Email Address
  • JavaScript Program to Check If a Variable is of Function Type
  • JavaScript Program To Work With Constants
  • JavaScript Program to Pass Parameter to a setTimeout() Function
  • JavaScript Program to Generate a Range of Numbers and Characters
  • JavaScript Program to Perform Function Overloading
  • JavaScript Program to Implement a Stack
  • JavaScript Program to Implement a Queue
  • JavaScript Program to Check if a Number is Float or Integer
  • JavaScript Program to Pass a Function as Parameter
  • JavaScript Program to Get the Dimensions of an Image
  • JavaScript Program to Remove All Whitespaces From a Text
  • JavaScript Program to Write to Console
  • JavaScript Program to Convert Date to Number
  • FR Français
  • ID Indonesia
  • IT Italiano
  • UK Українська

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

The Modern JavaScript Tutorial

How it's done now. From the basics to advanced topics with simple, but detailed explanations.

Table of contents

Main course contains 2 parts which cover JavaScript as a programming language and working with a browser. There are also additional series of thematic articles.

The JavaScript language

Here we learn JavaScript, starting from scratch and go on to advanced concepts like OOP.

We concentrate on the language itself here, with the minimum of environment-specific notes.

  • An Introduction to JavaScript
  • Manuals and specifications
  • Code editors
  • Developer console
  • Hello, world!
  • Code structure
  • The modern mode, "use strict"
  • Interaction: alert, prompt, confirm
  • Type Conversions
  • Basic operators, maths
  • Comparisons
  • Conditional branching: if, '?'
  • Logical operators
  • Nullish coalescing operator '??'
  • Loops: while and for
  • The "switch" statement
  • Function expressions
  • Arrow functions, the basics
  • JavaScript specials
  • Debugging in the browser
  • Coding Style
  • Automated testing with Mocha
  • Polyfills and transpilers
  • Object references and copying
  • Garbage collection
  • Object methods, "this"
  • Constructor, operator "new"
  • Optional chaining '?.'
  • Symbol type
  • Object to primitive conversion
  • Methods of primitives
  • Array methods
  • Map and Set
  • WeakMap and WeakSet
  • Object.keys, values, entries
  • Destructuring assignment
  • Date and time
  • JSON methods, toJSON
  • Recursion and stack
  • Rest parameters and spread syntax
  • Variable scope, closure
  • The old "var"
  • Global object
  • Function object, NFE
  • The "new Function" syntax
  • Scheduling: setTimeout and setInterval
  • Decorators and forwarding, call/apply
  • Function binding
  • Arrow functions revisited
  • Property flags and descriptors
  • Property getters and setters
  • Prototypal inheritance
  • F.prototype
  • Native prototypes
  • Prototype methods, objects without __proto__
  • Class basic syntax
  • Class inheritance
  • Static properties and methods
  • Private and protected properties and methods
  • Extending built-in classes
  • Class checking: "instanceof"
  • Error handling, "try...catch"
  • Custom errors, extending Error
  • Introduction: callbacks
  • Promises chaining
  • Error handling with promises
  • Promise API
  • Promisification
  • Async/await
  • Async iteration and generators
  • Modules, introduction
  • Export and Import
  • Dynamic imports
  • Proxy and Reflect
  • Eval: run a code string
  • Reference Type
  • Unicode, String internals

Browser: Document, Events, Interfaces

Learning how to manage the browser page: add elements, manipulate their size and position, dynamically create interfaces and interact with the visitor.

  • Browser environment, specs
  • Walking the DOM
  • Searching: getElement*, querySelector*
  • Node properties: type, tag and contents
  • Attributes and properties
  • Modifying the document
  • Styles and classes
  • Element size and scrolling
  • Window sizes and scrolling
  • Coordinates
  • Introduction to browser events
  • Bubbling and capturing
  • Event delegation
  • Browser default actions
  • Dispatching custom events
  • Mouse events
  • Moving the mouse: mouseover/out, mouseenter/leave
  • Drag'n'Drop with mouse events
  • Pointer events
  • Keyboard: keydown and keyup
  • Form properties and methods
  • Focusing: focus/blur
  • Events: change, input, cut, copy, paste
  • Forms: event and method submit
  • Page: DOMContentLoaded, load, beforeunload, unload
  • Scripts: async, defer
  • Resource loading: onload and onerror
  • Mutation observer
  • Selection and Range
  • Event loop: microtasks and macrotasks

Additional articles

  • Popups and window methods
  • Cross-window communication
  • The clickjacking attack
  • ArrayBuffer, binary arrays
  • TextDecoder and TextEncoder
  • File and FileReader
  • Fetch: Download progress
  • Fetch: Abort
  • Fetch: Cross-Origin Requests
  • URL objects
  • XMLHttpRequest
  • Resumable file upload
  • Long polling
  • Server Sent Events
  • Cookies, document.cookie
  • LocalStorage, sessionStorage
  • Bezier curve
  • CSS-animations
  • JavaScript animations
  • From the orbital height
  • Custom elements
  • Template element
  • Shadow DOM slots, composition
  • Shadow DOM styling
  • Shadow DOM and events
  • Patterns and flags
  • Character classes
  • Unicode: flag "u" and class \p{...}
  • Anchors: string start ^ and end $
  • Multiline mode of anchors ^ $, flag "m"
  • Word boundary: \b
  • Escaping, special characters
  • Sets and ranges [...]
  • Quantifiers +, *, ? and {n}
  • Greedy and lazy quantifiers
  • Capturing groups
  • Backreferences in pattern: \N and \k<name>
  • Alternation (OR) |
  • Lookahead and lookbehind
  • Catastrophic backtracking
  • Sticky flag "y", searching at position
  • Methods of RegExp and String
  • 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 …)
  • © 2007—2023  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

The Online Coding & Design School With A

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

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

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

In this tutorial, we are going to learn how to use Async/Await in JavaScript.

But before we get there, we should understand a few topics like:

  • Event loops

What are Event Loops in JavaScript?

Event loops are one of the most important aspects of JavaScript.

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.

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--8-

In the above example, we can see that we are logging two values in the console.

When the First() finishes its execution, it will be popped out of the call stack and the event loop will go down to the next line. The next line will be stored in the call stack and will be flagged for execution.

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--9-

Our console will print the following result:

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--18-

To understand things better, let’s take a look at another example.

As usual, our code will move into the call stack and the event loop will loop through line by line.

We will get “First!” in the console and it will be moved out of the call stack.

Now, the event loop will move to the second line and push it into the call stack. It will encounter the setTimeout function, which is a Macro task, and it will be executed in the next event Loop.

And now, you might be wondering what a Macro task is. Well, it's a task that runs after all of the tasks in the Event Loop, or you might say, in the other Event Loop. The SetTimeout and SetInterval functions can be the example of a Macro task which runs after all of the other tasks are completed.

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--19-

Finally, the final line of code will be executed. We will get First in our console, then Final, and then Timed Out.

How Do Callback Functions Work in JavaScript?

Callback functions are those functions that have been passed to another function as an argument.

Let’s take a look at an example.

We have an array that contains the list of Star Wars movies and a function getMovies() to fetch the list.

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--20-

Let’s create another function called createMovie() . It will be used to add a new movie.

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--20--1

But the problem here is we are not getting the third movie on the console. That is because createMovie() takes longer than getMovies() . The createMovie() function took two seconds but getMovies() took only one second.

In other words, getMovies() runs before createMovies() and the list of Movies is already displayed.

To solve this, we can use Callbacks .

In createPost() , pass a function callback and call the function right after the new movie is pushed (instead of waiting two seconds).

Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--21--2

Now we get the updated list of movies.

How Do Promises Work in JavaScript?

A promise is a value that may produce a value in the future. That value can either be resolved or unresolved (in some error cases, like a network failure). It works like a real-life promise.

It has three states: fulfilled, rejected, or pending.

  • Fulfilled: onFulfilled() will be called (for example, resolve() was called).
  • Rejected: onRejected() will be called (for example,   reject() was called).
  • Pending: not yet fulfilled or rejected.

Promise takes two parameters, resolve and reject. When something goes wrong, reject is called, or else resolve is called.

If we get an error, it will be something like ‘Error: Something went wrong!’, and if not, the promise will resolve.

Once the promise is resolved, it calls for the .then() keyword and getMovies() .

Finally, How Does Async/Await Work in JavaScript

Async means asynchronous. It allows a program to run a function without freezing the entire program. This is done using the Async/Await keyword.

Async/Await makes it easier to write promises. The keyword ‘async’ before a function makes the function return a promise, always. And the keyword await is used inside async functions, which makes the program wait until the Promise resolves.

The function execution “pauses” at the (*) line and resumes when the promise is fulfilled, with result becoming its result. So the code above shows “done!” in two seconds.

Let's take a look at a practice example.

In the above example, getMovies() at the (*) line is waiting for createMovies() to be executed in the async function.

In other words, createMovies() is async, so getMovies() will only run after createMovies() is done.

Now you know all the basics of Event Loops, Callbacks, Promises and Async/Await. These features were introduced in ECMAScript 2017, and they've made reading and writing JS code much easier and more effective.

That’s all folks! Happy learning and experimenting,

I build projects to learn how code works. And while I am not coding, I enjoy writing poetry and stories, playing the piano, and cooking delicious meals.

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)

Test your skills: Object-oriented JavaScript

The aim of this skill test is to assess whether you've understood our Classes in JavaScript article.

Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen , jsFiddle , or Glitch to work on the tasks.

If you get stuck, then ask us for help — see the Assessment or further help section at the bottom of this page.

Note: In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version).

In this task we provide you with the start of a definition for a Shape class. It has three properties: name , sides , and sideLength . This class only models shapes for which all sides are the same length, like a square or an equilateral triangle.

We'd like you to:

  • Add a constructor to this class. The constructor takes arguments for the name , sides , and sideLength properties, and initializes them.
  • Add a new method calcPerimeter() method to the class, which calculates its perimeter (the length of the shape's outer edge) and logs the result to the console.
  • Create a new instance of the Shape class called square . Give it a name of square , 4 sides , and a sideLength of 5 .
  • Call your calcPerimeter() method on the instance, to see whether it logs the calculation result to the browser's console as expected.
  • Create a new instance of Shape called triangle , with a name of triangle , 3 sides and a sideLength of 3 .
  • Call triangle.calcPerimeter() to check that it works OK.

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

Next we'd like you to create a Square class that inherits from Shape , and adds a calcArea() method that calculates the square's area. Also set up the constructor so that the name property of Square object instances is automatically set to square , and the sides property is automatically set to 4 . When invoking the constructor, you should therefore just need to provide the sideLength property.

Create an instance of the Square class called square with appropriate property values, and call its calcPerimeter() and calcArea() methods to show that it works OK.

Assessment or further help

You can practice these examples in the Interactive Editors above.

If you would like your work assessed, or are stuck and want to ask for help:

  • Put your work into an online shareable editor such as CodePen , jsFiddle , or Glitch . You can write the code yourself, or use the starting point files linked to in the above sections.
  • A descriptive title such as "Assessment wanted for OOJS 1 skill test".
  • Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment.
  • A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code.
  • A link to the actual task or assessment page, so we can find the question you want help with.
  • DSA with JS - Self Paced
  • JavaScript A to Z Complete Guide
  • JS Operator
  • JS Examples
  • JS Questions
  • JS Tutorial
  • Free JavaScript Course
  • Web-Technology
  • Write an Interview Experience
  • Share Your Campus Experience
  • Introduction to JavaScript Course – Learn how to build a task tracker using JavaScript
  • JavaScript Course What is JavaScript ?
  • JavaScript Course Printing Hello World in JavaScript
  • JavaScript Course Understanding Code Structure in JavaScript
  • JavaScript Course Variables in JavaScript
  • JavaScript Data Types
  • JavaScript Course Operators in JavaScript
  • JavaScript Course | Practice Quiz-1
  • JavaScript Course Interaction With User
  • JavaScript Course Logical Operators in JavaScript
  • JavaScript Course Conditional Operator in JavaScript
  • JavaScript Course Prompt Example
  • JavaScript Course | Practice Quiz-2
  • JavaScript Course Loops in JavaScript
  • JavaScript Course Functions in JavaScript
  • JavaScript Course Objects in JavaScript
  • JavaScript Course | Practice Quiz-3

JavaScript Course Task Tracker Project

In this final article of this course, we will learn how to make a simple javascript application where we can add tasks, delete tasks and edit them too. Pure(Vanilla) JavaScript has been used and we will also make use of DOM manipulation a lot so one of the main prerequisites is HTML | DOM .

Project Structure:

index.html styles.css list.js

Project Preview:

Course Tracker Project

Example: In this example code, we have built the course tracker project using javascript.

Output: Click here to see live code output

Explanation: 

The above HTML code contains simple list tags and one text field which we will populate with text when we add, or delete tasks. Certain classes are assigned which we make use of while getting that particular element by DOM or by styling it inside the styles.css file. All the above content is inside a div with the class ‘container’ that has its own styling and attributes.

Explanation

Part 1: The way this function works is that it takes the ‘inputString’ i.e. the text that we pass inside the HTML text field as a task and then it creates several elements using DOM properties and appends their specific classes. After appending we insert all the elements inside the list as listItems. Part 2: This addTask function is called when we click the button ‘addButton'(line 115) and then inside it we create a listItem with the value the user entered and then check the value, as it must not be an empty string then we simply add the above value inside the ‘inputTaskHolder’ and finally setting the value inside it as an empty string before calling the ‘bindFunction’.

Part 3: This code function is used to edit an existing task and we do so by keeping track of the parent node and then a simple if-else check whether the ‘editMode’ button is clicked or not if clicked then simply assign the value of the label innerText to value inside the editInput, if not then vice versa. Then after editing, we toggle the value of the ‘editMode’ as we have edited.

Part 4: In this part, we delete a task, and the way we do it is by making use of the parent node of the current node and then storing the parent of the parent node, and then simply deleting the child of this node.

Part 5: In this function, we mark the task as complete by simply appending the child of the parent node inside completeTaskHolder element and then calling the bindFunction.

Part 6: In this function, we mark the task as incomplete by simply appending the child of the parent node inside inCompleteTaskHolder element and then calling the bindFunction.

Part 7: In this part, we call the BindFunction where we respond to several user interaction activities and make several buttons work.

Part 8: In this final section, we iterate over several parts binding children with the help of for loop inside the incomplete and complete TaskHolder element.

Please Login to comment...

Improve your coding skills with practice.

  • Getting Started

Logo

Popular Articles

How to reload the page, html5 navigation: using an anchor tag for hypertext, how to create indents and bullet lists, top online courses to learn seo, sellzone marketing tool for amazon review, the top database plugins for wordpress, the revolutionary es6 rest and spread operators.

Logo

DEV Community

Victor Hazbun

Posted on Jul 3, 2019

Daily tasks with JavaScript arrays

Arrays are everywhere and we have to use them all the time.

I created this article specially for you, so you have a quick reference of the most common things you usually do with Arrays on a daily basis 😊

Table Of Contents 📋

Find in array 🔍, filter an array 🕵️, loop arrays 🔁, sort an array of objects ⬆️ ⬇️, add an element to an array 🗳️, remove an element from an array 🗑️, create an array from an existing array (map) 📦, accumulate array values (reduce) 🐝, combine arrays (concat) 🍔.

Hope you enjoyed this reading 🥳. Feel free to save this article into your bookmarks 🔖 so you have it available at your fingertips.

Top comments (12)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

dennisk profile image

  • Location Netherlands
  • Work Lead Full Stack Developer at Learned
  • Joined Jan 21, 2019

In Sort array of objects usersSortedByScoreDesc still returns asc i believe?

But great reference all together!

victorhazbun profile image

  • Email [email protected]
  • Location Colombia
  • Work Software engineer at Bonsai Labs
  • Joined Jun 22, 2019

Fixed! Thanks again!

Did you also include the fix? The result is still the same for me even after a hard refresh!

Please refresh again.

Worked for you now?

Yes it works now! Altough the json.stringify was actually nice to make it more readable :)

I used it for debugging purposes, but now you give me a good idea 😁 - I will put it back everywhere later.

There is another interesting blog I published yesterday 👉 dev.to/victorhazbun/modern-javascr...

zafer profile image

  • Location Istanbul
  • Joined Mar 16, 2019

Broken chrome tab after too many embed code editor :) It would be better if it had been placed less opts.

I will try to split my blog posts, i.e. Part 1, Part 2, etc. Since the embed code editor gives the reader the ability to play with the code. 😅

You bet, I will continue adding more of this for you.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

skipperhoa profile image

Example Of Using The GenerateStaticParams() In NextJs

Nguyễn Thanh Hòa - Sep 26

pavelkeyzik profile image

Hey Web Devs! What are you learning this week? 😋

Pavel Keyzik - Sep 25

janhommes profile image

Who does even need Microfronteds?

Jan Hommes - Sep 25

xmohammedawad profile image

🔥What are the differences between const, let, and var? 10 Must-Know Questions for Junior Developers💡🚀

Mohammed Awad - Sep 27

Once suspended, victorhazbun will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, victorhazbun will be able to comment and publish posts again.

Once unpublished, all posts by victorhazbun will become hidden and only accessible to themselves.

If victorhazbun is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Victor Hazbun.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag victorhazbun:

victorhazbun consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.

Unflagging victorhazbun will restore default visibility to their posts.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

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 functions.

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name , followed by parentheses () .

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas: ( parameter1, parameter2, ... )

The code to be executed, by the function, is placed inside curly brackets: {}

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:

  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

You will learn a lot more about function invocation later in this tutorial.

Advertisement

Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.

Functions often compute a return value . The return value is "returned" back to the "caller":

Calculate the product of two numbers, and return the result:

Why Functions?

With functions you can reuse code

You can write code that can be used many times.

You can use the same code with different arguments, to produce different results.

The () Operator

The () operator invokes (calls) the function:

Convert Fahrenheit to Celsius:

Accessing a function with incorrect parameters can return an incorrect answer:

Accessing a function without () returns the function and not the function result:

As you see from the examples above, toCelsius refers to the function object, and toCelsius() refers to the function result.

Functions Used as Variable Values

Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.

Instead of using a variable to store the return value of a function:

You can use the function directly, as a variable value:

You will learn a lot more about functions later in this tutorial.

Local Variables

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables can only be accessed from within the function.

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.

Test Yourself With Exercises

Execute the function named myFunction .

Start the Exercise

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. Review Our JavaScript Assignment Template

    task in javascript example

  3. JavaScript instructions of the given task

    task in javascript example

  4. Understanding JavaScript Call Stack, Task Queue and Event Loop

    task in javascript example

  5. Solved Task 1: JavaScript Basics • Exercise 1: Write a

    task in javascript example

  6. JavaScript: Basic Functions and Examples

    task in javascript example

VIDEO

  1. javascript

  2. Some Javascript programming

  3. JavaScript Example

  4. Outputs in JavaScript

  5. JavaScript in Forty Minutes

  6. #JavaScript #Tutorial Part -2 (Functions and Events)

COMMENTS

  1. JavaScript Exercises, Practice, Solution

    Happy Coding! Latest Exercises : Object Oriented Programming JavaScript Error Handling JavaScript Event Handling. List of JavaScript Exercises : JavaScript Basic [ 150 Exercises with Solution ] JavaScript Fundamental (ES6 version) Part-I [ 150 Exercises with Solution ] JavaScript Fundamental (ES6 version) Part-II [ 116 Exercises with Solution ]

  2. Using microtasks in JavaScript with queueMicrotask()

    A task is any JavaScript code which is scheduled to be run by the standard mechanisms such as initially starting to run a program, an event callback being run, or an interval or timeout being fired. These all get scheduled on the task queue. Tasks get added to the task queue when:

  3. 40 JavaScript Projects for Beginners

    Jessica Wilkins. 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 and rebuild it your own way.

  4. JavaScript Exercises

    Exercises. We have gathered a variety of JavaScript exercises (with answers) for each JavaScript Chapter. Try to solve an exercise by editing some code, or show the answer to see what you've done wrong. Count Your Score. You will get 1 point for each correct answer. Your score and total score will always be displayed. Start JavaScript Exercises.

  5. Tasks in javascript?

    Example: My dictionary contains these words: my, code, js, myj, scode. A user types myjscode. I traverse my tree of words and find that the input matches myj + scode and my + js + code. Since the first parsing is the shortest, my function returns 2 (the number of words in the shortest parsing) My Problem.

  6. JavaScript Examples

    The best way to learn JavaScript is by practicing examples. The page contains examples on basic concepts of JavaScript. You are advised to take the references from these examples and try them on your own. Popular Examples. JS Examples. Print Hello World. JS Examples. Generate a Random Number. JS Examples. Check Prime Number. JS Examples.

  7. Event loop: microtasks and macrotasks

    Examples of tasks: When an external script <script src="..."> loads, the task is to execute it. When a user moves their mouse, the task is to dispatch mousemove event and execute handlers. When the time is due for a scheduled setTimeout, the task is to run its callback. …and so on.

  8. JavaScript Examples

    JavaScript Booleans. Display the value of Boolean (10 > 9) Display the value of 10 > 9 Everything with a real value is true The Boolean value of zero is false The Boolean value of minus zero is false The Boolean value of an empty string is false The Boolean value of undefined is false The Boolean value of null is false The Boolean value of ...

  9. 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.

  10. How TO

    Step 1) Add HTML: Example. <div id="myDIV" class="header"> <h2> My To Do List </h2> <input type="text" id="myInput" placeholder="Title..."> <span onclick="newElement ()" class="addBtn"> Add </span> </div> <ul id="myUL"> <li> Hit the gym </li> <li class="checked"> Pay bills </li> <li> Meet George </li> <li> Buy eggs </li> <li> Read a book </li>

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

    Very Easy. Add to bookmarks. Add to collection. Return the Sum of Two Numbers. Create a function that takes two numbers as arguments and returns their sum. Examples addition (3, 2) 5 addition (-3, -6) -9 addition (7, 3) 10 Notes Don't forget to return the result. If you get stuck on a challenge, find help in the Resources tab.

  12. JavaScript Tutorial

    JavaScript is one of the 3 languages all web developers must learn: 1. HTML to define the content of web pages. 2. CSS to specify the layout of web pages. 3. JavaScript to program the behavior of web pages. This tutorial covers every version of JavaScript: The Original JavaScript ES1 ES2 ES3 (1997-1999)

  13. Object-oriented programming

    English (US) Object-oriented programming. Previous. 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.

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

    Beginner JavaScript Projects. Mouseover Element. Clock. Magic 8 Ball. Build a To-Do List. Epic Mix Playlist. Pet Rescue. Drum Kit. Speech Detection. Sticky Navigation. Geolocation. Movie App. Name Tags. Intermediate JavaScript Projects. Tone.js. Election Map. Login Authentication.

  15. 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.

  16. Test your skills: Object-oriented JavaScript

    A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with.

  17. JavaScript Course Task Tracker Project

    Example: In this example code, we have built the course tracker project using javascript. HTML. CSS. Javascript. <!DOCTYPE html> <html> <head> <title>Task Tracker</title> <link rel="stylesheet" href="styles.css" type="text/css" media="screen" charset="utf-8"> </head> <body> <div class="container"> <p>

  18. 15 Javascript Projects for Beginners

    1. Master the navbar. Learning how to build modern web page navigation with JavaScript is a time-worthy and skill-building task — especially if you anticipate working on web pages in the future. JavaScript can create slide menus, interactive tabs, modals, and the three-barred hamburger menu. Hamburger menus are handy on smaller screens.

  19. Top 10 JavaScript Snippets for Common Tasks

    Top 10 JavaScript Snippets for Common Tasks. By Scott Clark. June 11, 2010. Web developers often use JavaScript for common tasks on their websites. In this tutorial we'll show you the top 10 JavaScript snippets you can use on your webpages by just cutting and pasting! In this article we're going to cover the following popular script snippets!

  20. Daily tasks with JavaScript arrays

    Daily tasks with JavaScript arrays. # javascript. Arrays are everywhere and we have to use them all the time. I created this article specially for you, so you have a quick reference of the most common things you usually do with Arrays on a daily basis 😊. Table Of Contents 📋. Find in array 🔍. Filter an array 🕵️. Loop arrays 🔁.

  21. JavaScript Functions

    A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when "something" invokes it (calls it). Example. // Function to compute the product of p1 and p2. function myFunction (p1, p2) { return p1 * p2; } Try it Yourself » JavaScript Function Syntax.