• DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

JavaScript Exercises, Practice Questions and Solutions

JavaScript Exercise covers interactive quizzes, track progress, and enhance coding skills with our engaging portal. Ideal for beginners and experienced developers, Level up your JavaScript proficiency at your own pace. Start coding now!

A step-by-step JavaScript practice guide for beginner to advanced level.

How to Start Practicing JavaScript

When you start learning JavaScript journey with us, you will find a structured and engaging environment designed to help you master key concepts step by step. Here’s how you can get started:

  • Choose Your Category: Begin by selecting a category that matches your current focus or skill level. Whether it’s variables, control flow, loops, operators, functions, events, arrays, or strings, each category offers a set of challenges tailored to deepen your understanding and mastery.
  • Engage with Interactive Challenges: Get the hands-on coding exercises within each category. These exercises are crafted to provide practical experience and reinforce your theoretical knowledge.
  • Track Your Progress: Monitor your learning journey with real-time feedback. Each category displays your score, time taken, and completion status, allowing you to gauge your improvement and focus on areas that need more practice.
  • Flexible Learning: Practice at your own pace. Whether you prefer to tackle all exercises in one go or spread them out over sessions, our platform adapts to your schedule and learning style.
  • Access Anytime, Anywhere: Our online platform ensures accessibility wherever you are. Whether you’re at home, work, or on the go, you can continue learning and practicing JavaScript seamlessly.
  • Prepare for Real-World Applications: Each exercise is designed to simulate real-world coding scenarios. By mastering these challenges, you will build the confidence and skills needed to excel in practical JavaScript development.
  • Seek Guidance and Solutions: If you ever get stuck, our platform provides solutions to help you navigate through challenging exercises and deepen your understanding.

By following these steps, you will not only enhance your JavaScript skills but also enjoy a rewarding and structured learning experience that prepares you for success in JavaScript programming.

JavaScript Best Practice Guide

Explore JavaScript best practices with our comprehensive guide. Discover coding standards, optimization techniques, and industry-recommended approaches. Enhance your skills through practical examples, insightful tips, and interactive challenges.

Learn how to write efficient and maintainable JavaScript code that stands out in your projects.

Why Practice JavaScript Online?

Practice JavaScript effectively with structured fill-in-the-blank questions that:

  • Guide focused learning and improvement.
  • Provide instant feedback to reinforce concepts.
  • Integrate theory with practical application for comprehensive understanding.
  • Prepare you for real-world coding challenges.

JavaScript online practice Rules

Follow these guidelines for effective learning:

  • Manage your time effectively within set limits.
  • Prioritize clean, well-documented code.
  • Adhere to platform-specific instructions and submission procedures.
  • Refrain from using external resources unless permitted.
  • Use feedback to enhance your skills and actively participate in discussions for continuous improvement.

Benefits of Practice JavaScript

Master JavaScript through engaging exercises that offer:

  • Hands-on learning with interactive quizzes.
  • Progress tracking to monitor your improvement.
  • Effective skill enhancement at your own pace.
  • Immediate feedback for quick learning.
  • Access anytime, anywhere for convenient learning.
  • Practical application of JavaScript concepts.
  • Comprehensive coverage of JavaScript topics.

Features of JavaScript Exercises Portal

  • Immediate error correction and feedback.
  • Unlimited attempts to master concepts.
  • Time management tools with displayed elapsed times.
  • Comprehensive view of categories, completion status, and scores.
  • Helpful hints and solutions for guided learning.
  • Adaptive difficulty levels for personalized challenges.
  • Gamification elements such as scoring and achievements to keep learning engaging.

Explore our interactive JavaScript exercises designed for both beginners and experienced developers. Master key concepts, track your progress, and prepare for real-world coding challenges. Start practicing now to sharpen your JavaScript expertise and advance your programming journey with confidence.

JavaScript Exercises – FAQs

What are javascript exercises .

JavaScript exercises are coding challenges or problems based on fill in the blanks to help you to practice and improve your JavaScript programming skills. This exercise for beginners and experienced developer.

Where can I find JavaScript exercises?

You can find JavaScript exercises on GeeksforGeeks platform with compiled set of problems. Apart from Exercises, we offer a curated JavaScript tutorial and JavaScript course to learn easily.

What are some good beginner JavaScript exercises?

For beginners, exercises like working with variables, loops, arrays, functions, and simple DOM manipulations are great starting points.

Please Login to comment...

Similar reads.

  • Web Technologies
  • WebTech - Exercises
  • Best External Hard Drives for Mac in 2024: Top Picks for MacBook Pro, MacBook Air & More
  • How to Watch NFL Games Live Streams Free
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Uploaded avatar of ghjk

Practice 148 exercises in JavaScript

Learn and practice JavaScript by completing 148 exercises that explore different concepts and ideas.

Explore the JavaScript exercises on Exercism

Unlock more exercises as you progress. They’re great practice and fun to do!

Free Javascript challenges

Learn Javascript online by solving coding exercises.

Javascript for all levels

Solve Javascript tasks from beginner to advanced levels.

Accross various subjects

Select your topic of interest and start practicing.

Start your learning path here

Why jschallenger, a hands-on javascript experience.

JSchallenger provides a variety of JavaScript exercises, including coding tasks, coding challenges, lessons, and quizzes.

Structured learning path

JSchallenger provides a structured learning path that gradually increases in complexity. Build your skills and knowledge at your own pace.

Build a learning streak

JSchallenger saves your learning progress. This feature helps to stay motivated and makes it easy for you to pick up where you left off.

Type and execute code yourself

Type real JavaScript and see the output of your code. JSchallenger provides syntax highlighting for easy understanding.

Join 1.000s of users around the world

Most popular challenges, most failed challenges, what users say about jschallenger.

Photography of Mohamed Ibrahim who describes JSchallenger as a very helpful free resource for Javascript exercises

Mohamed Ibrahim

Photography of Tobin Shields who sais that JSchallenger is a great tool with Javascript beginner exercises

Tobin Shields

Photography of Meet Patel who describes JSchallenger as a great place to solve Javascript problems

Learn JavaScript

Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.

  • AI assistance for guided coding help
  • Projects to apply new skills
  • Quizzes to test your knowledge
  • A certificate of completion

javascript assignment for students

Skill level

Time to complete

Prerequisites

About this course

You interact with JavaScript code all the time — you just might not realize it. It powers dynamic behavior on websites (like this one) and plays an important role in many fields, like front- and back-end engineering, game and mobile development, virtual reality, and more. In this course, you’ll learn JavaScript fundamentals that will be helpful as you dive deeper into more advanced topics.

Skills you'll gain

Build core programming concepts

Learn object-oriented concepts

Read and write JavaScript

Welcome to Learn JavaScript

Learn about what the JavaScript course has in store!

Introduction

In this course, you will learn about JavaScript data types, built-in methods, and variables.

Conditionals

Learn how to use if, else if, else, switch, and ternary syntax to control the flow of a program in JavaScript.

Learn about JavaScript function syntax, passing data to functions, the return keyword, ES6 arrow functions, and concise body syntax.

Learn about global and block level scope in JavaScript.

In this course, you will learn about arrays, a data structure in JavaScript used to store lists of data.

In this course, you will learn how to use for and while loops to execute blocks of code multiple times.

Certificate of completion available with Plus or Pro

The platform

Hands-on learning

An AI-generated hint within the instructions of a Codecademy project

Projects in this course

Kelvin weather, magic eight ball.

javascript assignment for students

Earn a certificate of completion

  • Show proof Receive a certificate that demonstrates you've completed a course or path.
  • Build a collection The more courses and paths you complete, the more certificates you collect.
  • Share with your network Easily add certificates of completion to your LinkedIn profile to share your accomplishments.

javascript assignment for students

Learn JavaScript course ratings and reviews

  • 5 stars 65%
  • 4 stars 23%

Our learners work at

  • Google Logo
  • Amazon Logo
  • Microsoft Logo
  • Reddit Logo
  • Spotify Logo
  • YouTube Logo
  • Instagram Logo

Frequently asked questions about JavaScript

What is javascript.

JavaScript is one of the most popular languages in the world. It’s powerful and versatile, and with HTML and CSS, it forms the foundation of modern web development.

What does JavaScript do?

What kind of jobs can javascript get me, why is javascript so popular as a first coding language, why is javascript so popular, what do i need to know before learning javascript, are java and javascript the same, join over 50 million learners and start learn javascript today, looking for something else, related resources, javascript: all the cool kids are doing it, why learn javascript foundations, related courses and paths, learn javascript: fundamentals, learn javascript: functions and scope, create a back-end app with javascript, browse more topics.

  • Web Development 4,779,065 learners enrolled
  • Code Foundations 7,148,047 learners enrolled
  • JavaScript 2,780,437 learners enrolled
  • Computer Science 5,598,731 learners enrolled
  • Data Science 4,297,330 learners enrolled
  • Python 3,472,464 learners enrolled
  • For Business 3,166,576 learners enrolled
  • Data Analytics 2,294,232 learners enrolled
  • HTML & CSS 2,265,125 learners enrolled

Two people in conversation while learning to code with Codecademy on their laptops

Unlock additional features with a paid plan

Practice projects, assessments, certificate of completion.

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

javascript assignment for students

JavaScript Practice Exercises for All Levels

Louis herman content writer.

JavaScript is a language that can be intimidating for newcomers. But it’s actually easier than it seems.

One of the ways to get started is to do practice exercises. But there are so many online that it can be hard to choose the right ones for a beginner.

Before you go and do exercises, it’s best to learn a little about the subject. In this article, we’ll be introducing JavaScript and give you a curated list of the best JavaScript practice exercises to get started.

What is JavaScript?

JavaScript (not to be confused with  Java ) scripting programming language that appeared in 1995 and is at the core of the modern World Wide Web. While HTML takes care of the content and structure of a page and CSS of the style, JS is used on the client-side for the behavior of a page—it makes it come to life.

However, JavaScript is more complex than the first two. It lets you do things like:

Auto-update content, like a social media feed

Animate visual elements

Add visual feedback on user interactions

Add interactive maps

Trigger pop-ups/offers after user actions

It’s a high-level, interpreted language just like Python. High-level means that a lot of abstraction is made, so you don’t have to deal with memory management as you would with low-level languages like C or C++. Interpreted means that you don’t need to run it through a compiler, and the language can be directly executed by your computer’s processor.

JavaScript is also multi-paradigm so that you can write your code in a variety of ways, like  object-oriented  or  functional .

Behind JavaScript exist a convention called  ECMAScript . It is the scripting language specification it’s based on. It defines language lexicon & syntax and the  APIs  that should be made available in it.

With time, many frameworks have been developed to improve the functionalities and development of JS. The most popular ones are React (and Next.js its sub-framework), Vue (and Nuxt.js its sub-framework), and Angular.

What can it be used for?

It can be used in the front-end and run on the client-side/browser or in the back-end with node.js.

It’s your browser’s programming language, meaning it's the only language browser can execute. But JavaScript isn't only restricted to websites. With it, you can build:

Complete full-stack web apps

Mobile apps (with  React Native  or  Ionic , for example)

Desktop apps (with Electron.js),

Complete  shopping cart solutions

Why learn JavaScript?

Well, as you probably already observed, JavaScript is a powerful programming language that can be used to do a lot of things. It’s also very fast and relatively easy to learn compared to other languages.

Here are the reasons why you should learn JS:

Highly in demand

75% of companies  are looking for JavasScript web developers.

As we’ve seen earlier, JavaScript can be used to build almost anything for the modern world. Learning this language will enable you to be versatile in the different tasks you’ll have in your career.

Beginners-friendly

JavaScript is one of the easiest scripting languages out there. A lot of tools for debugging, for example, are also available to make your life as a newcomer a lot easier.

Free to learn

Since it’s one of the most popular programming languages, there are a lot of resources to get started. From books, blog tutorials, and videos, you can learn the way that suits you most.

Learning the JavaScript fundamentals

Before you dive into the JavaScript exercises, it’s best to learn the fundamentals. Here are a few resources I recommend to get started:

If you are an absolute beginner:

Learn JavaScript repository  from Snipcart

A first splash into JavaScript  from Mozilla

You SHOULD Learn Vanilla JavaScript Before JS Frameworks  from Snipcart

Eloquent JavaScript eBook  by Marijn Haverbeke

JavaScript exercises for all levels

So, now let’s get into it and explore how to get started when you have understood the basics.

Whatever your JavaScript skills are, here's are some JavaScript coding exercises you can do at your own pace.

1.  W3 School JavaScript exercises

67 exercises to practice the JavaScript basics.

2.  JavaScript - Exercises, Practice, Solution

Free exercises covering the basics to the more advanced aspect of JS like the DOM (document object modal) async function, and more.

3.  Show user IP address with JavaScript

An exercise created by our co-founder Charles. Ideal for beginners to practice the basic fetch function in the CodePen code editor.

4.  Add items to a wishlist with JavaScript

An exercise created by our co-founder Charles. Ideal for beginners. You’ll practice creating a simple wishlist with JS in the CodePen code editor.

5.  Some JavaScript Challenges

A resource with 47 exercises to practice whatever your level is, With exercises from well-known universities.

6.  Debugging Vue.js

Tutorial and exercise on how to debug your Vue.js frontend. Ideal for intermediate developers.

7.  Build a React E-Commerce Web App

JavaScript tutorial and exercise on how to create a React dynamic website.

8.  Progressive Web Application Development with Nuxt

JavaScript tutorial and exercise on how to build a PWA with a JavaScript framework. 

9.  Create a Node.js for E-Commerce

Tutorial and exercise about creating a complete eCommerce website using Snipcart, Node.js, and Koa.js as the frontend.

10.  5 Typical JavaScript Interview Exercises

5 exercises to practice for a JavaScript web developer interview.

JavaScript courses

Intro to js: drawing & animation.

This is a free course by Khan Academy. Each section is covered with an explanatory video and then you have exercises to practice what you just learned.

JavaScript Algorithms and Data Structures

Free course by freecodecamp. With 113 exercises that cover the basics of JavaScript.

Learn JavaScript

Free course by Learn JavaScript. Cover the fundamentals with exercises to practice at every step.

This is a course by Code Academy. It’s highly interactive, however, you need a subscription in order to have access to the whole course.

JavaScript courses on mobile

If you are looking for a way to learn and practice JavaScript while on the go, I suggest your look at two free apps.

Grasshopper

This is an app (mobile and web) developed by a team at Google. It’s a fun way to learn JavaScript by doing exercises. The course is divided into small sections that you can do when you have a few minutes.

Mimo is an app to learn web development. While it’s not strictly limited to JavaScript you can select to learn and practice only JavaScript. While they offer a free version, you can also subscribe to Mimo Pro to unlock more exercises.

As you may have noted, learning JavaScript is pretty accessible. Practice exercises are an important part of the learning experience. Because it’s a constantly evolving language, It’s best to keep up to date with the latest developments in the ecosystem. There are even some  JavaScript podcasts  if you want to learn on the go.

Let us know in the comments how it went if you’ve tried any of the exercises. If you enjoyed it, consider sharing it.

Louis Herman

About the author

Louis is a content writer. He is specialized in technology and marketing.

Add a Shopping Cart to a Website in 4 Simple Steps

Recent articles in web development, the 6 best javascript frameworks to use in 2022.

Diego Salinas Gardón

A Beginner's Guide to APIs: How to Integrate and Use Them

Alex Trost's avatar

5 Best Angular Tutorials for Beginners

Microservices vs. api: the benefits of using microservices, webhook vs. api: how do they compare.

Jaden Baptista's avatar

36 000+ geeks are getting our monthly newsletter: join them!

Learn JavaScript for Beginners – JS Basics Handbook

Nathan Sebhastian

The goal of this handbook is to quickly introduce you to the basics of JavaScript so you can start programming applications.

Instead of covering all the theories and concepts of JavaScript, I'll be teaching you only the most important building blocks of the language. We'll cover things like variables, data types, functions, objects, arrays, and classes. You'll also learn how to mix them all to build a small but solid program.

We're also going to leave out HTML, CSS, and using JavaScript in the browser. This tutorial focuses only on JavaScript as a programming language and uses the terminal to run the code.

This tutorial also has exercises for each section which gives you time to practice what you learned and "drill" the knowledge into your brain.

This handbook is completely free right here in this webpage. If you want the Kindle or paperback version of this tutorial , you can pay a small fee for it. It'll help support me in creating an in-depth JavaScript Tutorial that will help you build a complete web application.

Table of Contents

  • Why learn JavaScript

JavaScript vs Java

How to install vscode, how to install node.js, 3 - quick console introduction, 4 - time to say hello world, execution flow, exercise #1, variable naming, constant variable, the var keyword, exercise #2, strings in javascript, numbers (integers and floats) in javascript, booleans in javascript, undefined in javascript, null in javascript, type coercion, type coercion rules, why you should avoid type coercion, arithmetic operators, the assignment operator, the comparison operators, logical operators, the typeof operator, exercise #3, array index position, special methods for array manipulation, exercise #4, the if...else statement, the switch...case statement, the switch statement body, switch statement use cases, exercise #5, the for statement.

  • When to use the for loop?

The while statement

  • When to use the while loop?

Exercise #6

How to create your own function, function parameters and arguments, default parameters, default parameters and null, the return statement, variable scope, the rest parameter, arrow function, single and multiline arrow functions, arrow function without round brackets, arrow function doesn't have arguments binding, how to convert a normal function to an arrow function easily, exercise #7, how to access object values, how to add a new property to the object, how to modify object properties, how to delete object properties, how to check if a property exists in an object, exercise #8, final exercise: build a cash register machine, 1 - javascript introduction.

JavaScript was created around April 1995 by Brendan Eich. At the time, he was working to develop a browser for a company called Netscape. He was told that he only had 10 days to design and code a working prototype of a programming language that could run on the browser.

He needed to create a language that appealed to non-professional programmers like Microsoft Visual Basic.

The reason he was given only 10 days was that Netscape needed to release its browser, which at the time was in competition with Microsoft.

In the beginning, JavaScript was not as powerful as it is today, since it was originally designed to add interaction and animation for web pages. It wasn't until 2005 when jQuery and AJAX were released that JavaScript began to be used in every website.

People simply didn't have an easy alternative to jQuery and AJAX for DOM manipulation and sending asynchronous requests. Plus, an active community of JavaScript developers kept adding new features to the library.

Then Google launched its modern Chrome browser, and Facebook started getting more people online. JavaScript began to grow to accomodate the ambitions of these giant internet companies.

Browsers began developing APIs that you could use in JavaScript. JS could retrieve information such as IP addresses and geographic locations from the browser, adding more power to internet companies to localize the features of their websites.

Then another innovation happened to make JavaScript even more powerful.

A server-side environment named Node.js was released in 2009, allowing JavaScript to run on the server side like PHP, Java, Python, Ruby, and many more. It also enabled devs to develop full-stack web applications using only JavaScript.

Today, JavaScript is a language that can power the web, desktop, and mobile applications.

Here's a quote from Tim O'Reilly, the founder of O'Reilly Media:

Learning JavaScript used to mean you weren't a serious developer. Today, not learning JavaScript means the same thing.

Learning JavaScript is now critical for people who want to be web developers.

Why learn JavaScript?

There are 4 good reasons why you need to learn and deeply understand JavaScript:

  • JavaScript is the only language that works in the browser
  • It's fairly easy to learn (but hard to master)
  • It's an essential language for making web applications
  • There are many career opportunities for JavaScript devs

Learning JavaScript opens tremendous opportunities where you can be a frontend, backend, or mobile developer.

Basically, learning JavaScript is a gateway to career improvements in tech.

In the beginning, JavaScript was actually named LiveScript. It was renamed to JavaScript because Java was a very popular programming language.

Since most software developers were already familiar with Java, the name JavaScript was thought to help in marketing JavaScript as a great programming language and draw the interest of developers at the time.

Just to be clear, JavaScript and Java are two completely different programming languages. You don't need to know Java to learn JavaScript (or the other way around). :)

2 - How to Set Up Your Computer

To write a program using JavaScript, you need to install 2 free tools that are available for all operating systems.

The first tool to install is Visual Studio Code.

Visual Studio Code or VSCode for short is a text editor program created for the purpose of writing code. Aside from being free, VSCode is open source and available on all major operating systems.

You can use VSCode on Windows, macOS, and Linux, so if you don't have a text editor on your computer, I recommend that you install VSCode here.

Now that you have a text editor to write JavaScript code, you need a software to run JavaScript code. Let's install Node.js next.

To run JavaScript outside of the browser, you need to install Node.js, which is essentially a JavaScript runner.

Simply go to the Node.js website at nodejs.org and download the latest LTS version for your computer. Once the download is complete, install it on your system.

You need to run Node.js using the console, so open your command line or terminal application and run the following command:

This command will output the version of your freshly installed Node.js into the console.

The console is a text-based interface that you can use to type and run commands on your computer. On Windows, it's called the Command Line. On macOS and Linux it's known as the Terminal.

You're not going to use all the commands available within the console. In fact, you only need to know 7 basic commands to help you run JavaScript code.

First, open the console program on your computer and type the pwd command:

This is the command you use to find out which directory your terminal is currently on. pwd is short for print working directory.

To change the working directory, you need to run the cd command.

Here's an example to move into a child directory:

To move up to a parent directory, you specify .. next to the command:

To go up more than one directory, use ../..

To clear your console from previous commands and output, use the clear command:

To print out the list of files and directories in the current directory, run the ls command:

To create a new file, use the touch command followed by the file name and extension:

The command above will create a new JavaScript file named index.js on the current working directory.

To create a new directory, use the mkdir command followed by the directory name:

To run JavaScript using Node.js, specify node followed by the file name as follows:

You'll see any output from the code in the same console.

There are lots of things you can do with the console, but these 7 commands would be enough because we only need it to run JavaScript code.

Next, let's run your first JavaScript program!

It's time to run your first JavaScript program using Node.

From the console, create a new JavaScript file named index.js using the touch command.

Next, open the file using VSCode and write the following line of code into the file:

Back on the console, run this script with Node:

The console should execute the index.js file and print "Hello World!".

You've just run your very first JavaScript program using Node.js. Excellent!

When you run the node index.js command, the Node.js program starts reading the script line by line from top to bottom.

The node program sees that you wrote the word console.log followed by parentheses () , so it knows that you're instructing it to print something. The program then reads what you put in the parentheses and prints it out on the console.

In your VSCode or other text editor program, you should see different parts of your code highlighted with different colors. This is a feature of the text editor called syntax highlighting , and it's really useful to help you distinguish different parts of the code.

The log keyword is a function, so it gets highlighted in one color, while the words in the parentheses have another color.

A function is simply a piece of code that's used to perform a certain task. The log() function is used to "print" whatever you put inside the parentheses.

On the other hand, the console keyword is an object, which is a standalone property that gives access to certain functionalities.

We'll learn more about functions and objects later. For now, just remember that the console.log() keyword is used to print things to the console.

Next, let's start with learning JavaScript code structure.

5 - JavaScript Code Structure

A computer program is a series of pieces of code written in a text file. These text files are then run through a software that's designed specially for running the code. The Node.js software you downloaded previously is the tool that processes JavaScript code.

Before we go further, let's understand the structure of code.

A statement is a single instruction for the computer to run. Think of it like a sentence, but for computers. We can end a statement by using a semicolon ; just like we can end a sentence using a dot .

You can write multiple statements in a single line, but the convention is to write one statement per line:

Each statement is an expression of some action that needs to be carried out by the software that executes the code.

In programming, comments are text we use to communicate the context of the code written in the file.

To write a comment in JavaScript, you need to add two forward slashes // before the comment as shown below:

Comments are ignored by the language processor, so you can use comments to disable some code without having to delete that code.

The code below shows how to disable the second print statement:

A language processor such as Node.js executes statements in a top-down approach. The statement written in the first line will be executed before the second line, then continue down to the last line:

If you want to print the numbers before the text, then you need to move the corresponding console.log() lines to the top.

Try to print your name, age, and occupation on the console.

The output would look as follows:

Now that you understand the basic code structure of JavaScript, let's continue with learning variables next.

6 - JavaScript Variables

Before explaining what a variable is, I want you to change the code you've written in the index.js file.

Change the code in that file as follows:

Next, run the code using the node index.js command. You'll see the same output as when you write the 'Hello World!' message directly inside the console.log() function. How can this be?

This is because the message written in the code above is a variable .

In programming, a variable is simply a name that you give to a value so that you can access that value later. You can think of a variable as a label that can be tagged to a certain value, so you can refer to the value using the label.

To declare a variable, you need to type the keyword let followed by the variable name.

The first line in the code tells JavaScript to associate the message variable with the value Hello World! :

In the second line, JavaScript is instructed to print the value of message , and that's exactly what it does.

You can change the value of your variable by re-assigning another value as follows:

Run the file and you'll see two lines printed as the output:

Variables are used to reference data so that you can use the same data multiple times in your program.

Next, let's see some rules for naming variables in JavaScript.

JavaScript has a few naming rules that you need to know to avoid naming errors.

Variable names can only contain alphabet letters, numbers, and underscores ( _ ). This means you can name your variable message , message_1 , message_2 .

The first character of the variable name must not be a number. message_1 is okay. 1_message is not.

You can't use reserved keywords such as console because they are used by JavaScript to do certain things. There are many other keywords used by JavaScript that you'll learn in the following sections such as if , for , and while .

Variable names are case-sensitive, which means Message , MESSAGE , and message can be used to create three different variables. But of course, I don't recommend using similar names as it causes confusion.

Sometimes, you need more than one word to declare a variable name. JavaScript has two naming conventions that are used worldwide:

Camel case is a naming convention that uses an uppercase letter for the first character for subsequent words. Here's an example:

The snake case naming convention uses an underscore to separate words. Here's an example:

Both are acceptable naming conventions, but you should stick to one of them in your code to avoid confusion.

There are times when you need to store a value that never changes in a variable.

A constant variable is a variable that doesn't change its value as long as the program is running. In other programming languages, changing the value of a constant will produce an error.

In JavaScript, a constant variable is declared using the const keyword.

The following shows how to declare 2 constants in JavaScript:

The naming convention for a constant is to use all uppercase letters, although using lowercase letters also works. The uppercase is just a standard to make constants stand out more.

The var keyword is used to declare variables with a global scope. This keyword was the only keyword you can use to declare variables before JavaScript released the new let and const keyword in 2015.

As of today, you should avoid using var if you can, since var can introduce bugs that you can avoid by using the let keyword.

To show you what I mean, consider the following example:

The code above will print the name variable just fine, but it really should not because the variable name is declared inside the if block.

This is because any variable declared using the var keyword is accessible from everywhere. The scope of that variable is global.

On the other hand, the let keyword has a block scope, which means the variable is only accessible from the block and all its child blocks.

But why bother with scoping the variable? This is because when you have hundreds or thousands of code lines, it can become frustrating to trace an error that occurs because of global variables.

There's a principle in software development called "principles of least exposure", which means you don't expose any part of your program that's unnecessary.

Block scoping a variable ensures that a variable is exposed and accessible only in parts of your codebase that require the variable.

A variable declared using the let keyword is identical to a variable declared using var except for the scope level.

This also means that you now have var , let , and const keywords to declare a variable. Which one to use?

In general, you can declare a variable with const first. When you code your application and realize that you need to change the variable assignment, you can change the declaration to let .

If you know from the start that the variable's value will change, then you can use let immediately. Just don't use var today or people might get mad at you.

Write a program with three variables, each with the following value:

  • The first variable contains your name
  • The second variable contains your age
  • The third variable contains your occupation

Then print the variables using the console.log() method. Here's the example output:

How you use variables to make a program that does what you want it to do is one of the most important skills you can have as a programmer.

But before you learn more about how to make use of variables, let's learn about data types in JavaScript.

7 - JavaScript Basic Data Types

Data Types are simply definitions for different types of data known to a programming language.

A data type contains specifications about what you can and can't do with that data.

To show you a brain-friendly example, I'm sure you agree that 2 + 2 = 4 ?

Well, JavaScript also agrees with that:

But what if you try to add a number with letters as shown below?

Adding a number and letters together will cause JavaScript to concatenate or join the values together.

In this section, you're going to learn basic data types that JavaScript knows:

You will also see how these different types react to operators such as + shown in the above example.

First, let's start with strings.

Strings are simply data defined as a series of characters.

You've seen an example of string data previously when you call the console.log() function to print a message:

A string needs to be enclosed in quotations. You can use double quotes or single quotes, but they have to match.

You'll get an error when you use different quotation marks like this:

You can join two or more strings as one with the plus + symbol. Don't forget to add a space before the next string or you'll get a string without spaces!

When printing a variable's value, you can also add strings in the console.log() function directly as follows:

This is particularly useful when you have multiple strings to console.log in one sentence as follows:

Or you can also use the template strings format, which allows you to embed a variable directly inside the string as follows:

To use the template strings format, you need to use the backtick (`) character to wrap the string instead of quotations.

The variable is embedded in the string using the dollar symbol and curly brackets as in ${variable} .

This way, JavaScript knows that you're referencing a variable inside the string.

When you have multiple strings to print in a single line, then the template strings format is more convenient because you didn't have to break the string with quotations and concatenations.

Next, strings can also represent numbers. You surround the numbers in quotations as follows:

When you join two string numbers with a + symbol, JavaScript will join the two numbers instead of performing arithmetic addition.

This is how strings work in JavaScript. Let's look at numbers next.

Number data types represent different kinds of numbers. There are two types of numbers in JavaScript:

An integer is a whole number without decimals and fractions. Below, you see examples of two integers x and y :

On the other hand, floats refer to numbers with decimal points like this:

To create a float, you need to write a number and use . to define the decimal values.

With number types, you can perform arithmetic operations such as addition + , subtraction - , division / , and multiplication * just like how you use a calculator.

Boolean is a type that represents true and false values.

You can think of Booleans as a light switch that can only be in one of two positions: on or off.

So it is with Boolean values in programming languages. They are used when JavaScript needs to make a decision: Go left or go right? Right or wrong?

Here's how you create Boolean values in JavaScript:

This data type is frequently used when you need to make a decision using a control flow. You'll see why Boolean values are very useful in developing a program later in Section 9.

Undefined is a data type in JavaScript used to represent a variable that hasn't been assigned any value yet.

Anytime you declared a variable without assigning any value, the undefined value will be assigned to that variable. For example:

You can also assign undefined to a variable explicitly as follows:

But this is usually not recommended, because JavaScript has another value called null which is used to mark a variable as empty.

The null value is a special data type that represents an empty or unknown value. Here's how you assign a variable as null:

The code above means that the value of first_name is empty or unknown.

At this point, you may be thinking what's the difference between undefined and null ? They seem to serve a similar purpose.

And you are correct. Both undefined and null are values that represent nothing, and other programming languages usually only have one, and that is null .

In JavaScript, the undefined value is reserved as the default value when a variable is declared, while null means you intentionally assign an "empty" value for the variable.

This slight difference will come to play later when you learn about functions in Chapter 13.

For now, just keep in mind that JavaScript treats undefined as the "default" empty value and null as the "intentional" empty value.

8 - Type Conversion and Coercion

At times, you might want to convert one data type into another so that the program runs as expected.

For example, suppose you need to convert a string into an integer so you can perform an addition between numbers.

If you have one of the numbers as a string, JavaScript joins them together instead of adding:

To add the two numbers properly, you need to convert the x variable into an integer.

Changing the data from one type to another is also known as type conversion or type casting. There are 3 functions frequently used to do type conversion:

As their name implies, these type conversion functions will attempt to convert any value you specified inside the parentheses to the type of the same name.

To convert a string into an integer, you can use the int() function:

On the other hand, the String() function converts a value of another type to a string. If you type String(true) , then you'll get 'true' back.

Passing a value of the same type as the function has no effect. It will just return the same value back.

In JavaScript, type coercion is a process where a value of one type is implicitly converted into another type.

This is automatically done by JavaScript so that your code won't cause an error. But as you'll see in this section, type coercion can actually cause undesired behavior in the program.

Let's consider what happens when you perform an addition between a number and a string in JavaScript:

As you've seen in the previous section, JavaScript will consider the number as a string and join the two letters as 11 instead of adding them ( 1 + 1 = 2 )

But you need to know that other programming languages don't respond the same way.

Programming languages like Ruby or Python will respond by stopping your program and giving an error as feedback. It will respond with something along the lines of "Cannot perform addition between a number and a string".

But JavaScript will see this and said: "I cannot do the operation you requested as it is , but I can do it if the number 1 is converted to a string , so I'll do just that ."

And that's exactly what type coercion is. JavaScript notices that it doesn't know how to execute your code, but it doesn't stop the program and respond with an error.

Instead, it will change the data type of one of the values without telling you.

While type coercion doesn't cause any errors, the output is actually something you don't want either.

Type coercion rules are never stated clearly anywhere, but I did find some rules by trying various silly code myself.

It seems that JavaScript will first convert data types to string when it finds different data types:

But the order of the values matters when you have an object. Writing objects first always returns numeric 1 :

JavaScript can calculate between boolean and numeric types, because boolean values true and false implicitly has the numeric value of 1 and 0 :

Type coercion is always performed implicitly . When you assign the value as a variable, the variable type will never change outside of the operation:

You can try to find some more on your own, but you hopefully understand what type coercion is and how it works by now.

JavaScript developers are generally divided into two camps when talking about type coercion:

  • Those who think it's a feature
  • Those who think it's a bug

If you ask me, I would recommend that you avoid using type coercion in your code all the time.

The reason is that I've never found a problem where type coercion is required for the solution, and when I need to convert one type into another, it's always better to do so explicitly:

Using explicit type conversion functions such as Number() and String() will make your code clear and transparent. You don't need to guess the correct data type required in your program.

Type coercion is one of the unique features in JavaScript that may confuse beginners, so it's good to clear it up early.

Next, we'll learn about JavaScript operators.

9 - Operators in JavaScript

As the name implies, operators are symbols you can use to perform operations on your data.

You've seen some examples of using the plus + operator to join multiple strings and add two numbers together. Of course, JavaScript has more than one operator as you'll discover in this section.

Since you've learned about data types and conversion previously, learning operators should be relatively easy.

The arithmetic operators are used to perform mathematical operations like additions and subtractions.

These operators are frequently used with number data types. Here's an example:

In total, there are 8 arithmetic operators in JavaScript:

NameOperation exampleMeaning
Addition Returns the sum between the two operands
Subtraction Returns the difference between the two operands
Multiplication Returns the multiplication between the two operands
Exponentiation Returns the value of the left operand raised to the power of the right operand
Division Returns the value of the left operand divided by the right operand
Remainder Returns the remainder of the left operand after being divided by the right operand
Increment Returns the operand plus one
Decrement Returns the operand minus one

These operators are pretty straightforward, so you can try them on your own.

As you've seen in the previous section, the + operator can also be used on strings data to merge multiple strings as one:

When you add a number and a string, JavaScript will perform a type coercion and treats the number value as a string value:

Using any other arithmetic operator with strings will cause JavaScript to return a NaN value.

The next operator to learn is the assignment operator, which is represented by the equals = sign.

In JavaScript, the assignment operator is used to assign data or a value to a variable.

You've seen some examples of using the assignment operator before, so here's a reminder:

You may've noticed that the equals sign has a slightly different meaning in programming than in math, and you're correct!

The assignment operator isn't used to compare if a number equals another number in programming.

If you want to do that kind of comparison, then you need to use the equal to == operator.

Assignment operators can also be combined with arithmetic operators, so that you can add or subtract values from the left operand.

See the table below for the types of assignment operators:

NameOperation exampleMeaning
Assignment
Addition assignment
Subtraction assignment
Multiplication assignment
Division assignment
Remainder assignment

Next, let's look at comparison operators.

Comparison operators are used to compare two values. The operators in this category will return Boolean values: either true or false .

The following table shows all comparison operators available in JavaScript:

NameOperation exampleMeaning
Equal Returns if the operands are equal
Not equal Returns if the operands are not equal
Strict equal Returns if the operands are equal and have the same type
Strict not equal Returns if the operands are not equal, or have different types
Greater than Returns if the left operand is greater than the right operand
Greater than or equal Returns if the left operand is greater than or equal to the right operand
Less than Returns if the left operand is less than the right operand
Less than or equal Returns if the left operand is less than or equal to the right operand

Here are some examples of using these operators:

The comparison operators can also be used to compare strings like this:

String comparisons are case-sensitive, as shown in the example above.

JavaScript also has two versions of each comparison operator: loose and strict.

In strict mode, JavaScript will compare the types without performing a type coercion.

You need to add one more equal = symbol to the operator as follows

You should use the strict comparison operators unless you have a specific reason not to.

The logical operators are used to check whether one or more expressions result in either True or False .

There are three logical operators that JavaScript has:

NameOperation exampleMeaning
Logical AND Returns if all operands are , else returns
Logical OR`xy`Returns if one of the operands is , else returns
Logical NOT Reverse the result: returns if and vice versa

These operators can only return Boolean values. For example, you can determine whether '7 is greater than 2' and '5 is greater than 4':

These logical operators follow the laws of mathematical logic:

  • && AND operator - if any expression returns false , the result is false
  • || OR operator - if any expression returns true , the result is true
  • ! NOT operator - negates the expression, returning the opposite.

Let's have a little exercise. Try to run these statements on your computer. Can you guess the results?

These logical operators will come in handy when you need to assert that a specific requirement is fulfilled in your code.

JavaScript allows you to check the data type by using the typeof operator. To use the operator, you need to call it before specifying the data:

The typeof operator returns the type of the data as a string. The 'number' type represents both integer and float types, the string and boolean represent their respective types.

Guess the result of these operators in action:

10 - JavaScript Arrays

An array is an object data type that can be used to hold more than one value. An array can be a list of strings, numbers, booleans, objects, or a mix of them all.

To create an array, you need to use the square brackets [] and separate the items using a comma.

Here's how to create a list of strings:

You can think of an array as a list of items, each stored in a locker compartment:

Array as a locker illustration

You can also declare an empty array without any value:

An array can also have a mix of values like this:

The array above contains a string, a boolean, an integer, and a float.

JavaScript remembers the position of the elements within an array. The position of an element is also called an index number.

Going back to the locker example, you can think of index numbers as the locker numbers. The index number starts from 0 as follows:

Array index numbers as locker numbers

To access or change the value of an array, you need to add the square brackets notation [x] next to the array name, where x is the index number of that element. Here's an example:

Suppose you want to print the string 'Owl' from the birds array. Here's how you can do it.

There you go. You need to type the name of the array, followed by the index number wrapped in square brackets.

You can also assign a new value to a specific index using the assignment operator.

Let's replace 'Parrot' with 'Vulture':

Because the array index starts from zero, the value 'Parrot' is stored at index 2 and not 3.

Since array is an object, you can call methods that are provided by JavaScript to manipulate the array values.

For example, you can use the push() method to add an item to the end of the array:

Another method called pop() can be used to remove an item from the end of an array:

The unshift() method can be used to add an item from the front at index 0:

On the other hand, the shift() method can be used to remove an item from index 0:

The indexOf() method can be used to find and return the index of an item in the array.

The method will return -1 when the item isn't found inside the array:

To get the size of an array, you can access the length property:

Note that we don't add parentheses next to the length keyword above. This is because length is a property of the array object and not a method.

We'll learn more about objects in the coming tutorials.

Create an array named colors that include the 'red', 'green, and 'blue' colors.

First, add a 'black' color after the last index of the array. Then print the array.

Next, remove the value 'red' and swap the position of 'green' and 'blue'. Print the array.

Finally, add the color 'yellow' on the first index of the array, then print the array.

The result output is as follows:

You need to modify the original array using the methods explained in this section.

11 - Control Flows (Conditionals) in JavaScript

Up until now, the JavaScript code you've written is executed line by line from top to bottom. But what if you want to run some lines of code only when a certain condition is met?

A computer program usually needs to take into account many different conditions that can arise during the program's execution.

This is similar to how a human makes decisions in their life. For example, do you have money to cover the vacation to Japan? If yes, go. If not, then save more money!

This is where control flow comes in. Control flow is a feature in a programming language that allows you to selectively run specific code based on the different conditions that may arise.

Using control flows allows you to define multiple paths a program can take based on the conditions present in your program.

There are two types of control flows commonly used in JavaScript: conditionals and loops.

This section will focus on the conditional statements such as:

  • if...else statement
  • switch...case statement

You'll learn about loop statements in the next section.

The if statement allows you to create a program that runs only if a specific condition is met.

The syntax for the if statement is as follows:

Let's see an example. Suppose you want to go on a vacation that requires 5000 dollars.

Using the if statement, here's how you check if you have enough balance:

Run the code above once, and you'll see the string printed on the terminal.

Now change the value of balance to 3000 and you'll get no response.

This happens because the code inside the if statement is only executed when the condition is true .

After the if statement, you can write another line of code below it as follows:

The second console.log() call above will be executed no matter what value you assign to the balance variable.

If you want it to execute only when the if condition is met, then put the line inside the curly brackets as well:

Next, suppose you need to run some code only when the if statement condition is not fulfilled.

This is where the else statement comes in. The else statement is used to run code only when the if statement is not fulfilled.

Here's an example:

Now change the value of balance to be less than 5000 , and you'll trigger the else block in the example.

JavaScript also has the else if statement which allows you to write another condition to check should the if statement condition isn't met.

Consider the example below:

When the balance amount is less than 5000 , the else if statement will check if the balance is more than 3000 . If it does, then the program will proceed to recommend you do a staycation.

You can write as many else if statements as you need, and each one will be executed only if the previous statement isn't met.

Together, the if..else..else if statements allow you to execute different blocks of code depending on the condition the program faced.

The switch statement is a part of core JavaScript syntax that allows you to control the execution flow of your code.

It's often thought of as an alternative to the if..else statement that gives you more readable code, especially when you have many different conditions to assess.

Here's an example of a working switch statement. I will explain the code below:

First, you need to pass an expression to be evaluated by the switch statement into the parentheses. In the example, the age variable is passed as an argument for evaluation.

Then, you need to write the case values that the switch statement will try to match with your expression. The case value is immediately followed by a colon ( : ) to mark the start of the case block:

Keep in mind the data type of the case value that you want to match with the expression. If you want to match a string , then you need to put a string . switch statements won't perform type coercion when you have a number as the argument but put a string for the case:

The number expression doesn't match the string case value, so JavaScript won't log anything to the console.

The same also happens for boolean values. The number 1 won't be coerced as true and the number 0 won't be coerced as false :

The switch statement body is composed of three keywords:

  • case keyword for starting a case block
  • break keyword for stopping the switch statement from running the next case
  • default keyword for running a piece of code when no matching case is found.

When your expression finds a matching case , JavaScript will execute the code following the case statement until it finds the break keyword. If you omit the break keyword, then the code execution will continue to the next block.

Take a look at the following example:

When you execute the code above, JavaScript will print the following log:

This is because without the break keyword, switch will continue to evaluate the expression against the remaining cases even when a matching case is already found.

Your switch evaluation may match more than one case, so the break keyword is commonly used to exit the process once a match is found.

Finally, you can also put expressions as case values:

But you need to keep in mind that the value for a case block must exactly match the switch argument.

One of the most common mistakes when using the switch statement is that people think case value gets evaluated as true or false .

The following case blocks won't work in switch statements:

You need to remember the differences between the if and case evaluations:

  • if block will be executed when the test condition evaluates to true
  • case block will be executed when the test condition exactly matches the given switch argument

The rule of thumb when you consider between if and switch is this:

You only use switch when the code is cumbersome to write using if

For example, let's say you want to write a weekday name based on the weekday number

Here's how you can write it:

I don't know about you, but the code above sure looks cumbersome to me! Although there's nothing wrong with the code above, you can make it prettier with switch :

When you have lots of condition to evaluate for the same block, you'd probably combine multiple if conditions using the logical operator AND ( && ) or OR( || ) :

You can replace the code above using the switch statement. The key is you need to stack multiple cases as one just like this:

Unfortunately, switch can't replace multiple if conditions that use the && operator because of the way the case evaluation works. You need to use the if statement for that.

A primary school is giving different rewards based on the student's grade:

  • Students that got an A will get a Chocolate
  • Students that got a B will get a Cookie
  • Students that got a C will get a Candy
  • For any other value, print "No reward to give."

Create a variable named grade that will store the student's grade.

Example output:

You can use either the if...else or the switch...case statement.

12 - Control Flows (Loops) in JavaScript

As you program an application in JavaScript, you'll often need to write a piece of code that needs to be executed repeatedly.

Let's say you want to write a program that prints the numbers 1 to 10 in the console. You can do it by calling console.log 10 times like this:

This works, but there's a better way to write this kind of repetitive task.

A Loop statement is another category of control flow statement used to execute a block of code multiple times until a certain condition is met.

There are two loop statements used in JavaScript:

Let's learn how to use these statements in practice.

Instead of repeating yourself 10 times to print the numbers 1 to 10, you can use the for statement and write just a single line of code as follows:

There you go! The for statement is followed by parentheses ( () ) which contain 3 expressions:

  • The initialization expression, where you declare a variable to be used as the source of the loop condition. Represented as x = 1 in the example.
  • The condition expression, where the variable in initialization will be evaluated for a specific condition. Represented as x < 11 in the example.
  • The arithmetic expression, where the variable value is either incremented or decremented by the end of each loop.

These expressions are separated by a semicolon ( ; )

After the expressions, the curly brackets ( {} ) will be used to create a code block that will be executed by JavaScript as long as the condition expression returns true .

You can identify which expression is which by paying attention to the semicolon ( ; ) which ends the statement.

The arithmetic expression can be an increment ( ++ ) or a decrement ( -- ) expression. It is run once each time the execution of the code inside the curly brackets end:

Or you can also use shorthand arithmetic operators like += and -= as shown below:

Here, the x will be incremented by 3 each time the loop is executed.

Once the loop is over, JavaScript will continue to execute any code you write below the for body:

When to use a for loop

The for loop is useful when you know how many times you need to execute a repetitive task.

For example, let's say you're writing a program to flip a coin. You need to find how many times the coin lands on heads when tossed 10 times. You can do it by using the Math.random method:

  • When the number is lower than 0.5 you need to increment the tails counter
  • When the number is 0.5 and up you must increment the heads counter

The example above shows where the for loop offers the most effective approach.

Now let's see an alternative exercise about coin flips where the for loop is not effective:

Find out how many times you need to flip a coin until it lands on heads.

This time, you don't know how many times you need to flip the coin. This is where you need to use the while loop statement, which you're going to learn next.

The while statement or while loop is used to run a block of code as long as the condition evaluates to true .

You can define the condition and the statement for the loop as follows:

Just like the for loop, the while loop is used to execute a piece of code over and over again until it reaches the desired condition.

In the example below, we will keep executing the statement block until the condition expression returns false :

Here, the while loop will repeatedly print the value of i as long as i is less than 6 . In each iteration, the value of i is incremented by 1 until it reaches 6 and the loop terminates.

Keep in mind that you need to include a piece of code that eventually turns the evaluating condition to false or the while loop will be executed forever. The example below will cause an infinite loop:

Because the value of i never changes, the while loop will go on forever!

When to use a while loop

Seeing that both while and for can be used for executing a piece of code repeatedly, when should you use a while loop instead of for ?

An easy way to know when you should use while is when you don't know how many times you need to execute the code.

Back to the coin toss example, there's one case that's perfect for a while loop:

You also need to show how many times you flip the coin until it lands on heads:

Here, the condition isHead = Math.random() < 0.5 simulates the flipping of a fair coin. When the result is true , it means the coin landed on heads and the loop will exit.

Because you can't know how many times you need to loop until you get heads, you need to use a while loop instead of a for loop.

Write a program that prints a half pyramid using asterisks * as shown below:

Next, print a reverse half pyramid as follows:

13 - Functions in JavaScript

A function is simply a section (or a block) of code that's written to perform a specific task.

For example, the type casting function String() is used to convert data of another type to a string.

The console.log() and various array methods we've learned in previous chapters are also functions. But because these functions are called from an object, they are called methods.

You'll learn more about methods later in Chapter 14. For now, just know that a function and a method are essentially the same, except that a method is called from an object.

Besides the built-in functions provided by JavaScript, you can also create your own function.

Creating a function starts with typing the function keyword followed by the function name, a pair of round brackets, and then a pair of curly brackets.

To call a function, you need to specify the function name followed by parentheses:

The code inside the function is executed when you call that function.

Parameters are variables used to accept inputs given when the function is called.

You can specify parameters in the function header, inside the parentheses.

The following example shows a function that has one parameter called name :

How you use that name parameter inside the function is up to you.

You can use the parameter inside the print() function as follows:

Now whenever you need to call the greet() function, you need to pass an input to fill for the name parameter.

The input you passed to fill a parameter is called an argument, and here's how to do it:

The 'Peter' string inside the parentheses when calling the greet() function will be passed as the name parameter.

Run the code to receive this output:

You can have more than one parameter when defining the function, but you need to split each parameter with a comma as follows:

When you specify two parameters in the function header, you need to pass two arguments. If you call the function without passing the arguments then the value will be undefined .

In the next section, you'll learn how to create parameters with default values, which allows you to call the function without having to pass an argument to it.

But for now, I hope you see the convenience of having parameters. They make your functions more adaptable and reusable by taking different input values to cover a variety of scenarios the function might have.

As shown in the example, the name and weather parameters allow you to greet many different people in different weathers.

Whether sunny, rainy, or cloudy, just change the name and weather arguments when you want to greet another person.

When defining a function, you can set a default value for any parameter in that function.

For example, the name parameter in the function below is a default parameter:

Here, the default value 'Nathan' will be used when no value or undefined is passed for the name parameter.

You can test this by calling the greet() function without an argument as follows:

Any function you define can have a mix of default and non-default parameters.

Here's another example of a function that has one default parameter called name and one non-default parameter called weather :

Notice that the weather parameter was placed in front of the name parameter. This is for convenience so that you don't need to specify the default parameter.

If you place the non-default parameter after the default parameter, then you need to pass a value to the name parameter to get to the weather parameter.

To pass an argument to the weather parameter, we need to pass undefined or any value for the name parameter first.

This is why it's better to specify non-default parameters in front of default parameters.

Back in Chapter 7, recall that we briefly explored the difference between undefined as the "default" empty value and null as the "intentional" empty value.

When you pass undefined to a function that has a default parameter, the default parameter will be used:

As you can see, JavaScript prints the default parameter value John when you pass undefined to the function.

But when you pass null to the function, the default parameter will be ignored:

This is one of the common mistakes that beginners make when learning JavaScript. When you use the value null , JavaScript will think you want that value to be empty, so it doesn't replace the value with the default parameter.

When you use undefined , then JavaScript will replace it with the default parameter. You might encounter this issue as you work with JavaScript code in your career, so just keep this in mind.

A function can also have a return statement inside the code block. A return statement is used to return a value back to the caller.

For example, the following function returns the sum of two values:

The value returned by a function can be assigned to a variable for further operation. You can add the return statement anywhere inside the function.

When JavaScript reaches the return statement, it skips further code written inside the function block and goes back to where you call the function.

The following function has two return statements:

When we call the checkAge() function the first time, the value of age argument is greater than 18, so JavaScript executes the return statement inside the if block.

The second time we called the function, the if condition isn't met, so JavaScript executes the return statement under the if block instead.

You can also stop a function execution and return to the caller by specifying the return statement without any value:

Here, the return statement is called between the console.log() calls.

JavaScript executes the first console.log() call, then skips the rest of the code. The 'Good bye!' string isn't printed.

Now that you're learning about functions, it's a good time to talk about variable scope.

A variable declared inside a function can only be accessed from that function. This is because that variable has a local scope.

On the other hand, a variable declared outside of any block is known as a global variable because of its global scope.

These two scopes are important because when you try to access a local variable outside of its scope, you'll get an error. For example:

When you run the code above, JavaScript responds with an error:

This is because the myString variable is declared inside the greet() function, so you can't access that variable outside of it. It doesn't matter even if you called that function before accessing the variable.

Meanwhile, a global variable can be accessed from anywhere, even inside a function:

Here, the greet() function is able to access the myString variable declared outside of it.

Keep in mind that this applies only to variables declared using let and const .

Next, you can also define a local variable with the same name as the global variable without overwriting it.

When you call the greet() function, a local variable called myString was assigned the string 'Morning!'.

Outside of the function, the global variable that's also called myString still exists, and the value isn't changed.

JavaScript considers the local scope variable to be a different variable. When you declare the same variable inside a function, any code inside the function will always refer to the local variable.

In practice, you rarely need to declare the same variable in different scopes:

  • Any variable declared outside a function shouldn't be used inside a function without passing them as parameters.
  • A variable declared inside a function should never be referred to outside of that function

Keep this in mind when you write JavaScript functions.

The rest parameter is a parameter that can accept any number of data as its arguments. The arguments will be stored as an array.

You can define a rest parameter in the function header by adding triple dots ... before the parameter name.

Here's an example of creating a function that has a variable length argument:

When calling the printArguments() function above, you can specify as many arguments as you want:

Keep in mind that a function can only have one rest parameter, and the rest parameter must be the last parameter in the function.

You can use a rest parameter when your function needs to work with an indefinite number of arguments.

The JavaScript arrow function syntax allows you to write a JavaScript function with a shorter, more concise syntax.

When you need to create a function in JavaScript, the primary method is to use the function keyword followed by the function name as shown below:

The arrow function syntax allows you to create a function expression that produces the same result as the code above.

Here's the greetings() function using the arrow syntax:

When you create a function using the arrow function syntax, you need to assign the expression to a variable so that the function has a name.

Basically, the arrow function syntax looks as follows:

In the code above,

  • fun is the variable that holds the function. You can call the function as fun() later in your code.
  • (param1, param2, ...) are the function parameters. You can define as many parameters as required by the function.
  • Then you have the arrow => to indicate the beginning of the function.

The code above is equal to the following:

The arrow function syntax doesn't add any new ability to the JavaScript language.

Instead, it offers improvements to the way you write a function in JavaScript.

At first, it may seem weird as you are used to the function keyword.

But as you start using the arrow syntax, you will see that it's very convenient and easier to write.

The arrow function provides you a way to write a single line function where the left side of the arrow => is returned to the right side.

When you use the function keyword, you need to use the curly brackets {} and the return keyword as follows:

Using the arrow function, you can omit both the curly brackets and the return keyword, creating a single line function as shown below:

Without the curly brackets, JavaScript will evaluate the expression on the right side of the arrow syntax and return it to the caller.

The arrow function syntax also works for a function that doesn't return a value as shown below:

When using the arrow function syntax, the curly brackets are required only when you have a multiline function body:

The round brackets () are used in JavaScript functions to indicate the parameters that the function can receive.

When you use the function keyword, the round brackets are always required:

On the other hand, the arrow function allows you to omit the round brackets when you have exactly one parameter for the function:

The following code example is a valid arrow function expression:

As you can see, you can remove the round and curly brackets as well as the return keyword.

But you still need the round brackets for two conditions:

  • When the function has no parameter
  • When the function has more than one parameter

When you have no parameter, then you need round brackets before the arrow as shown below:

The same applies when you have more than one parameter.

The function below has two parameters: name and age .

The arrow syntax makes the round brackets optional when you have a single parameter function.

When using the function keyword to define a function, you can access the arguments you pass to the function using the arguments keyword like this:

The arguments keyword in the code above refers to the object that stores all the arguments you passed into the function.

By contrast, the arrow function doesn't have the arguments object and will throw an error when you try to access it:

You can use the JavaScript spread syntax to imitate the arguments binding as follows:

By using the spread syntax, the arguments you passed to the arrow function will be stored in an array.

Note that you need the round brackets even though you are passing just one argument to the function.

You can access the given arguments with the array index notation as arguments[0] , arguments[1] , and so on.

You can follow the three easy steps below to convert a normal function to an arrow function:

  • Replace the function keyword with the variable keyword let or const
  • Add = symbol after the function name and before the round brackets
  • Add => symbol after the round brackets

The code below will help you to visualize the steps:

The three steps above are enough to convert any old JavaScript function syntax to the new arrow function syntax.

When you have a single line function, there's a fourth optional step to remove the curly brackets and the return keyword as follows:

When you have exactly one parameter, you can also remove the round brackets:

But the last two steps are optional. Only the first three steps are required to convert any JavaScript function and use the arrow function syntax.

Write a function named calculateSquare() that's used to calculate the area and perimeter of a square shape.

The function accepts one parameter: the side of the square.

The formula to calculate the area is side * side , and the formula to calculate the perimeter is 4 * side .

The output shows the size of the size, the area, and the perimeter as follows:

14 - Objects in JavaScript

An object is a special data type that allows you to store more than one value, just like an array.

The difference between an object and an array is that an array stores data as a list of items, while an object stores data in a key:value pair format.

Let's see an example illustrating this difference. Suppose you want to store information about a book in your program.

When you use regular variables, it would look like this:

While it works fine, it certainly isn't the best way to store related values.

Another way to store the value would be to use an array:

This is certainly better as you can group related data about the book together, but you have no way to add context to the value.

This is where an object is useful. You can declare a single book object and store the data in key:value format:

An object is declared using the curly brackets {} , and each item inside the brackets is written in the key:value format.

An object item is also known as a property, with the key as property name and value as property value.

Like an array, you need to separate each item inside an object using a comma.

You can assign a string or numbers as the key of an item, and you can assign any type of data as the value, including a function:

Here, the describe key or property is a function that prints the title and author value from the object.

The this keyword refers to the context of the code, which is the myBook object in this case.

Usually, an object key is something that gives more context to the value it holds. A key must also be unique, so you can't use the same key twice in the same object.

For example, if you have data about a book, you can use object keys such as title , author , and price to help you understand the context of the value stored in each key.

To access the value of an object, you can use either the dot notation . or the square brackets [] notation.

Here's an example of using the dot notation to access the object properties:

And here's how you use the square brackets to access the same properties:

Keep in mind that you need to wrap the property name in quotes like a string, or JavaScript will think you're passing a variable inside the square brackets.

You can assign a new property to the object using either the dot notation or the square brackets like this:

When you print the object, here's the result:

You can add as many properties as you need to the same object.

To modify an existing property, you need to specify an existing object property using either the dot or square brackets notation followed by the assignment operator as follows:

As you can see, the author property value has been changed.

To delete a property from your object, you need to use the delete operator as follows:

When you try to access the deleted property, you will get the undefined value.

To check if a certain property exists in your object, you can use the in operator like this:

The in operator returns true if the propertyName exists in your object.

See the example below:

Now you know how to manipulate a JavaScript object.

Create a person object with the following properties:

  • name - the person's name
  • age - the person's age
  • greet() - a function to greet another person

Inside the greet() function, introduce the person, specifying the name and the age.

Here's an example output:

Let's build a cash register machine that can add items to a shopping cart, calculate total price, calculate discounts, and accept payment by cash.

The currency is assumed in USD, so you don't need to add it to the program.

The cash register has 3 items for sale:

  • Phone for 300
  • Smart TV for 220
  • Gaming Console for 150

There's a 10% discount when the total price is higher than 400.

The cash register should have a shopping cart that starts empty.

The cash register should provide a method called addItem that takes the name of an item as a parameter. When called, it should check if the item is available for sale. If it is, the item should be added to the shopping cart. If it is not available, show a message saying we don't sell that item.

The cash register should provide a method called calculateTotalPrice that calculates the total price of all the items in the shopping cart. It should iterate over the items in the shopping cart and sum up their prices.

The cash register should provide a method called pay that takes the payment amount as a parameter.

It should calculate the total price of the items in the shopping cart using the calculateTotalPrice method. If the total price is higher than 400, a 10% discount should be applied.

The method should then compare the payment amount with the total price (after applying the discount) and display an appropriate message:

  • If the payment amount is equal to or greater than the total price, it should display a message thanking the customer for the purchase. If there is any change, it should also display the amount of change to be given.
  • If the payment amount is less than the total price, it should display a message indicating that the customer does not have enough money to purchase the items.
  • The program should include appropriate console.log() statements to display messages for adding items to the shopping cart, displaying the total price, and processing the payment.

The program should handle scenarios where the customer's payment amount is exactly equal to the total price, as well as cases where the payment amount is greater or less than the total price.

To build the program, you need to use what you've learned about objects, arrays, conditionals, and loops.

I recommend that you try building the program yourself first. If you get stuck, then see the provided solution below. Good luck!

Congratulations on finishing this handbook! We have gone through quite a lot of concepts together to learn how to code using JavaScript.

I hope you enjoyed the process as much as I enjoy writing it. I would love to get your feedback, learning what you liked and didn't so I can improve the tutorial.

If you want to learn more about JavaScript, I'm creating a course that helps you use JavaScript to build web applications. It's currently in a pre-order period so you can get the course at a lower price and support my work in creating more tutorials. You can check it out here .

The JavaScript Tutorial by Nathan Sebhastian

Using if...else statement:

Using switch...case statement:

Half pyramid pattern:

Inverse half pyramid pattern:

Final Exercise

To test the object, run the code below:

Thanks for reading!

If you enjoyed this handbook and want to take your JavaScript skills to the next level, I recommend you check out my new book Beginning Modern JavaScript here .

beginning-js-cover

The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.

Here's my promise: You will actually feel like you understand what you're doing with JavaScript.

Until next time!

Read more posts .

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

Assignment 1: JavaScript fundamentals

Due thu apr 20 11:59pm pt.

Submissions not accepted after Sat Apr 22 11:59pm PT .

Backstory: As you embark on your web development journey, you decide to set your sights on something we can all get behind: fixing Axess! And hey, those systems are probably so broken that we may as well start from scratch, right? But before you can take on course enrollments, you'll need a few building blocks first. Besides, as we come up on commencement, maybe you can build up your reputation as a reliable web developer by helping out with that.

This assignment will have you practice some fundamental JavaScript concepts and how to use them in the browser. You'll build a small app to simulate students declaring their major and graduating.

Learning goals

After completing this assignment, you will be able to

  • Write functions and classes in JavaScript that manipulate various types and data structures,
  • Create modules that import dependencies,
  • Create a small HTML page with form elements, and
  • Use JavaScript to respond to user events and read form controls.

Getting started

As with assignment 0, follow these steps to get started.

  • Download the starter code and extract the .zip file's contents.
  • Open your command line and navigate to the extracted assign1 directory.
  • Run npm install .
  • Run npm start to start the web server.
  • Open localhost:1930 in your web browser.

Deliverables: We've tried to use boxes like this one to highlight the specific tasks you will need to complete for the assignment. These boxes won't stand alone without the rest of the handout, but consider, for example, using them as a checklist to make sure you've done everything.

Part 1: Warmup exercises

The first part of the assignment consists of a few short warmup exercises, designed to give you practice with JavaScript data structures.

You will write your answers in warmups.js , which has already been included in index.html . We have provided a function testWarmups() , callable from the console, to check your answers.

Task 1a: Using the debugger

The first task will give you practice using the debugger.

  • To begin, please make sure you replace the TODO in the import line at the top of warmups.js with your SUNetID (login name, not number).
  • The function debugExercise calls checkAnswer , passing it a "secret code." Your task is to determine the correct code to pass. But since checkAnswer is being imported from debugme.js , located outside of your assign1 folder, you won't be able to modify it (in order to, for example, add a console.log ).
  • Use the debugger to look at the JavaScript code for checkAnswer . Then, call debugExercise from the console and stop the function while it is running so you can inspect the values of the relevant variables to determine what you must pass to it.
  • Once you have the secret code, replace the TODO in the argument to checkAnswer . Rerunning debugExercise should print a "Success!" message.
  • Finally, fill in the comment in debugExercise with a brief (1-2 sentence) explanation of your strategy: how did you enter the debugger, and where did you stop? How did you read the secret code?

Some notes for this task:

  • The list of files in the Sources tab is split up by where the files are located. You'll find debugme.js under web.stanford.edu .
  • The secret code is a short string of random characters, different for each student. The script that generates it uses some advanced JavaScript features, so we've tucked it away in another file. You may look at the file if you'd like, but it's not necessary (and probably won't help you get the answer).
  • This being the web and JavaScript, there are ways to "circumvent the process" and solve the task without the debugger. We ask that you avoid these unintended alternate strategies, both because we think the debugger is a valuable tool to have in your toolbox, and because we expect that solving the task using the debugger will be much easier. If, after following the process we've outlined, you want to think about how you might solve it a different way, feel free.

Task 1b: Working with data structures

For the rest of this assignment, you'll work with data for a few sample students and departments.

First, open data.js to have a look at the provided data. The file exports a single JavaScript Object with three entries:

  • students is an Array of Objects, each object representing a student. A student object contains their givenName , their surname , and their sunetid . (Note: These aren't the CAs' actual SUNetIDs.) You can assume that SUNetIDs will be unique across all students in the array.
  • depts is an Array of Objects. Each object contains information about a department: its name (like "Computer Science") and its code (like "CS").
  • units is an Object mapping student SUNetIDs (keys) to the number of units that student has completed (values). You may assume that there will be one entry in the object for each student in students .

This data object has been imported into warmups.js as the variable DATA . Once you have reviewed the data, fill in the functions in warmups.js , using DATA , as follows:

  • firstNSunets returns the SUNetIDs of the first n students ( n is a parameter to the function) in the students array. You can assume there are at least n students.
  • shortDeptCodes returns an Object whose keys are department names and whose values are their corresponding codes. But only include a department in the result if its code is exactly two characters long.
  • averageUnits returns the average number of units completed by all students in the data. You can assume there will be at least one student, and you don't need to round or truncate the result.

Each function should be relatively short and will involve some form of iteration. Once you have written these functions, you can use testWarmups (which is exposed to the console) to check that your answers match what we expect.

Note on style and style checking

To help identify some common style issues (and a few functionality issues too), we have includes a configuration file for ESLint .

If you are using VSCode and have installed the ESLint extension, these issues should be highlighted automatically as you code. (If you aren't seeing any highlights, you may have to restart VSCode after you do npm install .)

If you are using something else, or would like to check for lint errors manually, you can run npm run lint in your terminal (you'll have to do this in a different window than the one you ran npm start in).

Note that ESLint won't catch all (or indeed most) style issues. We will give you specific style feedback on your assignment through grading. But having a clean lint run is a good first step!

Part 2: Modeling students and departments

For the remainder of the assignment, you will work with the various other .js files in the public folder. All of these files are imported by index.js . We have included index.js in the provided HTML.

Your next task is to implement two JavaScript classes which we will use to model students and departments in our app.

Task 2a: Student class

Implement the Student class in student.js , and export it as the default (and only) export. An instance of Student will have the following properties (instance variables), which are all "public":

  • sunetid : The student's SUNetID
  • givenName : The student's given name
  • surname : The student's surname
  • dept : The name of the department the student is declared in (a string), or null if the student has not declared yet
  • unitsCompleted : The number of units the student has completed (a number)
  • isAlum : true if the student has graduated, false if not

An instance has the following methods (with corresponding signatures):

  • constructor(sunetid, givenName, surname) : Construct a new Student . The student's SUNetID, given name, and surname are as passed in. Students start undeclared, ungraduated, and with zero units completed.
  • fullName() : Return the student's full name, which is their given name, followed by a space, followed by their surname.
  • addUnits(units) : Increase the number of units the student has completed by the parameter units .
  • toString() : Return a string representing the student, which should be their given name, a space, their surname, another space, and their SUNetID in parentheses. (For example, "Michael Chang (mchang91)")
  • canGraduate() : Return a boolean indicating whether the student can graduate. A student can graduate if they have declared and have completed at least 180 units. If the student has already graduated, this method should throw an Error with a descriptive message.

Task 2b: Department class

Now write the Department class and export it as the default export in dept.js . An instance of Department has the following "public" properties:

  • name : The full name of the department
  • code : The department code
  • students : An array of the current (non-alum) students who have declared under this department

Implement the following methods:

  • constructor(name, code) : Construct a new department with the name and code passed in. Departments start with no current students.
  • toString() : Return the string representation of the department, which is just the department's name.
  • declare(student) : Declare the passed-in Student instance under this department, updating the student's and department's instance variables accordingly. If the student is already declared under this department, this method should return without doing anything. But if the student is already declared under a different department, this method should throw an Error with a descriptive error message.
  • graduate() : Check if each current student in the department can graduate; if they can, mark them as an alum and remove them from the list of current students. Return an array of the just-graduated Student instances.

Some notes on these tasks:

  • You may add additional instance variables and methods to these classes if you wish, but you are not required to.
  • It is a good practice to reuse existing functionality where possible. For example, notice how a Student 's toString contains their full name.
  • You may assume that a client of these classes will not modify the instance variables in a way that makes the instance inconsistent. For example, a client will not directly set a student's dept without going through declare .
  • You aren't required to do any error checking beyond what is described here.
  • Review the end of lecture 3 for the syntax for throwing Error s. Your errors should generate exceptions that can be caught and handled by the client of your class (which you will do in the next part).

Part 3: The App class

Finally, you'll put this app together by implementing the App class (in app.js ).

Task 3a: Console interface

An instance of the App class is constructed by index.js when the page loads. App has the following instance variables:

  • students : An Object mapping students' SUNetIDs (keys) to corresponding Student instances.
  • depts : An Object mapping department codes (keys) to corresponding Department instances.

The constructor has been started for you; you will add to it in the next task. First, implement the following methods:

  • First, reset the students and depts instance variables to be empty. This allows loadData to "reset" the app.
  • Populate the students map with new Student instances, using the students data.
  • Update the number of units each student has completed via the units data.
  • Populate the depts map with new Department instances, based on the passed-in data.
  • declare(sunetid, deptCode) : Takes a SUNetID and department code (both strings) and tries to declare that student under that department, then returns the (updated) Student instance. If the SUNetID or department code isn't known to the app, throw an Error with a descriptive message. (If calling declare on the Department causes an error, don't handle it here.)
  • graduate(deptCode) : Make the department specified by the passed-in code try to graduate its students, returning the list of graduates ( Student instances). If the department code doesn't match a known department, throw an Error with a descriptive message.

You will also need to add imports for Student and Department .

After completing these methods, you will be able to test your app from end to end:

  • The app instance is exposed to the console. You can inspect its instance variables and call its methods.
  • For example, you could call app.declare(“mchang91", "CS") or app.graduate(“BOGUS") . (Note that loadData is already called for you in index.js .)
  • The function testApp , exposed to the console, will attempt to test a variety of methods from part 2 and this task. If anything doesn't match, it will print out an error message. These tests aren't comprehensive, and we encourage you to add some more tests of your own.

Task 3b: User interaction on the page

Your final task of this assignment is to expose the declare and graduate methods you just wrote to a user of the web page:

  • Edit the HTML to add a form with two inputs, one for SUNetID and one for department code. These inputs should be labeled so they are identifiable, and make sure to give them id s so you can reference them in JavaScript.
  • Add two buttons to the form, one for "Declare" and one for "Graduate".
  • When the user types in a SUNetID and department code and clicks "Declare", call your app's declare method with the entered values.
  • If the declaration is successful, display an alert informing the user, including the student's name and the department name. For example, "Michael Chang (mchang91) declared Computer Science!"
  • If the declaration fails, display an alert with the error message. (Note: It's not enough for the error to be printed to the console, since users won't think to look there. You must catch the error and present it via alert .)
  • Similarly, implement the "Graduate" button. This button ignores the entered SUNetID. Upon success, display an alert listing the students who graduated. For example, Graduates: Neel Kishnani (neelk) Jason Chuen (jahchuen) (You can use \n to add a newline in alert messages.)

Some notes on this task:

Screenshot of form controls and buttons

  • You will need to add additional methods to App and are free to add instance variables as well. But you should mark them as "private" by prefixing them with an underscore (_).
  • Recall from lecture 4 that you can access the forms on a web page using document.forms , and you can reference the controls of a form using their id or a property of the form.
  • Remember that a <button>l; inside of a <form> defaults to having type="submit" , meaning it will refresh the page when clicked. You'll want to change its type to button to avoid this.
  • Don't forget to bind your event handlers! As seen in lecture 4, it is best practice to do this in the constructor (and this is preferred over creating functions on the fly.)

When you are finished, please remember to delete your node_modules folder , and then submit your assign2 folder to Paperless .

  • JavaScript Home
  • ▼JavaScript Exercises
  • Exercises Home
  • Fundamental(ES6) Part-I
  • Fundamental(ES6) Part-II
  • Error Handling
  • Conditional statements and loops
  • Event Handling
  • Asynchronous
  • Object-Oriented Programming
  • Linked List
  • String/Text
  • Bit Manipulation
  • Validation with Regular expression
  • Validation without Regular expression
  • Sorting Algorithm
  • Searching Algorithm
  • ..More to come..

JavaScript basic - Exercises, Practice, Solution

Javascript basic [150 exercises with solution].

1. Write a JavaScript program to display the current day and time in the following format.   Sample Output : Today is : Tuesday. Current time is : 10 PM : 30 : 38 Click me to see the solution

2. Write a JavaScript program to print the current window contents.   Click me to see the solution

3. Write a JavaScript program to get the current date.   Expected Output : mm-dd-yyyy, mm/dd/yyyy or dd-mm-yyyy, dd/mm/yyyy Click me to see the solution

4. Write a JavaScript program to find the area of a triangle where three sides are 5, 6, 7.   Click me to see the solution

5. Write a JavaScript program to rotate the string 'w3resource' in the right direction. This is done by periodically removing one letter from the string end and attaching it to the front.   Click me to see the solution

6. Write a JavaScript program to determine whether a given year is a leap year in the Gregorian calendar.   Click me to see the solution

7. Write a JavaScript program to find out if 1st January will be a Sunday between 2014 and 2050.   Click me to see the solution

8. Write a JavaScript program where the program takes a random integer between 1 and 10, and the user is then prompted to input a guess number. The program displays a message "Good Work" if the input matches the guess number otherwise "Not matched".   Click me to see the solution

9. Write a JavaScript program to calculate the days left before Christmas.   Click me to see the solution

sample form

11. Write a JavaScript program to convert temperatures to and from Celsius, Fahrenheit.   [ Formula : c/5 = (f-32)/9 [ where c = temperature in Celsius and f = temperature in Fahrenheit ] Expected Output : 60°C is 140 °F 45°F is 7.222222222222222°C Click me to see the solution

12. Write a JavaScript program to get the website URL (loading page).   Click me to see the solution

13. Write a JavaScript exercise to create a variable using a user-defined name.   Click me to see the solution

14. Write a JavaScript exercise to get the filename extension.   Click me to see the solution

15. Write a JavaScript program to get the difference between a given number and 13, if the number is broader than 13 return double the absolute difference.   Click me to see the solution

16. Write a JavaScript program to compute the sum of the two given integers. If the two values are the same, then return triple their sum.   Click me to see the solution

17. Write a JavaScript program to compute the absolute difference between a specified number and 19. Returns triple the absolute difference if the specified number is greater than 19.   Click me to see the solution

18. Write a JavaScript program to check a pair of numbers and return true if one of the numbers is 50 or if their sum is 50.   Click me to see the solution

19. Write a JavaScript program to check whether a given integer is within 20 of 100 or 400.   Click me to see the solution

20. Write a JavaScript program to check two given integers whether one is positive and another one is negative.   Click me to see the solution

21. Write a JavaScript program to create another string by adding "Py" in front of a given string. If the given string begins with "Py" return the original string.   Click me to see the solution

22. Write a JavaScript program to remove a character at the specified position in a given string and return the modified string.   Click me to see the solution

23. Write a JavaScript program to create a new string from a given string by changing the position of the first and last characters. The string length must be broader than or equal to 1.   Click me to see the solution

24. Write a JavaScript program to create another string from a given string with the first character of the given string added to the front and back.   Click me to see the solution

25. Write a JavaScript program to check whether a given positive number is a multiple of 3 or 7.   Click me to see the solution

26. Write a JavaScript program to create a string from a given string. This is done by taking the last 3 characters and adding them at both the front and back. The string length must be 3 or more.   Click me to see the solution

27. Write a JavaScript program to check whether a string starts with 'Java' if it does not otherwise.   Click me to see the solution

28. Write a JavaScript program to check whether two given integer values are in the range 50..99 (inclusive). Return true if either of them falls within the range.   Click me to see the solution

29. Write a JavaScript program to check whether three given integer values are in the range 50..99 (inclusive). Return true if one or more of them are in the specified range.   Click me to see the solution

30. Write a JavaScript program to check whether a string "Script" appears at the 5th (index 4) position in a given string. If "Script" appears in the string, return the string without "Script" otherwise return the original one.   Click me to see the solution

31. Write a JavaScript program to find the largest of three given integers.   Click me to see the solution

32. Write a JavaScript program to find the closest value to 100 from two numerical values.   Click me to see the solution

33. Write a JavaScript program to check whether two numbers are in the range 40..60 or 70..100 inclusive.   Click me to see the solution

34. Write a JavaScript program to find the largest number from the two given positive integers. The two numbers are in the range 40..60 inclusive.   Click me to see the solution

35. Write a program to check whether a specified character exists between the 2nd and 4th positions in a given string.   Click me to see the solution

36. Write a JavaScript program that checks whether the last digit of three positive integers is the same.   Click me to see the solution

37. Write a JavaScript program to produce a new string that has the first 3 characters in lower case from a given string. If the string length is less than 3 convert all the characters to upper case.   Click me to see the solution

  • If the total marks fall within the range of 89 to 100 (inclusive), the student receives an A+ grade.
  • If the examination is labeled as "Final-exam," the student will receive an A+ grade only if their total marks are 90 or greater. Assume that final examination means we pass 'true' as second parameter otherwise blank.
  • If the student achieves an A+ grade, the program should return 'true'; otherwise, it should return 'false'.

39. Write a JavaScript program to compute the sum of the two given integers. If the sum is in the range 50..80 return 65 otherwise return 80.   Click me to see the solution

40. Write a JavaScript program to check from two given integers whether one of them is 8 or their sum or difference is 8.   Click me to see the solution

41. Write a JavaScript program to check a set of three numbers; if the three numbers are the same return 30; otherwise return 20; and if two numbers are the same return 40.   Click me to see the solution

42. Write a JavaScript program to check whether three given numbers are increasing in strict or in soft mode.   Note: Strict mode -> 10, 15, 31 : Soft mode -> 24, 22, 31 or 22, 22, 31 Click me to see the solution

43. Write a JavaScript program to check from three given numbers (non negative integers) that two or all of them have the same rightmost digit.   Click me to see the solution

44. Write a JavaScript program that evaluates three given integers to determine if any one of them is greater than or equal to 20 and less than at least one of the other two.   Click me to see the solution

45. Write a JavaScript program that checks two integer values and returns true if either one is 15 or if their sum or difference is 15.   Click me to see the solution

46. Write a JavaScript program to check two given non-negative integers if one (not both) is a multiple of 7 or 11.   Click me to see the solution

47. Write a JavaScript program to check whether a given number exists in the range 40..10000.   For example 40 presents in 40 and 4000 Click me to see the solution

48. Write a JavaScript program to reverse a given string.   Click me to see the solution

49. Write a JavaScript program to replace every character in a given string with the character following it in the alphabet.   Click me to see the solution

50. Write a JavaScript program to capitalize the first letter of each word in a given string.   Click me to see the solution

51. Write a JavaScript application that transforms a provided numerical value into hours and minutes.   Click me to see the solution

52. Write a JavaScript program to convert letters of a given string alphabetically.   Click me to see the solution

53. Write a JavaScript program to check whether the characters a and b are separated by exactly 3 places anywhere (at least once) in a given string.   Click me to see the solution

54. Write a JavaScript program to count the number of vowels in a given string.   Click me to see the solution

55. Write a JavaScript program to check whether a given string contains an equal number of p's and t's.   Click me to see the solution

56. Write a JavaScript program to divide two positive numbers and return the result as string with properly formatted commas.   Click me to see the solution

57. Write a JavaScript program to create one string of specified copies (positive numbers) of a given string.   Click me to see the solution

58. Write a JavaScript program to create an updated string of 4 copies of the last 3 characters of a given original string. The string length must be 3 and above.   Click me to see the solution

59. Write a JavaScript program to extract the first half of a even string.   Click me to see the solution

60. Write a JavaScript program to create a new string without the first and last characters of a given string.   Click me to see the solution

61. Write a JavaScript program to concatenate two strings except for their first character.   Click me to see the solution

62. Write a JavaScript program to move the last three characters to the start of a given string. The string length must be greater than or equal to three.   Click me to see the solution

63. Write a JavaScript program to create a string using the middle three characters of a given string of odd length. The string length must be greater than or equal to three.   Click me to see the solution

64. Write a JavaScript program to concatenate two strings and return the result. If the length of the strings does not match, then remove the characters from the longer string.   Click me to see the solution

65. Write a JavaScript program to test whether a string ends with "Script". The string length must be greater than or equal to 6.   Click me to see the solution

66. Write a JavaScript program to display the city name if the string begins with "Los" or "New" otherwise return blank.   Click me to see the solution

67. Write a JavaScript program to create a new string from a given string. This program removes the first and last characters of the string if the first or last character is 'P'. Return the original string if the condition is not satisfied.   Click me to see the solution

68. Write a JavaScript program to create a new string using the first and last n characters from a given string. The string length must be larger than or equal to n.   Click me to see the solution

69. Write a JavaScript program to compute the sum of three elements of a given array of integers of length 3.   Click me to see the solution

70. Write a JavaScript program to rotate the elements left in a given array of integers of length 3.   Click me to see the solution

71. Write a JavaScript program to check whether 1 appears in the first or last position of a given array of integers. The array length must be larger than or equal to 1.   Click me to see the solution

72. Write a JavaScript program to check whether the first and last elements are the same in a given array of integers of length 3.   Click me to see the solution

73. Write a JavaScript program to reverse the elements of a given array of integers of length 3.   Click me to see the solution

74. Write a JavaScript program to find the largest value between the first and last elements and set all the other elements to that value. Display the updated array.   Click me to see the solution

75. Write a JavaScript program to create an array taking the middle elements of the two arrays of integer and each length 3.   Click me to see the solution

76. Write a JavaScript program to create an array by taking the first and last elements from a given array of integers. The length must be larger than or equal to 1.   Click me to see the solution

77. Write a JavaScript program to test whether an array of integers of length 2 contains 1 or 3.   Click me to see the solution

78. Write a JavaScript program to test whether an array of integers of length 2 does not contain 1 or 3.   Click me to see the solution

79. Write a JavaScript program to test whether a given array of integers contains 30 and 40 twice. The array length should be 0, 1, or 2.   Click me to see the solution

80. Write a JavaScript program to swap the first and last elements of a given array of integers. The array length should be at least 1.   Click me to see the solution

81. Write a JavaScript program to add two digits to a given positive integer of length two.   Click me to see the solution

82. Write a JavaScript program to add two positive integers without carrying.   Click me to see the solution

83. Write a JavaScript program to find the longest string from a given array of strings.   Click me to see the solution

84. Write a JavaScript program to replace each character in a given string with the next in the English alphabet.   Note: 'a' will be replace by 'b' or 'z' would be replaced by 'a'. Click me to see the solution

85. Write a JavaScript program to divide a given array of positive integers into two parts. First element belongs to the first part, second element belongs to the second part, and third element belongs to the first part and so on. Now compute the sum of two parts and store it in an array of size two.   Click me to see the solution

  • Acute angle: An angle between 0 and 90 degrees.
  • Right angle: An 90 degree angle.
  • Obtuse angle: An angle between 90 and 180 degrees.
  • Straight angle: A 180 degree angle.

87. Write a JavaScript program to determine if two arrays of integers of the same length are similar. The arrays will be similar if one array can be obtained from another array by swapping at most one pair of elements.   Click me to see the solution

88. Write a JavaScript program that takes two integers and a divisor. If the given divisor divides both integers and does not divide either, two specified integers are similar. Check whether two integers are similar or not.   Click me to see the solution

89. Write a JavaScript program to check whether it is possible to replace $ in a given expression x $ y = z with one of the four signs +, -, * or / to obtain a correct expression.   For example x = 10, y = 30 and z = 300, we can replace $ with a multiple operator (*) to obtain x * y = z Click me to see the solution

90. Write a JavaScript program to find the k th greatest element in a given array of integers.   Click me to see the solution

91. Write a JavaScript program to find the maximum possible sum of some of its k consecutive numbers (numbers that follow each other in order) in a given array of positive integers.  Click me to see the solution

92. Write a JavaScript program to find the maximum difference between any two adjacent elements of a given array of integers.  Click me to see the solution

93. Write a JavaScript program to find the maximum difference among all possible pairs of a given array of integers.  Click me to see the solution

94. Write a JavaScript program to find the number appearing most frequently in a given array of integers.  Click me to see the solution

95. Write a JavaScript program to replace all numbers with a specified number in an array of integers.  Click me to see the solution

96. Write a JavaScript program to compute the sum of the absolute differences of consecutive numbers in a given array of integers.  Click me to see the solution

97. Write a JavaScript program to find the shortest possible string. This can be converted into a string and converted into a palindrome by adding characters to the end of it.  Click me to see the solution

98. Write a JavaScript program to change the case of the minimum number of letters to make a given string written in upper case or lower case.  Fox example "Write" will be write and "PHp" will be "PHP" Click me to see the solution

99. Write a JavaScript program to check whether it is possible to rearrange the characters of a given string. This is in such a way that it will become equal to another given string.  Click me to see the solution

100. Write a JavaScript program to check if there is at least one element in two given sorted arrays of integers.  Click me to see the solution

101. Write a JavaScript program to check whether a given string contains only Latin letters and no two uppercase and no two lowercase letters are in adjacent positions.  Click me to see the solution

102. Write a JavaScript program to find the number of inversions of a given array of integers.  Note: Two elements of the array a stored at positions i and j form an inversion if a[i] > a[j] and i Click me to see the solution

103. Write a JavaScript program to find the maximum number of a given positive integer by deleting exactly one digit of the given number.   Click me to see the solution

104. Write a JavaScript program to find two elements of an array such that their absolute difference is not larger than a given integer. However, it is as close as possible to the integer.  Click me to see the solution

105. Write a JavaScript program to find the number of times to replace a given number with the sum of its digits. This is until it converts to a single-digit number.  Click me to see the solution

106. Write a JavaScript program to divide an integer by another integer as long as the result is an integer and return the result.  Click me to see the solution

107. Write a JavaScript program to find the number of sorted pairs formed by arrays of integers. This is such that one element in the pair is divisible by the other one.  For example - The output of [1, 3, 2] ->2 - (1,3), (1,2). The output of [2, 4, 6] -> 2 - (2,4), (2,6) The output of [2, 4, 16] -> 3 - (2,4), (2,16), (4,16) Click me to see the solution

108. Write a JavaScript program to create the dot products of two given 3D vectors.  Note: The dot product is the sum of the products of the corresponding entries of the two sequences of numbers. Click me to see the solution

109. Write a JavaScript program to sort an array of all prime numbers between 1 and a given integer.  Click me to see the solution

110. Write a JavaScript program to find the number of even values in sequence before the first occurrence of a given number.  Click me to see the solution

111. Write a JavaScript program to check a number from three given numbers where two numbers are equal. Find the third one.  Click me to see the solution

112. Write a JavaScript program to find the number of trailing zeros in the decimal representation of the factorial of a given number.  Click me to see the solution

113. Write a JavaScript program to calculate the sum of n + n/2 + n/4 + n/8 + .... where n is a positive integer and all divisions are integers.  Click me to see the solution

114. Write a JavaScript program to check whether a given string represents a correct sentence or not. A string is considered a correct sentence if it starts with a capital letter and ends with a full stop (.)  Click me to see the solution

115. Write a JavaScript program to check whether a matrix is a diagonal matrix or not. In linear algebra, a diagonal matrix is a matrix in which the entries outside the main diagonal are all zero (the diagonal from the upper left to the lower right).  Example: [1, 0, 0], [0, 2, 0], [0, 0, 3] ]) = true [1, 0, 0], [0, 2, 3], [0, 0, 3] ]) = false Click me to see the solution

116. Write a JavaScript program to find all the possible options to replace the hash in a string (Consists of digits and one hash (#)) with a digit to produce an integer divisible by 3.  For a string "2*0", the output should be : ["210", "240", "270"] Click me to see the solution

117. Write a JavaScript program to check whether a given matrix is an identity matrix.  Note: In linear algebra, the identity matrix, or sometimes ambiguously called a unit matrix, of size n is the n ? n square matrix with ones on the main diagonal and zeros elsewhere. [[1, 0, 0], [0, 1, 0], [0, 0, 1]] -> true [[1, 0, 0], [0, 1, 0], [1, 0, 1]] -> false Click me to see the solution

118. Write a JavaScript program to check whether a given number is in a given range.  Click me to see the solution

119. Write a JavaScript program to check if a given integer has an increasing digit sequence.  Click me to see the solution

120. Write a JavaScript program to check if a point lies strictly inside the circle.  Input: Center of the circle (x, y) Radius of circle: r Point inside a circle (a, b) Click me to see the solution

121. Write a JavaScript program to check whether a given matrix is lower triangular or not.  Note: A square matrix is called lower triangular if all the entries above the main diagonal are zero. Click me to see the solution

122. Write a JavaScript program to check whether a given array of integers represents a strictly increasing or decreasing sequence.  Click me to see the solution

123. Write a JavaScript program to find out if the members of a given array of integers are a permutation of numbers from 1 to a given integer.  Click me to see the solution

124. Write a JavaScript program to create the NOR value of two given booleans.  Note: In boolean logic, logical nor or joint denial is a truth-functional operator which produces a result that is the negation of logical or. That is, a sentence of the form (p NOR q) is true precisely when neither p nor q is true - i.e. when both of p and q are false Sample Example: For x = true and y = false, the output should be logical_Nor(x, y) = false; For x = false and y = false, the output should be logical_Nor(x, y) = true.

125. Write a JavaScript program to find the longest string in a given array.  Click me to see the solution

126. Write a JavaScript program to get the largest even number from an array of integers.  Click me to see the solution

127. Write a JavaScript program to reverse the order of bits in a integer.  14 -> 00001110 -> 01110000 -> 112 56 -> 00111000 -> 00011100 -> 28 234 -> 11101010 -> 01010111 -> 87 Click me to see the solution

128. Write a JavaScript program to find the smallest round number not less than a given value.  Note: A round number is informally considered to be an integer that ends with one or more zeros.[3] So, 590 is rounder than 592, but 590 is less round than 600. Click me to see the solution

129. Write a JavaScript program to find the smallest prime number strictly greater than a given number.  Click me to see the solution

130. Write a JavaScript program to find the number of even digits in a given integer.  Click me to see the solution

131. Write a JavaScript program to create an array of prefix sums of the given array.  In computer science, the prefix sum, cumulative sum, inclusive scan, or simply scan of a sequence of numbers x0, x1, x2, ... is a second sequence of numbers y0, y1, y2, ..., the sums of prefixes of the input sequence: y0 = x0 y1 = x0 + x1 y2 = x0 + x1+ x2 ... Click me to see the solution

132. Write a JavaScript program to find all distinct prime factors of a given integer.  Click me to see the solution

133. Write a JavaScript program to check whether a given fraction is proper or not.  Note: There are two types of common fractions, proper or improper. When the numerator and the denominator are both positive, the fraction is called proper if the numerator is less than the denominator, and improper otherwise. Click me to see the solution

134. Write a JavaScript program to change the characters (lower case) in a string where a turns into z, b turns into y, c turns into x, ..., n turns into m, m turns into n, ..., z turns into a.  Click me to see the solution

135. Write a JavaScript program to remove all characters from a given string that appear more than once.  Click me to see the solution

136. Write a JavaScript program to replace the first digit in a string (should have at least one digit) with the $ character.  Click me to see the solution

137. Write a JavaScript program to test whether a given integer is greater than 15 and return the given number, otherwise return 15.  Click me to see the solution

138. Write a JavaScript program to reverse the bits of a given 16-bit unsigned short integer.  Click me to see the solution

139. Write a JavaScript program to find the position of the rightmost round number in an array of integers. If there are no round numbers, the function returns 0.   Note: A round number is informally considered to be an integer that ends with one or more zeros. Click me to see the solution

140. Write a JavaScript program to check whether all the digits in a given number are the same or not.   Click me to see the solution

141. Write a JavaScript program to find the number of elements in both arrays.   Click me to see the solution

142. Write a JavaScript program to simplify a given absolute path for a file in Unix-style.   Click me to see the solution

143. Write a JavaScript program to sort the strings of a given array of strings in order of increasing length.   Note: Do not change the order if the lengths of two string are same. Click me to see the solution

144. Write a JavaScript program to break an URL address and put its parts into an array.   Note: url structure : ://.org[/] and there may be no part in the address. Click me to see the solution

145. Write a JavaScript program to find the maximum integer n such that 1 + 2 + ... + n Click me to see the solution

146. Write a JavaScript program to compute the sum of cubes of all integers from 1 to a given integer.   Click me to see the solution

147. Write a JavaScript program to compute the sum of all the digits that occur in a given string.   Click me to see the solution

148. Write a JavaScript program to swap two halves of a given array of integers of even length.   Click me to see the solution

149. Write a JavaScript program to change the capitalization of all letters in a given string.   Click me to see the solution

150. Write a JavaScript program to swap pairs of adjacent digits of a given integer of even length.   Click me to see the solution

More to Come !

* To run the code mouse over on Result panel and click on 'RERUN' button. *

See the Pen javascript-common-editor by w3resource ( @w3resource ) on CodePen .

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-basic-exercises.php

  • Weekly Trends and Language Statistics

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 assignment, javascript assignment operators.

Assignment operators assign values to JavaScript variables.

Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y

Shift Assignment Operators

Operator Example Same As
<<= x <<= y x = x << y
>>= x >>= y x = x >> y
>>>= x >>>= y x = x >>> y

Bitwise Assignment Operators

Operator Example Same As
&= x &= y x = x & y
^= x ^= y x = x ^ y
|= x |= y x = x | y

Logical Assignment Operators

Operator Example Same As
&&= x &&= y x = x && (x = y)
||= x ||= y x = x || (x = y)
??= x ??= y x = x ?? (x = y)

The = Operator

The Simple Assignment Operator assigns a value to a variable.

Simple Assignment Examples

The += operator.

The Addition Assignment Operator adds a value to a variable.

Addition Assignment Examples

The -= operator.

The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example

The *= operator.

The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example

The **= operator.

The Exponentiation Assignment Operator raises a variable to the power of the operand.

Exponentiation Assignment Example

The /= operator.

The Division Assignment Operator divides a variable.

Division Assignment Example

The %= operator.

The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example

Advertisement

The <<= Operator

The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example

The >>= operator.

The Right Shift Assignment Operator right shifts a variable (signed).

Right Shift Assignment Example

The >>>= operator.

The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).

Unsigned Right Shift Assignment Example

The &= operator.

The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable.

Bitwise AND Assignment Example

The |= operator.

The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and assigns the result to the variable.

Bitwise OR Assignment Example

The ^= operator.

The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands and assigns the result to the variable.

Bitwise XOR Assignment Example

The &&= operator.

The Logical AND assignment operator is used between two values.

If the first value is true, the second value is assigned.

Logical AND Assignment Example

The &&= operator is an ES2020 feature .

The ||= Operator

The Logical OR assignment operator is used between two values.

If the first value is false, the second value is assigned.

Logical OR Assignment Example

The ||= operator is an ES2020 feature .

The ??= Operator

The Nullish coalescing assignment operator is used between two values.

If the first value is undefined or null, the second value is assigned.

Nullish Coalescing Assignment Example

The ??= operator is an ES2020 feature .

Test Yourself With Exercises

Use the correct assignment operator that will result in x being 15 (same as x = x + y ).

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

w3docs logo

  • Password Generator
  • HTML Editor
  • HTML Encoder
  • JSON Beautifier
  • CSS Beautifier
  • Markdown Convertor
  • Find the Closest Tailwind CSS Color
  • Phrase encrypt / decrypt
  • Browser Feature Detection
  • Number convertor
  • CSS Maker text shadow
  • CSS Maker Text Rotation
  • CSS Maker Out Line
  • CSS Maker RGB Shadow
  • CSS Maker Transform
  • CSS Maker Font Face
  • Color Picker
  • Colors CMYK
  • Color mixer
  • Color Converter
  • Color Contrast Analyzer
  • Color Gradient
  • String Length Calculator
  • MD5 Hash Generator
  • Sha256 Hash Generator
  • String Reverse
  • URL Encoder
  • URL Decoder
  • Base 64 Encoder
  • Base 64 Decoder
  • Extra Spaces Remover
  • String to Lowercase
  • String to Uppercase
  • Word Count Calculator
  • Empty Lines Remover
  • HTML Tags Remover
  • Binary to Hex
  • Hex to Binary
  • Rot13 Transform on a String
  • String to Binary
  • Duplicate Lines Remover

Ace Your JavaScript Assignments: How Assignment Writing Services Can Help Students

Jun 14, 2023

Ace Your JavaScript Assignments

Almost every website you visit has some JavaScript working behind the scenes. So, if you want to jazz up websites, JavaScript is your go-to. If you know JavaScript, you've got a real shot at landing a great job. There are tons of companies out there hungry for JavaScript gurus. They need people who can make their websites slick, user-friendly, and interactive.

Just like with any other skill, the key to mastering JavaScript is practice, practice, and more practice. And what better way to practice than through assignments? Often, they mirror real-life programming challenges. This means students get hands-on experience solving problems they're likely to encounter in the working world.

What’s more, assignments cover a wide range of topics. This way, students get to explore all the different corners of JavaScript, from basic syntax and functions to more advanced stuff like asynchronous programming and using APIs.

Assignments, especially in subjects like JavaScript, can be a tough nut to crack. When the going gets tough, there's no shame in reaching out for a little help. That's where assignment services come into play, and UK assignment is a particularly reliable one.

Imagine you're working late at night on a JavaScript assignment, and you hit a roadblock. You've tried several approaches, but nothing seems to work. That's when homework help can come in handy. Instead of spending hours stuck in the same spot, you can reach out to assignment writing services for guidance. The team there specializes in academic support and has a deep understanding of JavaScript.

A Typical JavaScript Assignment Structure

A typical JavaScript assignment may vary based on the learning level and the topic at hand. However, many assignments tend to follow a certain structure to ensure a comprehensive understanding of the subject matter.

Problem Statement

This is where the task is clearly defined. It includes:

  • what needs to be accomplished
  • any specific requirements
  • the expected output
  • sometimes even hints or steps to get you started.

This could involve:

  • creating a specific function
  • building a web application
  • fixing existing code.

This section may provide links to relevant learning materials or tools that may assist you in solving the task. For example, reference to particular JavaScript methods , libraries, or frameworks that might be relevant to the assignment.

Code Section

This is where you'll do most of your work. Depending on the platform you're using, this could be an online code editor embedded into the assignment page or a local development environment where you write and test your code.

Most assignments will also include tests, which are used to automatically check if your code meets the assignment's requirements. These tests can be very useful for getting immediate feedback on your work.

Once you're done, there will be instructions on how to submit your assignment. This could be as simple as hitting a "Submit" button on the task page, or it may involve uploading files to a specific location.

Remember, each JavaScript task is an opportunity to learn and practice. It's important to take the time to understand the problem, plan your solution, and review your work before submission.

Acing Your Java Script Assignment

Acing Your Java Script Assignment

Assignments often involve complex problems that require a deep understanding of the language's concepts and techniques. Let's explore how services can help students ace their JavaScript assignments.

A Guide through Complex Problems

Assignment writing services offer expert guidance to navigate through intricate JavaScript tasks. Whether it's working with advanced functions, asynchronous programming, or using JavaScript libraries, these services can provide clarification and instruction.

Enhanced Understanding

An assignment service doesn't just provide answers. It helps students to understand the 'why' and 'how' behind the solutions. It breaks down complex concepts into comprehensible pieces, providing a better grasp of the topic and paving the way for easier problem-solving in the future.

Quality Check and Proofreading

Once you've completed a task, the service can also review your work, identifying any errors and suggesting improvements. This not only helps enhance the quality of your assignment but also assists in refining your JavaScript skills.

Time Management

Learning JavaScript while juggling other academic and personal responsibilities can be tough. Assignment writing services can help manage your workload effectively, ensuring you meet your deadlines without compromising the quality of your work.

Personalized Learning

Every student learns differently. Assignment services often tailor their help to your learning style, providing personalized tips and strategies to improve your understanding and skills.

Improving Grades

With expert guidance, your JavaScript tasks will likely improve in quality, leading to better grades. This can be particularly useful if you're aiming for a high GPA or looking to impress potential employers with your academic performance.

Author's BIO

Karl Bowman is a self-confessed JavaScript junkie with a knack for teaching. He's spent more than ten years in the buzzing tech scene. He worked with everyone from budding startups to big-name companies, all while living and breathing JavaScript. So Karl is a techie with a big heart for teaching and a serious talent for JavaScript.

  • HTML Basics
  • Javascript Basics
  • TypeScript Basics
  • React Basics
  • Angular Basics
  • Sass Basics
  • Vue.js Basics
  • Python Basics
  • Java Basics
  • NodeJS Basics
  • Skip to main content
  • Skip to search
  • Sign up for free

6. JavaScript fundamentals

Core modules

JavaScript is a huge topic, with so many different features, styles, and techniques to learn, and so many APIs and tools built on top of it. This module focuses mostly on the essentials of the core language, plus some key surrounding topics — learning these topics will give you a solid basis to work from.

General resources:

  • Learn JavaScript , Scrimba Course partner
  • What is JavaScript?
  • A first splash into JavaScript

6.1 Variables

Learning outcomes:

  • Understand what variables are and why they are so important in programming generally, not just JavaScript.
  • Declaring variables with let and initializing them with values.
  • Reassigning variables with new values.
  • Creating constants with const .
  • The difference between variables and constants, and when you would use each one.
  • Understand variable naming best practices. If not explicitly covered, all examples should show good variable naming pratices in action.
  • The different types of value that can be stored in variables — strings, numbers, booleans, arrays, and objects.
  • Storing the information you need — Variables
  • Basic number operations in JavaScript — add, subtract, multiply, and divide.
  • Understand that numbers are not numbers if they are defined as strings, and how this can cause calculations to go wrong.
  • Converting strings to numbers with Number() .
  • Operator precedence.
  • Incrementing and decrementing.
  • Assignment operators, e.g. addition assignment and subtraction assignment.
  • Comparison operators.
  • Basic Math object methods, such as Math.random() , Math.floor() , and Math.ceil() .
  • Basic math in JavaScript — numbers and operators
  • Numbers and dates
  • Creating string literals.
  • Understand the need for matching quotes.
  • String concatenation.
  • Escaping characters in strings.
  • Using variables in template literals.
  • Multiline template literals.
  • toString() .
  • includes() .
  • indexOf() .
  • toLowerCase() and toUpperCase() .
  • replace() .
  • Handling text — strings in JavaScript
  • Useful string methods
  • Understand what an array is — a structure that holds a list of variables.
  • The syntax of arrays — [a, b, c] and the accessor syntax, myArray[x] .
  • Modifying array values with myArray[x] = y .
  • push() and pop() .
  • shift() and unshift() .
  • join() and split() .
  • Advanced array methods such as forEach() , map() and filter() .
  • Aside: Intro to arrays , Scrimba Course Partner

6.5 Conditionals

  • Understand what a conditional is — a code structure for running different code paths depending on a test result.
  • if ... else ... else if .
  • Using comparison operators to create tests.
  • AND, OR, and NOT in tests.
  • Switch statements.
  • Ternary operators.
  • Making decisions in your code — conditionals
  • Understand the purpose of loops — a code structure that allows you to do something very similar many times without repeating the same code for each iteration.
  • Basic for loops.
  • Looping through collections with for ... of .
Notes : There are many other types of loop in JavaScript that we haven't listed here. It is not necessary (or useful) to understand all of them at this stage. For now, students need to understand the purpose of loops, and the most common types.
  • break and continue .
  • Looping code

6.7 Functions

  • Understand the purpose of functions — to enable the creation of reusable blocks of code that can be called wherever needed.
  • Understand that functions are used everywhere in JavaScript and that some are built into the browser and some are user-defined.
  • Understand the difference between functions and methods.
  • Invoking a function.
  • Return values.
  • Understand global scope and function/block scope.
  • Passing in arguments to function calls.
  • Named and anonymous functions.
  • Including parameters.
  • Including return values.
  • Callback functions — understand that arguments to functions can themselves be functions, and what this pattern is used for.
  • Arrow functions.
  • Using functions to write less code , Scrimba Course Partner
  • Functions — reusable blocks of code
  • Build your own function
  • Function return values
  • Arrow function expressions

6.8 JavaScript object basics

  • Understand that in JavaScript most things are objects, and you've probably used objects every time you've touched JavaScript.
  • Object literals.
  • Properties and methods.
  • Nesting objects and arrays in objects.
  • Using constructors to create a new object.
  • Object scope, and this .
  • Accessing properties and methods — bracket and dot syntax.
  • Object destructuring.
  • JavaScript object basics
  • Object destructuring assignment

6.9 DOM scripting

  • Understand what the DOM is — the browser's internal representation of the document's HTML structure as a hierarchy of objects, which can be manipulated using JavaScript.
  • Understand the important parts of a web browser and how they are represented in JavaScript — Navigator , Window , and Document .
  • Understand how DOM nodes exist relative to each other in the DOM tree — root, parent, child, sibling, and descendant.
  • Getting references to DOM nodes, for example with querySelector() and getElementById() .
  • Creating new nodes, for example with innerHTML() and createElement() .
  • Adding and removing nodes to the DOM with appendChild() and removeChild() .
  • Adding attributes with setAttribute() .
  • Manipulating styles with Element.style.* and Element.classList.* .
  • Manipulating documents

6.10 Events

  • Understand what events are — a signal fired by the browser when something significant happens, which the developer can run some code in response to.
  • addEventListener() and removeEventListener()
  • Event handler properties.
  • Inline event handler attributes, and why you shouldn't use them.
  • Event objects.
  • Preventing default behavior with preventDefault() .
  • Event delegation.
  • Introduction to events

6.11 Async JavaScript basics

  • Understand the concept of asynchronous JavaScript — what it is and how it differs from synchronous JavaScript.
  • Understand that callbacks and events have historically provided the means to do asynchronous programming in JavaScript.
  • Basic usage.
  • Understanding async function return values.
  • Error handling with try ... catch .
  • Understand that async / await use promises under the hood; they provide a simpler abstraction.
  • Chaining promises.
  • Catching errors with catch() .
  • Asynchronous JavaScript

6.12 Network requests with fetch()

  • Understand that fetch() is used for asynchronous network requests, which is by far the most common asynchronous JavaScript use case on the web.
  • Text content, JSON , media assets, etc.
  • Data from RESTful APIs . Learn the basic concepts behind REST, including common patterns such as CRUD .
  • Accessibility issues behind asynchronous updates, for example, content updates not being announced by screen readers by default.
  • Usability issues behind asynchronous updates, like loss of history and breaking the back button.
  • Understand HTTP basics. You should look at common HTTP methods such as GET , DELETE , POST , and PUT , and how they are handled via fetch() .
  • Fetching data from the server

6.13 Working with JSON

  • Understand what JSON is — a very commonly used data format based on JavaScript object syntax.
  • Understand that JSON can also contain arrays.
  • Retrieve JSON as a JavaScript object using mechanisms available in Web APIs (e.g. Response.json() in the Fetch API).
  • Access values inside JSON data using bracket and dot syntax.
  • Converting between objects and text using JSON.parse() and JSON.stringify() .
  • Working with JSON
  • JSON Review , Scrimba Course Partner

6.14 Libraries and frameworks

  • Understand what third-party code is — functionality written by someone else that you can use in your own project, so you don't have to write everything yourself.
  • Efficiency and productivity: A huge amount of complex functionality is already written for you to use, created in a way that enforces efficient, modular code organization.
  • Compatibility: Reputable framework code is already optimized to work across browsers/devices, for performance, etc. Many frameworks also have systems to output to specific platforms (e.g. Android or iOS) as build targets.
  • Support/ecosystem: Popular frameworks have vibrant communities and help resources to provide support, and rich systems of extensions/plugins to add functionality.
  • A library tends to be a single code component that offers a solution to a specific problem, which you can integrate into your own app (for example, chart.js for creating <canvas> -based charts, or three.js for simplified 3D GPU-based graphics rendering), whereas a framework tends to be a more expansive architecture made up of multiple components for building complete applications.
  • A library tends to be unopinionated about how you work with it in your codebase, whereas a framework tends to enforce a specific coding style and control flow.
  • They can provide a lot of functionality and save you a lot of time.
  • A lot of companies use popular frameworks such as React or Angular to write their applications, therefore a lot of jobs list frameworks as requirements for applicants to have.
  • Can easily be overkill for a small project — you might be better off writing a few lines of vanilla JavaScript to solve the problem or using a tailored library.
  • Usually adds a lot of JavaScript to the initial download of your application, leading to an initial performance hit and possible usability issues.
  • Usually comes with its own set of custom syntax and conventions, which can introduce a significant additional learning curve to the project.
  • May be incompatible with an existing codebase because of its architecture choice.
  • Will need to be updated regularly, possibly leading to extra maintenance overhead for your application.
  • May introduce significant accessibility issues for people using assistive technologies because of its architecture (for example, SPA-style client-side routing), which will need to be considered carefully.
  • Solve your problems while offering advantages that significantly outweigh any negatives that it brings to the table.
  • Have good support and a friendly community.
  • Be actively maintained — don't choose a codebase that has not been updated for over a year, or has no users.
  • Introduction to client-side frameworks
  • Introduction to React , Scrimba Course Partner

6.15 Debugging JavaScript

  • Understand the different types of JavaScript errors, for example, syntax errors and logic errors.
  • Learn about the common types of JavaScript error messages and what they mean.
  • Using browser developer tools to inspect the JavaScript running on your page and see what errors it is generating.
  • Using console.log() and console.error() for simple debugging.
  • Using conditionals to avoid errors.
  • try ... catch .
  • Advanced JavaScript debugging with breakpoints, watchers, etc.
  • What went wrong? Troubleshooting JavaScript
  • Control flow and error handling > Exception handling statements
  • The Firefox JavaScript debugger , Firefox Source Docs
  • Chrome > Console overview , developer.chrome.com (2019)
  • Chrome > Debug JavaScript , developer.chrome.com (2017)

javascript assignment for students

🟨 Create your first JavaScript assignment

This tutorial will guide you through all the steps to create your first JavaScript assignment in CodeGrade. For this tutorial, we will consider the example below. The zip folder contains a completed solution and a template file. Please make sure to save this file somewhere accessible on your computer:

A quick note about this example In this assignment, students have been asked to create a JavaScript program that prompts the user for their name in the console and prints a greeting. It is a purely console-based application.

Step 1: Create an assignment

First, we need an assignment to work with. Whether CodeGrade is integrated into your LMS or you are using CodeGrade Standalone, you can follow the steps in the guide below to get started:

Step 2: Configure submission settings

The first step in setting up an assignment is to ensure that students can submit their code correctly. Because this example is straightforward and only requires a single solution file, we will offer the students the option to code in the CodeGrade Editor alongside the default File Uploader option.

Navigate to the Assignment Management page by using the ⚙️ icon at the right-hand side of the page header on the submissions page.

Find the Submission settings in the corresponding container under the General tab.

Enable the File uploader and Editor submission methods by clicking the respective check boxes.

Enabling the Editor will reveal the Template files option. Unzip the Greeting.zip folder and upload Greeting/Template/greeting.js file as the template.

Finalize your settings by clicking the "Submit" button.

It is good practice to provide a template file when enabling the Editor so that your students don't have to create their own file. This also avoids the risk of students submitting a file with the wrong name.

For more information about submission methods, see submission settings .

Step 3: Create a rubric

While you can always grade assignments directly by manually setting the Final grade , It's only possible to award points for your automatic tests with Rubrics . Rubrics also allow you to standardize the grading scheme for graders and clarify the grading requirements for your students.

CodeGrade offers two types of rubric categories:

Discrete category - Specify points in discrete steps (e.g. 0, 5, or 10 points)

Continuous category - Specify points as a continuous scale (e.g. 0 - 10)

Navigate to the Rubric tab on the Assignment Management page.

Select Create new rubric .

Create 2 new Continuous Categories . Set the parameters as follows:

Category nameDescriptionMin - Max points

Step 4: Create automatic tests

Automatic tests are really what allow your students to learn uniquely. The immediate feedback they get from the automatic tests allows them to learn through trial and error by applying the instant feedback and resubmitting their work.

For this tutorial, we will set up two automatic tests: IO tests and Semgrep code structure tests.

Step 4.1: Setup

Before creating the tests, we need to ensure we have the correct version of Node installed.

Navigate to the Setup tab under the AutoTest settings.

Add an Install Node block to your configuration.

Select Node version 18 to install.

Step 4.2: Input/Output tests

Input/Output tests (or "IO tests" for short) are a great way of checking a program's functionality by providing various input cases that should result in different outputs. You can create IO test cases in AutoTest v2 using the IO Test wrapper block and its corresponding Full match , Substring match , and Regex match blocks.

Navigate to the Tests tab of the AutoTest settings.

Add a Connect rubric block to your AutoTest configuration. Select the "IO tests" rubric category from the drop-down menu.

Add an IO test block to your AutoTest configuration and nest it inside the Connect Rubric block.

In the editor provided, use the command node greeting.js to run the program.

Add three Substring match blocks to your AutoTest configuration and nest them inside the IO test block. Make sure each match block is case insensitive and ignores whitespaces.

Copy and paste the info from the table below into the Input and Expected output fields in their respective match block:

InputExpected output

Each input must have a trailing newline for it to be recognized (i.e., "James\n").

It's a good idea to give your tests descriptive names so that it's clear to both you and your students what is actually being checked (e.g., "Does your program produce the correct output? - Input: 5").

Step 4.3: Code structure tests

Semgrep is a code structure testing framework that is excellent for checking if students have used a specific syntax to reach their solution. AutoTest v2 offers the Code structure test block and its corresponding Positive match and Negative match blocks for running Semgrep tests. For more details on setting up Code Structure Tests, read our dedicated guide .

For this example, we want to check that the students have used an if-else statement in their program. Here is the Semgrep rule we will be using:

Add a Connect rubric block to your test configuration and select the "Code structure tests" rubric category.

Add a Code structure test block to your test configuration and nest it within the Connect rubric block.

In the Student file input field, write "greeting.js".

Add a Positive match block to your test configuration and nest it within the Code structure test block.

Copy and paste the Semgrep rule in the code block above into the provided editor. Make sure to delete the template provided.

Step 5: Test and publish your AutoTests

It's important to test your AutoTest configuration before running it on students' submissions to ensure your tests are running as expected and to check for edge cases. This is easy to do with Snapshots . When you're ready to check your tests, press the Build snapshot button at the bottom of the test block sidebar. This will make a test run of your AutoTest configuration on your Test submission.

CodeGrade will prompt you to upload a Test submission the first time you build a snapshot. Use the "Click here to upload files" option or drag-and-drop the Greeting/Solution/greeting.js file you downloaded at this tutorial's beginning and click "Submit".

If in the future you need to re-upload your test submission, you can do so by going to Upload Submission option in the General Settings tab. Just upload your file and check the "Test Submission" option before clicking "Submit".

Once you're happy with your tests, you must publish them to your students so they can run on their submissions. Publish your tests by building a snapshot, and at the bottom of the pop-up modal, click the Publish to students button. Once it is published, AutoTest V2 is available for students through the editor and on the submission page.

You have just built your first automatically graded assignment and are ready for your students to begin submitting work!

This guide is designed to get you started with a completed assignment but doesn't go into explicit detail about all of the features CodeGrade offers. For more in-depth information about the product and the various workflows you can achieve, see Learn more or contact our support team at [email protected].

Last updated 1 month ago

javascript assignment for students

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

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.

Best Way for Conditional Variable Assignment

Which is the better way for conditional variable assignment?

I actually prefer 2nd one without any specific technical reason. What do you guys think?

Emile Bergeron's user avatar

  • 4 Doesn't the first limit myVariable to the scope it has been assigned in and can't be used outside of the if or the else it has been assigned in. –  Tomaltach Commented Oct 13, 2017 at 9:59
  • 1 var is funky in javascript and is scoped to the function (or global) not the block. That's another advantage of using let over var . –  Jordan Soltman Commented Jun 4, 2019 at 1:27

15 Answers 15

dku.rajkumar's user avatar

  • 5 Is this different than the first way? Isn't it the same thing with different syntax? –  Andy Groff Commented Jun 7, 2012 at 6:48
  • @Rajkumar, This is no different from the first. I actually want clarification about the over-riding thing. The second way is assigning a variable and then overriding it with something else. Is that a good way to do? –  RaviTeja Commented Jun 7, 2012 at 8:13
  • 1 yeah.. you can do that. whenever there is a default value.. .second way is good. In second way actually you are assigning a default value false and later on you are modifying it based on conditions. –  dku.rajkumar Commented Jun 7, 2012 at 9:59
  • What if you have 3? Why no inline ifelse statement in the world? –  gunslingor Commented Aug 23, 2022 at 19:43

There are two methods I know of that you can declare a variable's value by conditions.

Method 1: If the condition evaluates to true, the value on the left side of the column would be assigned to the variable. If the condition evaluates to false the condition on the right will be assigned to the variable. You can also nest many conditions into one statement.

Nesting example of method 1: Change variable A value to 0, 1, 2 and a negative value to see how the statement would produce the result.

Method 2: In this method, if the value of the left of the || is equal to zero, false, null, undefined, or an empty string, then the value on the right will be assigned to the variable. If the value on the left of the || does not equal to zero, false, null undefined, or an empty string, then the value on the left will be assigned to the variable.

Although the value on the left can be an undefined value for JS to evaluate the condition but the variable has to be declared otherwise an exception will be produced.

Kevin Ng's user avatar

  • 1 I like the || because it reminds me of perl in the olden days. –  MarkHu Commented Oct 31, 2018 at 18:07

An alternative way of doing this is by leveraging the ability of logical operators to return a value.

let isAnimal = false; let isPlant = true; let thing = isAnimal && 'animal' || isPlant && 'plant' || 'something else'; console.log(thing);

In the code above when one of the flags is true isAnimal or isPlant , the string next to it is returned. This is because both && and || result in the value of one of their operands:

  • A && B returns the value A if A can be coerced into false; otherwise, it returns B.
  • A || B returns the value A if A can be coerced into true; otherwise, it returns B.

Answer inspired by this article: https://mariusschulz.com/blog/the-and-and-or-operators-in-javascript

PS: Should be used for learning purposes only. Don't make life harder for you and your coworkers by using this method in your production code.

Julian E.'s user avatar

  • 1 can anyone explain the PS added at the end? ...Why "learning purposes only" and not for use in production code? My guess is that it's unusual compare to other languages, so it'd maybe cause confusion. –  C-Note187 Commented Mar 28, 2022 at 18:41
  • 1 @C-Note187 I added the PS because while it's a concise way to do assignment, it also hard to understand what the code does on first glance. So if someone's doing code review or maybe finds this line of code during development, he's going to waste some time trying to understand it. In these cases it would be easier to just use if statements so that whoever is looking at the code can understand the logic quickly, with less mental overhead. –  Valentin Commented Apr 1, 2022 at 9:20
  • 1 oh, you are the best. I just wanted more than two on conditions and single ternary operator was not enough and I didn't want that long ifs or switch. –  irakli2692 Commented Jul 17, 2023 at 18:38
  • I think what @Valentin is also getting at with regard to production code is you shouldn't depend on tests that use coerced values but rather do specific tests on variables. –  David Welborn Commented Mar 16 at 15:58

You could do a ternary, which is a lot shorter (and no darn curly braces):

Joseph's user avatar

Another cool thing is that you can do multiple assignment based on a conditional:

aris's user avatar

Third way when you are storing only true false in variabel then use

Just for completion, there is another way in addition to all the others mentioned here, which is to use a lookup table.

Say you have many possible values, you could declaratively configure a Map instead of using an if , switch or ternary statement.

This works even for booleans:

For booleans you would probably do it the 'normal' way though with logic operators specifically designed for that. Though sometimes it can be useful, such as:

  • portability : you can pass a map around
  • configurability : maybe the values come from a property file
  • readability : if you don't care it's a boolean or not, you just want to avoid conditional logic and reduce cognitive load that way

Note there is some overlap between the advantages using a lookup map and advantages of using a function variable (closure).

Benny Bottema's user avatar

The first solution uses only one assignment instead of 1,5 by average in the second code snippet. On the other hand the first code snippet is less readable as people not familiar with JavaScript might not realize that the scope of a variable is not block oriented by function oriented - on other languages with C-like syntax myVariable would not be accessible outside if and else blocks.

In other words both solutions have disadvantages. What about ternary operator:

or if you don't care about the camel-case (although I understand this is just an example, not a real code);

Tomasz Nurkiewicz's user avatar

If you tired of ternary operator then use IIFE

Another way would be to use Immediately Invoked Function Expression . The good thing about it is that it can hold some logic and can be encapsulated from the outside world.

const direction = "n"; const directionFull= (() => { switch(direction ){ case "n": return "north"; case "s": return "south"; case "w": return "west"; case "e": return "east"; } })() console.log(directionFull);

I would prefer 2nd option too, no technical reason but for the sake of easy to read code, readability is very important in code.

If you see the second option, from processing point of view only one check will ever be executed, saved some very minute processing time, so there is only one check in second case.

mprabhat's user avatar

  • one technical reason:there will be only one condition check in second –  user1432124 Commented Jun 7, 2012 at 6:47

It depends on the use for me. If I have code that I only want to run if true, but with no extra code for false, I'll use the second. If I want to execute some code on true, and different on false, I use the first. It all depends on use, but the general rule for me is to write once. Keep it clean, keep it simple, and keep it short

Gareth Parker's user avatar

Maybe you simply need && operator to check if boolean is true, if it is, assing "myVariable" to true.

Eric Valero's user avatar

If all you need to do is convert a boolean to a string, you should do so explicitly:

If it's important that the first letter be capitalized, as in your example, that is not difficult to do; see e.g. this answer .

Malcolm's user avatar

Another approach with Map and Object: (Maps are more flexible with key types and Objects are more readable IMHO)

const condition_var = 'e' const options1 = new Map([ ['n','north'],['s','south'],['e','east'],['w','west']]) const myVar1 = options1.get(condition_var) || null const options2 = {n:'north', s:'south', e:'east', w:'west'} const myVar2 = options2[condition_var] || null console.log(myVar1) console.log(myVar2)

Cesar Morillas's user avatar

If what you're trying to do is set a value if it is not null/undefined, and otherwise use another value, you can use the nullish coalescing operator :

jeffrey.d.m's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

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 you have read our privacy policy .

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

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • Announcing the new Staging Ground Reviewer Stats Widget
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Removing undermount sink
  • How can "chemical-free" surface cleaners work?
  • "00000000000000"
  • Determining Entropy in PHP
  • Example of a forcing notion with finite-predecessor condition that does not add reals
  • Futuristic/Dystopian teen book trilogy with people that can breathe underwater
  • Smallest prime q such that concatenation (p+q)"q is a prime
  • “…[it] became a ______ for me.” Why is "gift" the right answer?
  • Copyright on song first performed in public
  • How to assign a definition locally?
  • Count squares in my pi approximation
  • Sum of the individual kinetic energies of the particles which make the system the same as the K.E. of the center of mass? What's bad in my reasoning?
  • Are There U.S. Laws or Presidential Actions That Cannot Be Overturned by Successor Presidents?
  • Class and macro with same name from different libraries
  • Understanding “Your true airspeed will be the same, but your airspeed as opposed to the ground is much faster.” Bhutan Paro International Airport PBH
  • Confusion about the definition of strict epimorphism
  • Genetic engineering of adult subjects with transform viruses
  • Why is Germany looking to import workers from Kenya, specifically?
  • My math professor is Chinese. Is it okay for me to speak Chinese to her in office hours?
  • Smoking on a hotel room's balcony in Greece
  • Is there a way to hide/show seams on model?
  • Simple XML string to user-friendly plain text converter method in Java
  • Calm and Insight is the Normative Meditative Practice in Buddhism
  • Seeking a text-based version of Paul Dirac's 1926 paper on quantum mechanics

javascript assignment for students

IMAGES

  1. Review Our JavaScript Assignment Template

    javascript assignment for students

  2. JavaScript Suggestions and Tips For Students To Score Good Grades

    javascript assignment for students

  3. Assignment 1

    javascript assignment for students

  4. Assignment Operator in JavaScript

    javascript assignment for students

  5. Mastering JavaScript Assignment: A Comprehensive Guide

    javascript assignment for students

  6. Javascript Assignment 2 KAlpas

    javascript assignment for students

VIDEO

  1. JavaScript Assignment Operators #basicsforbeginners #javascript #coding

  2. Week 3 Javascript Assignment

  3. Assignment with a Returned Value (Basic JavaScript) freeCodeCamp tutorial

  4. 13 assignment operator in javascript

  5. 9 JavaScript Assignment Operators

  6. Day 5: JavaScript Array and JSON

COMMENTS

  1. JavaScript Exercises

    Get certified by completing the JavaScript course. Track your progress - it's free! 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.

  2. JavaScript Exercises, Practice Questions and Solutions

    Benefits of Practice JavaScript. Master JavaScript through engaging exercises that offer: Hands-on learning with interactive quizzes. Progress tracking to monitor your improvement. Effective skill enhancement at your own pace. Immediate feedback for quick learning. Access anytime, anywhere for convenient learning.

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

  4. 40 JavaScript Projects for Beginners

    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. Experiment with adding new features or using different methods. That will test if you have really learned the concepts ...

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

    Practice JavaScript coding with fun, bite-sized exercises. Earn XP, unlock achievements and level up. It's like Duolingo for learning to code.

  6. JavaScript exercises on Exercism

    379,345 students About JavaScript Learn Practice. 263 contributors. 5604 mentors. Practice 148 exercises in JavaScript. Learn and practice JavaScript by completing 148 exercises that explore different concepts and ideas. Join The JavaScript Track Explore the JavaScript exercises on Exercism.

  7. Free Javascript challenges online

    JSchallenger recognizes what skill level you're on and adjusts the difficulty of the next challenges automatically. Making you continuously improve your Javascript skills in a short amount of time. JSchallenger. Free Javascript challenges. Learn Javascript online by solving coding exercises. Javascript for all levels.

  8. Learn JavaScript

    Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity. 4.5. 27,630 ratings. Start. 2,153,231 learners enrolled. This course includes. AI assistance for guided coding help. Projects to apply new skills. Quizzes to test your knowledge.

  9. PDF Introducing Assignment 0: A JavaScript Crash Course

    • This assignment is designed to be an easy warm-up! It may take 15 min for students familiar with JavaScript, and 3+ hours for those with no experience - Rmk: The idea here is to make sure everyone has some JS experience going into A1 - Please style and comment your code so that it is readable.

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

  11. JavaScript Practice Exercises for All Levels

    Free exercises covering the basics to the more advanced aspect of JS like the DOM (document object modal) async function, and more. 3. Show user IP address with JavaScript. An exercise created by our co-founder Charles. Ideal for beginners to practice the basic fetch function in the CodePen code editor. 4.

  12. Learn JavaScript for Beginners

    In JavaScript, the assignment operator is used to assign data or a value to a variable. You've seen some examples of using the assignment operator before, so here's a reminder: // Assign the string value 'Hello' to the 'message' variable let message = "Hello"; // Assign the Boolean value true to the 'on' variable let on = true;

  13. Assignment 1: JavaScript fundamentals

    For the rest of this assignment, you'll work with data for a few sample students and departments. First, open data.js to have a look at the provided data. The file exports a single JavaScript Object with three entries: students is an Array of Objects, each object representing a student.

  14. JavaScript basic

    Expected Output : mm-dd-yyyy, mm/dd/yyyy or dd-mm-yyyy, dd/mm/yyyy Click me to see the solution. 4. Write a JavaScript program to find the area of a triangle where three sides are 5, 6, 7. Click me to see the solution. 5. Write a JavaScript program to rotate the string 'w3resource' in the right direction.

  15. JavaScript Assignment

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  16. Ace Your JavaScript Assignments: How Assignment Writing ...

    This means students get hands-on experience solving problems they're likely to encounter in the working world. What's more, assignments cover a wide range of topics. This way, students get to explore all the different corners of JavaScript, from basic syntax and functions to more advanced stuff like asynchronous programming and using APIs.

  17. 6. JavaScript fundamentals

    JavaScript fundamentals | MDN Curriculum. 6. JavaScript fundamentals. JavaScript is a huge topic, with so many different features, styles, and techniques to learn, and so many APIs and tools built on top of it. This module focuses mostly on the essentials of the core language, plus some key surrounding topics — learning these topics will give ...

  18. Ideas for a comprehensive Javascript assignment

    1. I would most definitely have them write vanilla JavaScript. It will encourage all students to better understand the abstractions that frameworks/libraries provide in particular environments i.e. for the most part, in the browser working with the DOM. I highly recommend having a good text for the course.

  19. Create your first JavaScript assignment

    Step 2: Configure submission settings. The first step in setting up an assignment is to ensure that students can submit their code correctly. Because this example is straightforward and only requires a single solution file, we will offer the students the option to code in the CodeGrade Editor alongside the default File Uploader option.

  20. Assignments on Javascript for beginners?

    1. One of the biggest differences between JavaScript and C is how scope is defined. In C closures are a convenience that are of little importance. In JavaScript closures are incredibly powerful. My suggestion to use is to attempt to write a program in JavaScript using what you know of C. Make the program as object oriented as absolutely possible.

  21. Best Way for Conditional Variable Assignment

    There are two methods I know of that you can declare a variable's value by conditions. Method 1: If the condition evaluates to true, the value on the left side of the column would be assigned to the variable. If the condition evaluates to false the condition on the right will be assigned to the variable. You can also nest many conditions into ...