After the function has been executed, the default parameters will still be present. What should be done in this

When I set default parameters in a function and then call the function again without those parameters, they still remain. I want them to be reset on every function call.

It seems like a simple issue, but as a beginner, I'm struggling to understand it...

function test(){
 console.log(name)
 let test = (name !== "undefined") ? "test" : "welp"
}

test(name="harry")
test()

Why does the second test() still output "harry"? Is there a way to fix this without giving up on default parameters?

I thought adding "use strict" would solve the problem, but it didn't work.

Answer №1

The issue arises with the line:

test(name="harry")

In this scenario, you didn't establish a default parameter but instead created a global variable that remains in the global scope, thereby cluttering the environment with that specific value (highlighting why globals are discouraged).

To address default parameters correctly, the code should be structured as follows:

// defining the function while setting its default parameter
// named "name", and assigning it the value of "Harry":
function test(name = "Harry"){
 console.log(name)
 let test = (name !== "undefined") ? "test" : "welp"
}

test("Marge") // outputs Marge
test() // outputs Harry

An alternative approach involves a slight modification:

// defining the function using a default parameter
// named "name", with a value of "Harry":
const test = function (name = "Harry"){
 console.log(name)
 let test = (name !== "undefined") ? "test" : "welp"
}

test("Marge") // outputs Marge
test() // outputs Harry

Alternatively, an Arrow function can be used:

// defining the function with a default parameter
// named "name", set to "Harry":
const test = (name = "Harry") => {
 console.log(name)
 let test = (name !== "undefined") ? "test" : "welp"
}

test("Marge") // outputs Marge
test() // outputs Harry

If multiple defaults are desired:

// defining the function and a parameter to be passed
// to the function, called "opts":
const test = function(opts) {
  // specifying defaults for the function
  // (other approaches exist, but this is an example):
  let defaults = {
      givenName: "Harry",
      familyName: "Harrison"
    },
    // merging the defaults with user-supplied options:
    details = Object.assign(defaults, opts),
    // creating the name using template literals,
    // which incorporate JavaScript into the String:
    name = `${details.givenName} ${details.familyName}`;
  console.log(name)
  let test = (name !== "undefined") ? "test" : "welp"
}

test({
  givenName: "Marge"
}) // outputs Marge Harrison
test({
  familyName: "Kanagarathnam"
}); // outputs Harry Kanagarathnam
test() // outputs Harry Harrison

References:

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

Eliminate any null strings from an object by comparing the object's previous state with its updated state

I am currently implementing an exemptions scheduler using react-multi-date-picker. The react-multi-date-picker component is integrated within a react-table in the following manner: const [data, setData] = useState(0); const [dateValues, setDateValues] = us ...

Accessing feedback from Reddit's API

After writing some code to search Reddit's API with a specific query, I now want it to display comments as well. Inside my $.getJSON statement that retrieves each title/post based on the search query, I have the following nested code block. The goal i ...

Shifting an element to the right before revealing or concealing it with Jquery Show/Hide

$(document).ready(function(){ var speed = 700; var pause = 3500; function removeFirstElement(){ $('ul#newsfeed li:first').hide('slide', {direction: "up"}, speed, function() {addLastElement(thi ...

I am looking to trigger the change event from within the click event in Angular

My objective involves detecting when the cancel button is clicked while a file is being uploaded. I am trying to accomplish this by triggering the click event, then monitoring for the change event. If the change event occurs, the document will be uploaded. ...

Remove the most recent file in a MongoDB collection using a DELETE request

As I delve into the world of REST APIs, one task on my to-do list is to delete the last POST in my mongoDB collection using a DELETE route with mongoose. Despite searching for answers, none seem to provide guidance on achieving this deletion through a rout ...

Adding Gridster to a WordPress theme

I am having an issue with implementing Gridster into my WordPress plugin. Despite correctly loading the necessary files from the folder, it does not seem to work. function add_my_stylesheet() { wp_enqueue_style( 'myCSS', plugins_url( ' ...

Stopping JavaScript when scrolling to the top and running it only when not at the top

I found a great jQuery plugin for rotating quotes: http://tympanus.net/codrops/2013/03/29/quotes-rotator/ Check out this JSFiddle example: http://jsfiddle.net/LmuR7/ Here are my custom settings (with additional options that I haven't figured out yet) ...

Customizing the default button in Ant Design Popconfirm to display "Cancel" instead

When the Ant Design Popconfirm modal is opened, the Confirm ("Yes") button is already preselected. https://i.stack.imgur.com/bs7W7.png The code for the modal is as follows: import { Popconfirm, message } from 'antd'; function confirm(e) { c ...

Identify and handle multiple scenarios in JavaScript without using if statements

I have developed a function that is supposed to evaluate all scenarios and provide an immediate result if one of the cases does not match. const addText = (data, addAlternative) => { return (data !== 'N/T' || data === 0 || data) ? d ...

Engaging with tasks like incorporating fresh elements into JavaScript code

I am looking to implement an event listener that triggers whenever a new element is added to the document or any of its children. Can someone recommend a method for accomplishing this? ...

A guide on how to initiate a click event in Angular 5 using JQuery

I am trying to trigger a click event for each element based on its id, but it doesn't seem to be working. Below is the code I am using: ngOnInit() { this.getProductsLists(); } getProductsLists() { this.supplierService.getProductLists() .sub ...

Delay the execution of the function in AngularJS until the browser has finished rendering completely and the view-model synchronization cycle has ended

I'm uncertain about the appropriate title for this inquiry, so please correct me if I am mistaken. Suppose that upon page refresh (load), I require an animated scroll to an anchor based on the current location's hash (I am aware of ngAnchorScrol ...

My AJAX requests do not include any custom headers being sent

I'm facing an issue with making an AJAX request from my client to my NodeJS/ExpressJS backend. After firing the request, my backend successfully receives it but fails to recognize the custom headers provided. For example: $.ajax({ type: " ...

Having trouble loading a React component

I've been working on breaking down modules from a monolithic React project to store them separately in my npm registry. However, I'm encountering issues with exporting and importing them correctly. Previously, I was using the following code: con ...

Stylized search input inspired by Pinterest with a bubbly design

When it comes to my search bar, I want the user's entered keywords to be displayed within a bubble that has a delete option when they press space to add another keyword. This functionality is similar to what Pinterest does with their search bar, as de ...

How can we fix the null parameters being received by the ModelPage function?

I've been learning how to successfully pass values to a Post method using AJAX in .NET Core 6 Razor Pages, but I am encountering some difficulties. Below are the relevant codes: Front end: function calculateSalary() { var dropdown = document.get ...

Enhancing Symfony's performance through optimized Ajax response time

When using Symfony2, I am experiencing differences in loading times for AJAX requests between development and production environments. In development, it takes 1 second to load, while in production it only takes 500 milliseconds for a simple call: Here is ...

What is the best way to incorporate a fadeIn animation to a text in jQuery?

Looking for help with appending the fadeIn() jQuery function to a string that increments an integer within a paragraph. I attempted concatenation without success. Any recommendations on how to solve this issue? $p.text(parseInt($p.text(),10) + 1); ...

What is causing this particular area to remain unaffected by the blur effect?

issue I followed a tutorial to create a mouse trailer from this video - https://www.youtube.com/watch?v=kySGqoU7X-s. However, when I tried adding text and other elements inside a div, the blur effect just didn't show up. I attempted using z-index but ...

Navigate to the AngularJS documentation and locate the section on monitoring data changes after a dropdown selection

Just starting out with AngularJS and Stack Overflow, so I hope I am asking this question correctly. I am working on a single-page application with editable text inputs. Two select drop-downs are used to control which data is displayed - one for time perio ...