What is the proper way to declare a JavaScript variable using a hyphen symbol?

When it comes to evaluating a string like employee-count = 3, my main issue arises when dealing with variables that may not have a standard naming convention. While valid variable names pose no challenge, identifiers such as employee-count leave me slightly perplexed.

Below is an excerpt of my approach for regular variable names:

function evalWithObject(expression, object) {
  _.each(object, (value, key) => {
    eval(`var ${key} = value`);
  });

  return eval(expression.replace('=', '==='));
}

I am exploring solutions where I can define a variable within the current scope using object notation. For instance, while I can easily execute object['employee-count'] = true, the process becomes trickier in scenarios involving unconventional variable names.

Any suggestions on how to overcome this obstacle?

Answer №1

In the realm of variable names, using a hyphen is generally not accepted due to syntax rules. However, there might be a clever workaround available. One approach is to substitute hyphens with underscores (for example) and utilize eval within the global scope.

// To create a variable in the global space, you can make an indirect eval call
var geval = window.execScript || eval; 
function evalWithObject(expression, object) {
  for (var key in object) {
    if (object.hasOwnProperty(key)) {        
        value = object[key];
        key = key.replace('-', '_');        
        geval('var ' + key + ' = ' + value);
        // OR
        // eval.call(null, 'var ' + key + ' = ' + value)
    }
  }
  return geval(expression.replace('=', '==='));
  // OR
  // return eval.call(null, expression.replace('=', '==='));
}

// It's important to adjust your expressions accordingly; replace key employee-count with employee_count 
evalWithObject("employee_count = 5 ? console.log('Yes')  : console.log('No') " , {"employee-count": 5});

// Display the variable
console.log(window['employee_count']);

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

What is the best way to retrieve a promise from several promises?

Every time I check the console, I see the following: teamsUpdated2 addUserToProjects deleteUserFromProjects However, they should be displayed in a different order. var result = teamService.addOrDeleteUser(userId, newTeams, deleteTeams); result.then(fun ...

I have successfully managed to populate the Google Apps Script listbox based on the previous listbox selection for two options, but unfortunately, I am encountering issues

Struggling to set up 3 list boxes that populate based on each other? At the moment, I have one list box fetching data from a spreadsheet. Could someone assist me in configuring it so that the second list box populates based on the first, and a third list b ...

A guide to removing functions from the render method

Greetings! Currently, I am in the process of creating a simple webpage that utilizes a map function to display all details to the user. Some fellow developers have advised me to remove my functions from the render method, as it continuously renders unneces ...

Is there a term similar to "Rise above the Rest" in the world of Web Development?

Hey, I've encountered a new issue right now. Currently, I have two elements that are fixed to the top and bottom of the page. However, the elements in between them are overlapping the top element. Even though I tried keeping both elements fixed, th ...

Checking the parameters passed to a function in Typescript: A step-by-step guide

Currently, I am working with Typescript and then transpiling my TS code into JavaScript. However, I have encountered an issue that I am struggling to resolve. The error message I am facing is as follows: Error Found in TypeScript on Line:2 - error TS230 ...

What is the process for implementing a custom error when compiling Sass code with node-sass?

When using node-sass to compile my sass code, I am curious about the possibilities during the compilation process. To clarify, I am interested in creating custom rules and generating specific errors under certain conditions while compiling. ...

Implementing Bootstrap in Angular 2 using vanilla JavaScript/ES6: A step-by-step guide

Currently, I am in the process of developing an Angular 2 application without TypeScript and facing difficulties with bootstrapping it as I cannot find any relevant examples. My app, which does not include the bootstrap() function, starts off like this: ...

What is the process for inserting a new item into a mongoose array?

I'm currently developing a confidential web application. Below is the layout I've created for the user. const itemsSchema = { name: String } const userSchema = new mongoose.Schema({ username: String, email: String, password: String, M ...

Boost Engagement with the jQuery PHP MySQL Like Feature

Seeking assistance in creating a like button with PHP, MySQL, and jQuery. I'm encountering an error but unable to pinpoint its source. Can anyone provide guidance? The project involves two pages: index.php & callback.php INDEX $k = 1; //POST ID $n ...

MongoDB and Node.js encounter unexpected outcomes due to undefined variables

I am trying to retrieve data from my collection called students within the pool database in MongoDB. Despite having a successful connection to the database, when I use console.log(result.lastname), it returns undefined. Below is an excerpt from my server ...

Performing String formatting in JavaScript using an array

I've been utilizing the stringformat library to format strings in my node.js applications. var stringFormat = require('stringformat'); stringFormat.extendString(); In my current project, I'm attempting to pass an array of parameters a ...

Is there a way to verify the existence of an element based on its class name?

In the title of my question, I mentioned that my element lacks an id attribute. So how can I determine if it exists or not? Here is the HTML code: <div class="classname">something</div> Note1: If there was an id attribute like this: var el ...

Is there a way to adjust the quantity of items in the shopping cart without the need to reload the webpage?

Currently, I am working on a test project using React & Redux. The project involves implementing a basket feature where I receive an array of products structured like this: products: [ { name: "Product one", count: 1, ...

Encountering an issue of duplicate key error when using multiple v-for loops with various keys

I've encountered an issue while working on a Python application that utilizes Vue.js. A ticket came my way with an error message stating: [Vue warn]: Duplicate keys detected: ''. This may cause an update error. (found in Root) The pro ...

How can I implement conditional rendering with React on a div element?

Is it possible to implement conditional rendering by simply adding the boolean checked isVisible=true onto the div? Will this ensure that it only renders when true? Could there be any potential issues with the component's state changing after renderi ...

Issues with sending an AJAX POST request to a PHP script

Hello, I am trying to send a variable from an AJAX JavaScript file to a PHP file. Here is what I have done so far: var request = createRequest(); var deletenode = node.id; window.alert("nodeid=" + deletenode); var vars = "deletenode ...

Ways to dynamically incorporate input fields into a form

My current project involves managing an Asset Management system for a company with multiple locations. This system has the capability to return unused asset items back to storage. I am faced with the task of returning a large number of items, which requi ...

I am experiencing an issue with my localhost website where the images only display after I open the files in VScode. Is there a way to load the images correctly using app.js?

app.js While working on web development in VScode, I've encountered an issue where the images on my localhost website only appear after opening files like home.pug and contact.pug alongside app.js. Is there a way to make the images load properly witho ...

TS1057: It is required that an async function or method has a return type that can be awaited

There was a recent Github issue reported on March 28th regarding async arrow functions generating faulty code when targeting ES5, resulting in the error message: TS1057: An async function or method must have a valid awaitable return type You can find t ...

Issues arise when utilizing external scripts alongside <Link> components in ReactJS, resulting in them becoming unresponsive

I'm experiencing some difficulties with an external script when using <Link to="/">. The script is included in the main layout file index.js as componentDidMount () { const tripadvisorLeft = document.createElement("script"); tripadvisorLef ...