Problem concerning the distinction between local and global scope as well as the presence

I have this code snippet for creating a calculator:

const numbers = document.querySelector('.numbers')
const display = document.querySelector('.display')
const functions = document.querySelector('.functions')
const equalClear = document.querySelector('.equalClear')

numbers.addEventListener('click', e => {
    // adding number to display
   if(e.target.innerHTML == '1'){
       display.innerHTML += '1';
   }else if (e.target.innerHTML == '2'){
       display.innerHTML += '2';
   }else if (e.target.innerHTML == '3'){
    display.innerHTML += '3';
}else if (e.target.innerHTML == '4'){
    display.innerHTML += '4';
}else if (e.target.innerHTML == '5'){
    display.innerHTML += '5';
}else if (e.target.innerHTML == '6'){
    display.innerHTML += '6';
}else if (e.target.innerHTML == '7'){
    display.innerHTML += '7';
}else if (e.target.innerHTML == '8'){
    display.innerHTML += '8';
}else if (e.target.innerHTML == '9'){
    display.innerHTML += '9';
}else if (e.target.innerHTML == '0'){
    display.innerHTML += '0';
}
});

functions.addEventListener('click', e => {
    // selecting a function and displaying it
    if(e.target.innerHTML == 'Add'){
        display.innerHTML += '+';
        functionVal = add();
    } else if(e.target.innerHTML == 'Subtract'){
        display.innerHTML += '-';
        functionVal = subtract();
    } else if(e.target.innerHTML == 'Multiply'){
        display.innerHTML += '*';
        functionVal = multiply()
    } else if(e.target.innerHTML == 'Divide'){
        display.innerHTML += '/';
        functionVal = divide();
    }else{
        display.innerHTML + 'Error'
    }
    numberVal = display.innerText;
    console.log(numberVal, "numberVal");
    console.log(functionVal, "functionVal");
});

equalClear.addEventListener('click', e => {
    if(e.target.innerHTML === 'Clear'){
        display.innerHTML = "";
    } 
    else if(e.target.innerHTML = '='){
    }
})

//calculator functions

function add(variable1, variable2) {
    return variable1 + variable2;
};

function subtract(variable1, variable2) {
    return variable1 - variable2;
}

function multiply(variable1, variable2) {
    return variable1 * variable2;
};

function divide(variable1, variable2) {
    return variable1 / variable2;
}

// operation in calculator

function operate(operator, num1, num2){
   operate = operator, num1, num2;
}

operate(functionVal(numberVal,5))
console.log(operate, "this is an operation");

I am facing issues with calling "functionVal" and "numberVal" within the "operate" function. They are showing as undefined due to local scope. I attempted to give them global scope using "var" but had no success. Any suggestions on how to resolve this would be greatly appreciated.

Another concern is that when I try to log "functionVal" in "functions.AddEventListener," it displays NAN instead of the assigned function value. I expected it to show the actual function defined for "add" upon clicking the corresponding button. Any insights on what could be causing this discrepancy?

Thank you in advance for any assistance!

Best regards, A JavaScript beginner

Answer №1

Initially, it is not advisable to check equality using the === operator for different types:

numbers.addEventListener('click', e => {
    // selecting and adding number to display
    if(e.target.innerHTML == '1'){
        display.innerHTML += '1';
    }else if (e.target.innerHTML == '2'){
        display.innerHTML += '2';
    }else if (e.target.innerHTML == '3'){
        display.innerHTML += '3';
    }else if (e.target.innerHTML == '4'){
        display.innerHTML += '4';
    }else if (e.target.innerHTML == '5'){
        display.innerHTML += '5';
    }else if (e.target.innerHTML == '6'){
        display.innerHTML += '6';
    }else if (e.target.innerHTML == '7'){
        display.innerHTML += '7';
    }else if (e.target.innerHTML == '8'){
        display.innerHTML += '8';
    }else if (e.target.innerHTML == '9'){
        display.innerHTML += '9';
    }else if (e.target.innerHTML == '0'){
        display.innerHTML += '0';
    }
});

A more efficient way would be:

numbers.addEventListener('click', e => { 
    display.innerHTML += e.target.innerHTML;
}

If I understand correctly, `numbers` should be an array of buttons with numbers. Using `querySelector` only returns the first button. You should utilize `querySelectorAll` like this:

const numbersButtons = document.querySelectorAll('.numbers');
// convert to array as we cannot iterate over querySelectorAll result directly
Array.from(numbersButtons).forEach((button,index) => {
    button.addEventListener('click', e => {
        display.innerHTML += e.target.innerHTML;
    }
});

Functions should also be stored in an array for clarity. You can create a map of functions like so:

const functionsMap = {
    '+': add,
    '-': subtract
    //add other functions here
}

You can call them in this manner:

// will return the add function
const targetFunc = functionsMap['+'];
// calling with parameters
targetFunc(1,2);

Executing `functionVal = divide();` does not pass a reference to the function, instead, it executes it, resulting in storing the returned value in `functionVal`, which might be `NaN` if the function was executed without parameters.

It's important to carefully review your code and address any mistakes from the beginning.

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

Table that is sized to fit perfectly within the entire width of the viewport

In my current project, I am developing a reporting feature that allows users to select various elements to include in their report. The number of elements available can change based on the user's preferences, and each element may contain user-generate ...

To trigger a pop-up window displaying a link upon clicking the submit button

I am attempting to create a popup box that displays an application accepted message and a link back to the home page upon clicking the submit button. However, the .popup box is not appearing after validation. This is the content that should be displayed w ...

Save the information from a particular block into a JSON or text file using Node.js

I'm working on a code block in Node.js to scrape information from a URL, and I need help figuring out how to store the data either in a .txt file or create a JSON object from it once I receive the data inside the .then block. import { Builder, By, Key ...

Problem with OnClick function in Firefox

I have implemented the following code in an external JavaScript file: $( document ).ready(function() { var elem='<img class="imgload" src="/common/images/spinLoader/transperent.png">'; $('.imgchange').append(elem); }); $(func ...

The concealment of the container is ineffective when attempting to hide it until all cached images are

My website has a background and a main container. I wanted to hide the container until the entire page had loaded, so I included #cover{opacity:0} at the beginning of the page and $(window).load(function() { $('#cover').css('opacity&apo ...

Showing changes in state in real-time using ReactJS: A quick guide

Hello, I am currently facing an issue while trying to add a comment and display it immediately on the DOM. Whenever I type any word in the form box, it does not appear in the box. Additionally, pressing the enter key does not trigger a POST request. Could ...

Why is my data not being sent with the $http POST request in AngularJS?

using angularjs to fetch data with $http userId = '1'; $http({ url: "php/loadTab.php", method: "POST", data: userId }).success(function(data, status, headers, config) { console.log(data); }).error(function(data, status, headers, config) { } ...

Error: Issue encountered while attempting to download file using express.js res.download

After creating an xlsx file with the help of the json2xlsx npm module, I am utilizing the res.download(file) functionality in express.js to facilitate the download process. For more information, please refer to: Download a file from NodeJS Server using Ex ...

Managing backbone models on the server side and in memory

When I have a backbone model on the server (node.js) and insert data on each route using Express, will that model continue to grow indefinitely? Should I take steps to clear memory when the model has completed its intended purpose? For example: var model ...

What is the best way to navigate to a different page, such as Google, using Node.js?

I need to retrieve a number to store in a short variable, and then search the database for a corresponding shortUrl associated with that number. If a match is found, I want the response to be the full URL, such as www.google.com. For example, if a user ty ...

Adjust the clarity of the elements within my HTML document

I have been working on creating a login page that will appear in front of the main webpage. Through my online research, I discovered a technique to blur the main webpage background until the user logs in. Below is the code snippet: HTML: <div id="logi ...

Please be cautious not to directly change the state. Remember to always use setState() in ReactJS to update

Looking for a way to update states in React.js using the "=" sign instead of the setState method? Check out the code below for an example where I'm trying to update the state of an object within another object. However, I'm encountering an error ...

Should I incorporate PHP/HTML code or opt for using a function instead?

I'm currently exploring the most effective method for integrating HTML/PHP code into various pages, such as headers, footers, and other repetitive sections. Would it be better to use include_once(php file) (even if it's used multiple times on a ...

URL JSON data will not display markers

I am currently working on a map that fetches data from the police.uk API by allowing users to drag and drop a dot on the map to display crimes within a 1-mile radius. However, I'm facing an issue when trying to implement geocoding functionality by tak ...

Ember.js encountering an "Access-Control-Allow-Origin" error with Ajax

Seeking opinions on how to resolve the Access-Control-Allow-Origin issue in this simple Ajax code snippet. Attempts to define the Ember "Access-Control-Allow-Origin": "* " have been unsuccessful. Has anyone with a similar problem found a solution? The URL ...

Tips on extracting information from a table containing a mix of HTML elements

I'm currently working on a table that contains a mix of plain text, input textboxes, selects, and spans. My goal is to loop through each row of the table and extract the value from each cell. All <tr> in my table have a specific css class assign ...

Assistance from ChromeDriver for clicking in situations where zoom level is not at 100%

While using chromedriver on Windows, I encountered an issue where the browser's zoom level impacted the functionality of element.click(). If the zoom level was anything other than 100%, the click command would target a different element instead of the ...

Is it possible that MapBoxGL installation with Expo doesn't function properly for web?

I have been working on building an app featuring a map using the MapBoxGL library in Expo. I followed the installation instructions provided by the library, which can be found here. After completing the installation, I proceeded to write the code below to ...

Click event dynamically bound to list items

I have a web application built with Durandal and Knockout. Here is the HTML code snippet: <ul id="header"> </ul> In a JavaScript function, I am dynamically adding a list item as follows: $("#header).append('<li id="btn"><a hre ...

"Transmit the document by utilizing the file ID in the form of

When sending a file from my server, I can easily define the path and it goes through successfully. However, with the node-telegram-bot-api, there is an option to send a document that is already hosted on telegram servers by providing the file_id in the doc ...