What are the steps for utilizing functions with a variable parameter?

I have been working on a small project to practice my javascript skills, but I've run into an error that I can't seem to fix. I've tried researching a solution, but no luck so far. My goal is to create a program that generates silly insults as a joke. It should randomly combine one item from the 'people' array with one from the 'offense' array. Everything was working fine until I tried turning the randomizer into a function. That's when things started going haywire - it would stop after asking for a friend's name and assign 'personGenerator' to 'undefined'. Here is the code I have so far:

<script>
    //this is plonker base

    //create a variable to start the game
    var start = confirm("Are you sure you want to play plonker base alpha?")

    //start and loop the game
    if(start==true){
        //prompt for a friend's name
        var person1 = prompt("Please enter the name of one of your best friends.")
    }

    //create a randomizer function
    var random = function (variable,subject){
        variable = subject[Math.floor(subject.length * Math.random())]
    }

    while(start==true){
        //create 'person' array
        var person = ["You are ","Your mum is ","Your dad is ", "The world is ", (person1 + " is ")]
        var personGenerator
        random(personGenerator,person)

        //create 'offense' array
        var offense = ["an idiot!",
            "a complete psycho!!!",
            "a smelly, worthless piece of junk!",
            "a whale reincarnated that looks like a squirrel!",
            "a dumb pile of dirt that has the misfortune of seeing itself in the mirror once in a while!",
            "a complete and utter plonker!",
            "a dumbo!",
            "a right doofus!!!",
            "a pile of rabbit dung!",
            "an intelligent, good looking king being... Did I mention - it's opposite day!",
            "a bum-faced rat!!!",
            "a fat, lazy oaf!",
            "a blobfish look-alike!!!!!",
            "a lump of toenail jelly!"]
        var offenseGenerator = offense[Math.floor(offense.length * Math.random())]
        //generate and display the insult
        alert(personGenerator + offenseGenerator)
    }
    {
        alert("What a plonker!")
    }
</script>

I am new to javascript so please keep your explanations simple and correct me if I use the wrong terms. Thank you for your help.

Thanks, Reece C.

Answer №1

The script below does not execute properly in JavaScript:

//creates a randomizer function
var random = function (variable, subject){
    variable = subject[Math.floor(subject.length * Math.random())]
}

This code does not update the given variable. Instead, you should return the new random value from the function.

//creates a randomizer function
var random = function (subject){
    return subject[Math.floor(subject.length * Math.random())];
}

Then, when using it:

var personGenerator = random(person);

The reason why your original code is ineffective in JavaScript is because JavaScript does not support true pass by reference, where you can modify what the original variable points to. When you write this:

//creates a randomizer function
var random = function (variable, subject){
    variable = subject[Math.floor(subject.length * Math.random())]
}

random(personGenerator, person);

The variable parameter in your random function will store the contents of the personGenerator variable at the time the function is called. Nonetheless, it will be a distinct variable. So, if you do this:

variable = subject[Math.floor(subject.length * Math.random())]

it only alters the value of the local function argument. It does not alter the value of personGenerator.

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

One can only iterate through the type 'HTMLCollection' by utilizing the '--downlevelIteration' flag or setting a '--target' of 'es2015' or above

I'm currently working on developing a loader for my static grid. I've incorporated the react-shimmer-skeleton package source code, but I'm encountering issues with eslint in strict mode. You can find the respective repository file by followi ...

When I click the button, the page goes blank and keeps loading endlessly

http://jsfiddle.net/iansan5653/7EPjH/17/ <head> <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type="text/javascript"> function chart() { var pressure; ...

Merge two JavaScript functions

I've been attempting to merge two if functions together but I keep encountering errors. Despite trying different methods, I have not been successful in combining them. My goal is to check if the body has a specific class and if it does, I want to unc ...

The mouseenter event in jQuery is failing to trigger

I'm encountering an issue with the mouseenter event on a div section of my webpage. I am attempting to alter the background color of this div when the mouse enters, but it seems to be disregarded. This is the basic HTML code: <div id="services" c ...

extracting an empty value from this variable

When I click on an anchor tag using this operator, the value appears blank. I have multiple divs with the same class, so I used the .each() function, but I can't figure out where I'm going wrong. The desired output is that when I click on one of ...

Having trouble transmitting data with axios between React frontend and Node.js backend

My current challenge involves using axios to communicate with the back-end. The code structure seems to be causing an issue because when I attempt to access req.body in the back-end, it returns undefined. Here is a snippet of my front-end code: const respo ...

turn the cube shape into one with smooth, rounded corners

Does anyone know how to create a cube with rounded corners using three.js? I've heard it's not possible with CSS. Any guidance on how to achieve this? Check out this link for an example /* |------------------------------------------| | MelonHTM ...

Tips for creating a scale animation using HTML5 Canvas

I am currently developing a canvas whiteboard tool and I have reached the stage where I am focusing on implementing the Zoom In and Zoom Out feature. While the functionality is working fine, I would like to enhance it with smooth animations for scaling. H ...

Utilizing JQuery Template to Invoke JavaScript Functions

If I have the following JSON object structure: ITEMS is an array with one element, and FILTER is another array with 3 items in it. Description: "churches with some restrictions" ITEMS: {...} [0]: {...} FILTER: {...} ...

Navigating through a multistep form in AngularJS using UI Router and arrow keys for seamless movement

Is there a way to navigate to the next or previous form step using arrow keys in AngularJS UI Router? The code provided below is currently allowing navigation with previous and next buttons. .config(function($stateProvider, $urlRouterProvider) { $stat ...

Having trouble processing the Firebase snapshot with Node.js

I have a question regarding a snapshot; ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {}) After printing the snapshot with ; console.log(snapshot.val()); This is the output that gets printed; {'-LBHEpgffPTQnxWIT ...

Creating a new route in a Express JS server to specifically handle POST requests

Just starting to learn the ropes of Javascript, and I'm diving into express to create an application that will enable users to craft new recipes, explore existing ones, and view details about each recipe. To get things moving, I've launched my s ...

troubleshooting problems with feathers.JS using the npm start command

After developing two separate feathersJS applications, I encountered a situation where running npm start resulted in two unique types of errors for each app. How can I go about resolving this issue? View image here https://i.stack.imgur.com/RrsGW.pnghtt ...

Experience the latest HTML5 features directly within a Java desktop GUI, with seamless communication through

This Java desktop GUI utilizes a Java-based web services communication layer along with an HTML library to provide powerful charting and interactivity. I am looking to integrate an HTML5 view within the Java GUI. Can someone assist me in managing JavaScri ...

I prefer to avoid generating the document structure while parsing with JSOUP

Utilizing the Jsoup API to parse a section of HTML using the Jsoup.parse() method. However, during parsing, it includes the document structure in the HTML content. For Instance: <p><a href="some link">some link data</a> Some paragraph c ...

Inaccurate audio timestamps in Chrome

I am currently working on a web application that features an audio component sourced from a local .mp3 file lasting approximately 1 hour. I have encountered an issue where, upon clicking the seekbar to jump to a specific point in the audio (e.g., 00:01:00) ...

Guidelines on executing a function after page load in meteor

Currently, I am using cursor.observeChanges to monitor new records inserted in MongoDB and trigger a notification when that happens. The issue I am facing is that these notifications are popping up when my app is loaded for the first time or when I navigat ...

Switch off JavaScript beyond the parent element

Struggling with implementing an event to toggle a div using an element located outside of the parent container. I am attempting to achieve the same functionality by targeting elements beyond the parent structure utilizing a span tag. Any assistance on th ...

Is It Possible to Create Global Variables in PHP?

Looking for assistance in making the variables $courseInfo and $row global, so they can be accessed for displaying row details in the header DIV. I'm unsure how to achieve this. Any guidance would be appreciated. <?php // Get Course ID From ...

Tips for creating a new route within a separate component in React JS without causing the previous one to unmount

I am currently developing a recipe website using React JS and React Router. On the HomePage, I have set up a display of cards, each representing a preview of a recipe. Each card is enclosed within a <Link></link> tag. When one of these cards ...