Utilizing Mathematical Calculations Across Multiple JavaScript Functions

Just dipping my toes into the Javascript realm and attempting to crack this task my instructor assigned. Here's what he expects from us:

  1. Create a function to kickstart the program. Name it start()

  2. Inside the start() function, invoke a function named getValue()

  3. The getValue() function should retrieve a number from the user for squaring.

  4. Add another function inside the start() function called makeSquare()

  5. The makeSquare() function will square the user-provided number obtained in the getValue() function.

  6. Make sure to display the squared result within the makeSquare() function.

Here's what I managed to put together so far:

function start() {

    getValue();
    getSquare();
}

function getValue() {

    var num = prompt("Please enter a number")
}

function getSquare() {

    var squaredNum = Math.pow(num)
    document.write(squaredNum)
}

start()

This activity doesn't involve any HTML tags, just grappling with getting the prompt box to work. Any thoughts on whether I'm handling variables correctly?

Answer №1

You were almost there, but it appears that you may need a better grasp on scoping and how to correctly utilize the pow function.

Understanding Math.pow:

Math.pow requires two parameters: the base and the exponent. In your example, only the base was provided. This can result in issues as the function will return undefined and assign it to b. Here is the correct way to square a number using this function:

Math.pow(a, 2);

Scope Rules:

Each function has its own scope. While you can access variables and functions created outside the function from inside it, you cannot reach those created within another function. Consider the following example:

var c = 5;

function foo() {
   var a = c;
}

var b = a; // This will not work as 'a' is no longer accessible after the function ends.

Functions can be seen as private entities, except for the ability to return values using the return keyword. The value next to this keyword becomes the function's return value:

function foo() {
    return 5;
}

var a = foo(); // Now 'a' equals 5

The error in your code lies in attempting to access

// ...
var b = Math.pow(a)

Can you spot the mistake now? Since 'a' is defined within the function, it cannot be accessed outside of it.

To fix this issue, the code should be revised as follows (Remember to always use semicolons where necessary):

function start() {
    getSquare();
}

function getValue() {
    var a = prompt("Number please");
    return a;
}

function getSquare() {
    var b = Math.pow(getValue(), 2);
    document.write(b);
}

start();

Answer №2

Since this is a homework assignment, I won't provide the answer outright but instead offer some hints.

In JavaScript, variables are scoped within functions. This means that a variable like var a declared inside the function getValue is only accessible within that function.

You have the ability to use return to send back a value from a function.

Remember, functions are considered first-class objects in JavaScript. This allows you to pass them as arguments to other functions and ultimately call them within those functions.

Answer №3

Is my utilization of variables causing issues?

Absolutely, that appears to be the root of your troubles. Variables in various programming languages are bound by a specific scope, dictating where they can be accessed. In this scenario, a and b act as local variables within the functions getValue() and makeSquare() respectively. This means their accessibility is confined to the function they belong to.

In general, this practice has its benefits. Utilizing restricted scopes for your variables enhances the clarity of data transmission throughout your program. It's preferable to utilize return values and parameters for passing data among functions instead of resorting to global variables:

function commence() {
    var a = getValue();
    makeSquare(a);
}

// Obtain a value inputted by the user
function getValue() {
    return prompt("Please enter a number")
}

// Display the square of the provided `a` parameter within the document
function makeSquare(a) {
    var b = Math.pow(a)
    document.write(b)
}

Answer №4

  1. Ensure that your getValue() function returns the value before passing it to the getSquare() function.

  2. It is advisable to terminate each line with a ;.

  3. To convert user input into a number, consider using parseFloat(string).

  4. When using Math.pow, remember to pass 2 as the second argument to calculate the square.

I have included explanatory comments in your code:

function start() {
    // Capture the returned value
    var value = getValue();
    // Pass the value to the square-function
    getSquare(value);
}

function getValue() {
    // Convert user input into a number and return    
    return parseFloat(prompt("Enter a number"));
}

// Allow the square-function to accept the user input
function getSquare(a) {  
    // Utilize Math.pow with a power of 2 as the second argument
    var b = Math.pow(a, 2);
    document.write(b);
}

start();

An alternative approach

In JavaScript, variable scope is determined by functions. Declaring a variable with var restricts its access to that function and its child functions. Without var or at a global level, the variable becomes accessible globally across the page.

You could make the variable a in getValue() global by omitting the var keyword, allowing it to be accessed within getSquare() as attempted in your example.

This practice is not recommended due to namespace pollution and potential conflicts if another script uses a global variable of the same name, leading to unexpected behavior.

Answer №5

Give this a shot.

<script type="type/javascript">
function begin(){
createSquare(obtainValue());
}

function obtainValue(){
return prompt("input a number");
}

function createSquare(b){
var output=Math.pow(b,2);
alert(output);
}
begin();
</script>

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

Troubleshooting issues with applying styles in Vue framework when configured with webpack

I'm facing an issue with setting up the Vue framework using webpack. Specifically, I'm having trouble with styles not being applied when included in the <style> tag within single file components. Despite following several tutorials on this ...

Images not showing in Vue.js

I have been working on setting up a carousel using bootstrap-vue. It is being generated dynamically through an array containing three objects with keys such as id, caption, text, and image path. The issue I am facing now is that while the caption and text ...

Retrieving information from a JSON file using JavaScript

My code snippet looks like this: { "badge_sets":{ "1979-revolution_1":{ "versions":{ "1":{ "image_url":"https://static-cdn.jtvnw.net/badges/v1/7833bb6e-d20d-48ff-a58d-67f ...

Implement a T3 App Redirect in a TRPC middleware for unsigned users

Is there a way to implement a server-side redirect if a user who is signed in has not finished filling out their profile page? const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { if (!ctx.session || !ctx.session.user) { throw new TRPCE ...

appearing like a straightforward process of creating strings in JavaScript

Originally, I thought this task would be easy, but it ended up taking me the entire morning! var insert = '<div class="main_content_half_panel_circle" id="circle_' + c + '"></div><script type="text/javascript">$("#circle_& ...

Activating JavaScript in the browser only when a button is manually clicked, not by default

As I work on my website, which is currently being constructed, I rely heavily on JavaScript. However, a concern of mine is the potential for failure if a user has JavaScript disabled on their client side system. I understand that it is not possible to pro ...

React- Struggling to modify state from child component using function declared within a parent component

This is my main component: import React, {useState} from 'react'; import SearchBar from '../components/SearchBar'; import WeatherDisplay from '../components/WeatherDisplay'; import LocationInfo from '../components/Locat ...

The behavior of input types disabled and readonly varies when combined with a hyperlink (a href

In the code snippet below, I am trying to disable and enable a calendar clickable icon. <p> <label> <input type="text" name="date18" id="date18" value="01/01/2012" style="width:75px;" disabled/> </label> ...

Troubleshooting problems with the width of a Bootstrap navbar

I'm encountering a frustrating issue with my bootstrap menu. When I include the "navbar Form" in the menu, the width of the menu extends beyond the screen width in mobile mode (when resizing the browser window or viewing on a mobile device). Interesti ...

Obtaining a String from a Nested Array through Nested Iterations

As someone who is just starting out with coding, I am currently focused on practicing loops and arrays. One of my exercises involves working with an array that contains multiple sub arrays, each of them consisting of pairs of strings. My goal is to extract ...

Permuting sentences to create intricate anagrams

I am faced with a task of creating the correct phrase for a sentence anagram using an array of nearly 2700 strings. The list consists of almost 100k words that could potentially fit. My goal is to combine these words in groups of 1, 2, and 3 words togethe ...

How can the @blur event be added to the vue-bootstrap-typeahead in Nuxt/Vue application?

I am facing an issue where I want to trigger a function upon leaving an input field. The input in question is set up using vue-bootstrap-typeahead. Upon inspecting the DOM, I found that the structure of the input element looks like this: <div id="m ...

After running the command "npx/npm create-react-app hello" to create a react app, I received the following message

Whenever I try to execute this command for creating a React app: C:\WINDOWS\system32> npm i create-react-app -g hello I receive the following message in my cmd prompt: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf ...

Cart Quantity Can Only Be Updated Once Using Ajax

I am currently facing an issue with my page that allows users to increase and decrease the quantity of a product in their cart before proceeding to the checkout confirmation page. I am using Ajax for this functionality, where the backend manipulates the qu ...

How to prevent v-menu from overlapping a navbar in Vue.js

Exploring the examples on the main page of Vuetify, we come across the v-menu component showcased in detail. Check it out here: https://vuetifyjs.com/en/components/menus/#accessibility If you activate any of the buttons to open the v-menu and then scroll ...

The image slider script I've built is functioning perfectly in Codepen, but unfortunately, it's not working as

My image slider called Orbit is functioning properly on Codepen.io, however when I try to run the exact same code on Plunker, it doesn't work at all. <ul class="slider" data-orbit> <li> <img src="http://foundation.zurb.com/docs/a ...

What is the best way to obtain root access and utilize disk usage (du) within the main process of Electron?

In the process of developing a macOS application with the help of Electron, I encountered an issue. Attempting to execute the following command from the main process using ipcMain and NodeJS's exec: // Navigating to a directory and utilizing disk us ...

Having issues with 'direction' in React withStyles causing errors

I am experiencing an issue with my React website where I am using the withStyles feature to apply styles to a material-ui Grid element. Specifically, when attempting to use direction: "column" in the style, I encounter the error message provided below. Th ...

Implementing Node.js Modules Technology

Is it possible to implement a module called 'test' in nodejs that exposes two functions, getter and setter, for accessing and setting its member data? The challenge is ensuring that data set via the setter function from another module, such as & ...

What is the best way to manage two different IDs, one using jQuery and the other using Vue.js?

How can I manage to include a sliding effect for my products using jQuery ID and display items with Vue.js? <script type="text/javascript> $(window).load(function() { $("#flexiselDemo1").flexisel({ ....................... ...