What is the method for determining the length of a string in JavaScript?

I'm in the process of developing a calculator that can compute the values within a string. To achieve this, I've implemented a Function object, but upon execution of the code, I encounter an issue where I receive a result of 'undefined'. My assumption is that this problem stems from the global scope of the Function object, yet I'm unable to pinpoint the exact error within the function. While passing it a local variable could potentially resolve the issue, I'm facing challenges in figuring out how to implement this solution.

let attachEventListeners = function () {
    screens = document.querySelectorAll("[class=screen]");
    operationsButtons = document.querySelectorAll("[class^=operations_button]");

    initializeAttributes();
    addNumberButtonListeners();
    addOperationsListeners();
    addOtherButtons();
}


function addNumberButtonListeners() {
    numberButtons = document.querySelectorAll("[id^=number]");
    numberButtons.forEach(button => {
        button.addEventListener("click", function () {
            let buttonNumber = button.innerText;
            screens.forEach(screen => {
                screen.numberLast = true;
                if (screen.isDefault) {
                    screen.innerText = buttonNumber;
                    screen.isDefault = false;
                    if (screen.id == "little_screen") {
                        screen.value = screen.innerText;
                    }
                }
                else {
                    screen.innerText += buttonNumber;
                    if (screen.id == "little_screen") {
                        screen.value = screen.innerText;
                    }
                }

            })

        })
    });
}

// Other functions...

attachEventListeners()
// Additional styling and HTML content...

While I understand that using eval() would provide a solution, I am striving to avoid its usage. I have incorporated a console.log statement that displays the value of the string required for calculation each time you attempt a computation by pressing the equals button.

EDIT: After making some modifications, I no longer encounter the 'undefined' output. However, my current challenge lies in only receiving the raw string without performing the actual calculation.

let calculate = function () {
                        screen = document.querySelector("[id=little_screen]");
                        screen.innerText = screen.innerText.slice(0, -1);
                        return screen.innerText;

Answer №1

Typically, executing "untrusted code" is not recommended due to the potential risks involved, which is why the rule "eval is bad" exists. The method of running such untrusted code may vary, so whether you use eval or create "new functions" doesn't really make a difference.

However, in your current application, the only code being executed is what users input by pressing the calculator buttons. Unless this code is shared or there is a way to initialize the app with arbitrary code, the risk of using eval is minimal. The worst scenario would be a user running malicious code on their own computer (assuming limited hacking skills).

If the code somehow persists, it's important to sanitize it before passing it through eval. One approach is to apply a regular expression that removes any characters outside of [^0-9+\-*\/\.]. Characters like +, -, *, /, ., and numbers 0 to 9 pose relatively low harm.

const code = 'alert("bad stuff"); 1+1';
const safeCode = code.replaceAll(/[^0-9+\-*\/\.]/g, '');
console.log(eval(safeCode));
// expected output: 2

When integrating more complex functionalities, like a sqrt() function, the above approach becomes impractical. This leads to the realm of tokenizers, parsers, and interpreters. Parser generators are often used these days to generate parser code based on formal language declarations.

Most generated parsers produce either an "AST" or a "CST" after processing an input string. The difference lies in how closely they resemble the original code. These structures can then be interpreted, compiled, or transpiled for various purposes.

While parser generators automate this process, writing a parser manually is possible. Recursive descent parsers are commonly chosen due to their balance of power and comprehensibility. Crafting Interpreters provides a valuable resource for understanding this domain further.

An example scanner, parser, and interpreter for simple mathematical expressions can be explored here.

The provided console output demonstrates the input string, scanned tokens, parsed tree, and result alongside an evaluation using "eval".

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

Struggling to design a form to incorporate changing weekly elements into a homepage

Hey, I'm looking to simplify my life by creating a form that allows me, as the administrator/creator, to easily update a group of weekly variables from datalists without needing to manually change the code every time. <form method="post" action= ...

Creating JEST unit tests for a basic functionality

Here is the React code I have written: getDetails: function () { var apiUrl = ConfigStore.get('api') request .get(apiUrl) .set('X-Auth-Token', AuthStore.jwt) .set('Accept&apo ...

Guide to incorporating eslint with Next.js in a project that already has an eslint configuration

I recently created a new next.js project within my existing Node.js project, which already has an eslint config set up. Here's how the folder structure looks now: ...

At what point does the browser begin fetching the background images specified in a stylesheet?

Are images mentioned in a valid CSS declaration with a background-image value downloaded when the stylesheet is parsed or when the declaration is applied on a page? In simpler terms, do I need to download all background images listed in my stylesheet even ...

Equal-height list items in a multi-column unordered list

A multi-column unordered list has been created. Below is the HTML code: <ul> <li>Antelope</li> <li>Bison</li> <li>Camel</li> <li>Deer</li> <li>Eland</li> <li>Gazell ...

Aligning a bootstrap button group at the center of a container

Looking for suggestions on how to center a Bootstrap button group (btn-group) within an element? For instance, consider the following structure: <div id='toolbar'> <div class="btn-group"> <button type="button" class="b ...

The Collada model in Three.js appeared completely dark until a mouse movement brought in some light

Recently, I've run into a peculiar issue while trying to display a collada model in three.js. It appears that there may be an error in the script logic, but I'm having trouble pinpointing it. The problem is that when the page first loads, the Col ...

Overflowing goodness: Bootstrap 4 row spills beyond container boundaries

After deciding to experiment with Bootstrap, I chose version 4 to work with. As I started structuring the template, I encountered an issue where the main content row extended beyond the bounds of the container div, unlike the other rows on the page. My at ...

What is the best way to determine the number of dimensions in a JavaScript array?

Take a look at this array and its corresponding expected output: In Javascript, is it possible to dynamically determine how many levels there are in the array ary? var ary = ["a","b",["c","d"],"e",["f","g",["h","i"],"j"]]; Output: 3 var ary = ["a","b",[" ...

Utilizing Mysql Joins with parameterized queries in Node.js: A Comprehensive Guide

Currently, I am utilizing Node.js and Express.js for my project. In particular, I am incorporating the "mysql2 library" into my development process. My current task involves concatenating and joining queries with parameters in a secure manner. How can I ...

When using a CSS background image in ReactJS, a white space may appear at the bottom of the window

Currently, I am working on creating a background for a React website and implementing it in the div above component. My purpose is to have this background only appear on specific components and not throughout the entire website. However, I am encountering ...

Encountering problems when transforming Next.js server components into client components

I've been working on a blog site using next.js. Initially, I had a home page that was a server component, but I wanted to convert it into a client component to add interactivity like pagination. However, after converting the code to a client componen ...

Storing user credentials in Firestore after registration - best practices

Hi, I need some assistance with storing user credentials in Firestore after they sign up. Unfortunately, I keep encountering the following error: Invalid collection reference. Collection references must have an odd number of segments, but userDatabase/QMJ ...

Why is the session variable in PHP failing to store the value?

Could you assist me with the following PHP code snippet? I'm trying to ensure that when the update function is called, the session variable 't' increments its value. However, every time I run the code, the output remains at Value: 1. What ad ...

What is the best way to iterate through an array of objects in React and JavaScript, adding a new property to each object in order to generate a new array

Greetings, I am currently dealing with an array of objects structured as follows: const arr_obj = [ { children: [{}], type: "type1", updated: "somevalue", }, { children: [{}], type: ...

Avoid the problem of animations triggering twice when clicking

Hey there, I am facing an issue with my slider. If you could take a look at this website , you will notice that after clicking on the arrows, the slider behaves asynchronously. It changes speed rapidly at times and then slows down, repeating this pattern ...

Can we set a restriction on the maximum number of children a particular div can contain?

I'm trying to find a way to restrict the number of children in a div. The concept is that there is a selected commands div where you can drag and drop available commands (essentially buttons) from another div called available commands. However, I wan ...

What methods can be used to prevent accessing 'res' after the resolution of getServerSideProps?

While working on my nextJS application, I encountered an error in the page file: warn - You should not access 'res' after getServerSideProps resolves. Read more: https://nextjs.org/docs/messages/gssp-no-mutating-res I tried reading the provided ...

Dynamic parameters can be passed in Rails using the link_to method

Feeling a bit stuck, maybe this is just a simple question. I have a sort button that I need to use to organize my list of questions. To do this, I create a link_to like this: <%= link_to xx_path(:is_sort => true, :remote=> true , :method=> :p ...

Could someone explain to me why searchQuery.value is coming up as undefined?

Within my development task, I am endeavoring to create a functional search icon on the header bar that allows users to input Pokémon names for searching purposes. Despite my efforts, I am consistently facing a console error message suggesting "searchQu ...