Checking for the existence of a parameter in a class constructor using JavaScript

I am dealing with a JavaScript class set up like this

class Student {
  constructor(name, age) {}
}

I am looking for a way to throw an error message if one of the parameters (such as 'name') is not passed. For example:

if (!name) {
  return "Oops, you forgot to provide a name"
}

Answer №1

If a value is not provided, the function throwIfMissing() will be called with the default value specified.

    function throwIfMissing() {
       throw new Error('Missing parameter');
    }

    class Student{
        constructor(mustBeProvided = throwIfMissing()) {
             return mustBeProvided;
         }
    }
    var student = new Student(100); //works
    console.log(student);
    var err = new Student(); // throws Uncaught Error: Missing parameter

Answer №2

Examine the arguments object to determine the number of parameters it contains. Simply checking if its value is undefined may not be accurate, as it could have been explicitly assigned the value of undefined.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Facing a node.js installation issue on Windows 10 while using Visual Studio Code (VS

Issue encountered while trying to execute "DownloadString" with one argument: Unable to establish a secure connection due to SSL/TLS channel creation failure. At line:1 char:1 + iex ((New-Object System.Net.WebClient).DownloadString('https ...

What is the best method for animating a display table to none or reducing its height to

My goal is to animate a header whenever the class collapseTest is applied. After some trial and error, I have come up with the following solution: http://jsfiddle.net/robertrozas/atuyLtL0/1/. A big shoutout to @Hackerman for helping me get it to work. The ...

Decoding Lodash: Unveiling the findwhere and copy operator in the realm of

Could someone please explain why using Lodash to fetch an object with findWhere allows for a reference copy that enables dynamic changes based on user actions, while the same operation using the copy operator fails to update the source object? I have creat ...

Load JavaScripts asynchronously with the function getScripts

Asynchronously loading scripts on my login page: $.when( $.getScript("/Scripts/View/scroll-sneak.js"), $.getScript("/Scripts/kendo/kendo.custom.min.js"), $.Deferred(function (defer ...

Tips on creating a subsequent post for a file that has been uploaded to a Node Express server and then forwarded to a different API

We are currently working with an Express server in Node, where we upload a file on one route and then need to send this file to another endpoint for processing. However, the file is not stored locally on the server; it exists as an uploaded object. I&apos ...

Encountering the "ERR_FILE_NOT_FOUND" message within the popup of my Chrome extension

Currently, my manifest file is structured as follows: { "manifest_version": 2, "name": "My Extension", "description": "A starting point for creating a functional Chrome extension", "version": "0.0.1", "browser_action": { "default_popup": " ...

jQuery disregards the else-if statement

Currently, I am developing a web application that prompts the user to input an "application" by providing the StudentID and JobID. With the help of jQuery, I am able to notify the user if the student or job entered does not exist, if the application is alr ...

An HTML form featuring various submit buttons for accomplishing different tasks

After searching extensively, I have come across solutions that are similar but not quite right for my specific situation. Here's what currently works for me: <script type="text/javascript"> function performTask1(a, b) { window.open('intern ...

Assistance with the JQuery Validation Plugin

Currently, I am utilizing the JQuery validation plugin to validate a form. However, in addition to displaying an error message, I also want it to modify the CSS for the td element above it. This is my current implementation: function handleValidationError ...

What is the method for retrieving hotels from a database based on their proximity to a specific set of latitude and longitude coordinates?

I have a database table with latitude, longitude, and hotel locations. I want to create a feature that will show hotels near a specific point defined by latitude and longitude. Code Snippet function findNearbyHotels() { $this->lo ...

Attempting to adjust the style.color of a <label> element with JavaScript results in an error

Why does this code work in Firefox but not in IE9? // turn on the 'image file upload' field and its label document.getElementById('itemImageId').disabled = false; document.getElementById('labelForImageUploadID').style.color = ...

Is there a workaround for the issue of the NodeJS Web Cryptography API require() being undefined in an unsecure origin (Heroku App)?

My goal is to implement the experimental Web cryptography API (SubtleCrypto) on my Node.js server hosted on Herokuapp. The aim is to encrypt data from a fetch request sent from gitpages to herokuapp, concealing sensitive information from the browser consol ...

How to adjust the timezone settings in PHPMyAdmin on a shared server platform

I'm having trouble changing my timezone to India on my shared server database. I've tried everything but can't seem to get it to work. My website is built using PHP Codeigniter The contact us page on my site saves all inquiry details to my ...

Unable to display objects in the console window debugger for debugging purposes

When attempting to print the objects in the console window using the code below, I am receiving an "Undefined" error message. Any advice on how to resolve this issue? var details = [ { name:"Anita", age:"20" },{ name: "H ...

Transform a <td> into a table-row (<tr>) nested within a parent <tr> inside an umbrella structure

Similar questions have been asked in the past, but I still haven't found a solution to my specific inquiry. Here it is: I have a table that needs to be sortable using a JavaScript plugin like ListJS. The key requirement is that I must have only one & ...

Utilizing PHP for Long Polling within AJAXcreateUrlEncodeProtect(chr(

Utilizing AJAX to refresh specific parts of a page without the need for constant reloading. However, I aim for the table to only refresh upon detecting changes (a concept known as long polling). Despite attempting to implement loops with break statements, ...

Expanding parent nodes in Jstree to load child nodes dynamically (json)

I am trying to optimize the performance by loading the child nodes of a parent node only after clicking on that specific parent node. It is important because there are many child nodes, so this method helps in keeping the performance high. Currently, I ha ...

Conceal player controls for HTML videos on iOS devices

How can I hide the video player controls in Windows and Android, they are hidden but still visible on iOS. I have tried different methods but can't seem to hide them. Here is what it looks like on iOS: https://i.sstatic.net/Uwrg3.png Here is my code ...

What is the best way to display information from a Django model using a React frontend?

Currently, I am in the process of developing a personal portfolio website using Django for the backend and React for the frontend components. Within this project, I have set up Django tables to store my education history, work experiences, skills, and port ...

Please enter data into the input fields provided in the text

Below is the code where Google transliteration is used for typing in Indian language in a text field. There are two routes with different page IDs. Initially, the transliteration works fine on the default page. However, when changing routes, an error occur ...