When using JavaScript, the dash will trigger a ReferenceError

When working with JavaScript...

if (eval('typeof admin_post_css_theme_dark-moon)=='function')) {/**/}

...an error message is triggered:

Error: ReferenceError: moon is not defined

This issue seems to be linked to the dash in the theme name, as themes without dashes do not cause any errors...

if (eval('typeof admin_post_css_theme_silver)=='function')) {/**/}

...do not result in any errors.

So why does the dash between 'dark' and 'moon' lead to this error?


Edit: It is recommended that those facing this issue should consider using camelCase or a similar naming convention. Personally, I use a 'name' and a 'base'. The 'base' is a URL-friendly version of the 'name', which may contain characters that are not URL-friendly. For example, 'My Example' and 'my-example' or 'my_example'.

http://en.wikipedia.org/wiki/CamelCase

Answer №1

Unlike JavaScript variable names, object properties are allowed to contain dashes. For example, you can define object properties like this:

var colors = {
  'background-color': '#ffffff',
  'text-color': '#000000'
};

if (typeof colors['text-color'] === 'string') {
  /**/
}

Answer №2

Due to the fact that '-' is not a valid identifier in JavaScript, as it represents the minus sign. Your eval function is essentially attempting to determine the typeof the expression admin_post_css_theme_dark minus moon. In JavaScript, valid identifiers (such as variable, function, or object names) include [A-Za-z0-9_$] but cannot begin with a number (please note that this is a regex and the hyphens indicate range, from a to z, for clarity).

My approach to this issue would be: how were you expecting admin_post_css_theme_dark-moon to be defined? You anticipate it being defined somewhere in the code, in order to then test if it's a function.

But achieving this would be entirely impossible.

var admin_post_css_theme_dark-moon = function(){...};

//or

admin_post_css_theme_dark-moon = function(){...};

However, it can be done like this.

window['admin_post_css_theme_dark-moon'] = function(){...};

Or better yet, utilize your own object.

var Themes = {};
Themes['admin_post_css_theme_dark-moon'] = function(){...};

//or

var Themes = {
    'admin_post_css_theme_dark-moon' : function(){...};
}

When referencing object properties with string indexes (inside [] as a string), they are not restricted by identifier rules.

Then of course, your eval function would need to be adjusted as well.

Something along the lines of:

if (eval("typeof window['admin_post_css_theme_dark-moon']")=='function')) {/**/}

//or

if (eval("typeof Themes['admin_post_css_theme_dark-moon']")=='function')) {/**/}

Take note of alternating " and ' so there's no need for escaping characters.

Answer №3

There was a modification...

eval('typeof '+my_object)=='function')

...which now reads as follows:

eval('typeof \''+my_object+'\'')=='function')

I didn't get the opportunity to make this change earlier to improve clarity. If you found this answer helpful, be sure to also check out responses from OJay and sabof as they provide valuable insights.

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

Sending information to Firebase using Angular 4

Utilizing Angular 4 in combination with AngularFire, I have successfully implemented a data transfer to Firebase. The specific data that I am looking to retrieve includes: name, country, zip-code paired with email and password details. Following the upda ...

How to invoke a Struts 2 action synchronously using JavaScript

I've been attempting to use JavaScript to make a synchronous call to a Struts 2 action. Despite finding multiple examples, none of them have worked for me. The only method that has worked so far is making an asynchronous call like this: function togg ...

The Angular.js resource REST request encountered a TypeError due to a function being undefined

My goal is to update data using a REST call. I have already made a GET request to populate the form, and upon clicking the update button, I intend to initiate a PUT call. However, instead of successfully executing the PUT call, I encounter a Type Error. B ...

What is the best way to prevent the need for a custom script for every button in dataTables?

After writing a customized script that is triggered when a specific button in dataTable is clicked, here's what it looks like: buttons : [ { extend : 'copyHtml5'}, { extend ...

inserting information into HTML document

I've noticed that this particular method hasn't been addressed yet due to the document.GetElementsByClassName I'm using, but for some reason it's not working. My goal is to add a specific value (a string) to the page. I have located an ...

Is there an issue with the precedence of jison rules?

I've been stuck for hours trying to solve what seems like a simple problem but I just can't figure it out :/ I'm working on defining a small javascript-like language in jison. The issue I'm facing is that both the Parameter rule and th ...

The latest iteration of three.js appears to disrupt how light is reflected on meshes

After upgrading from three.js version r110 to r124 for the new features, I noticed a significant change in the way my meshes reflect light. Suddenly, everything looks different and it's quite disappointing! ...

"Exploring the Differences between JavaScript, AJAX, and Servlet for String

I am attempting to compare a string that is received from a servlet. The servlet page returns the following: out.println("pass"); In JavaScript: function Check() { if (ajax.responseText === "pass") { document.getElementById("pass").innerHTML = "This is ...

The publish-subscribe feature appears to be ineffective

Recently starting with meteor, I learned about the importance of removing autopublish. So, I decided to publish and subscribe to a collection in order to retrieve two different sets of values. Here is the code on my meteor side: Meteor.publish('chann ...

swap out a method within a publicly available npm module

Currently, I am using an API wrapper package that utilizes the request module for making API requests. While this setup works well in most cases, I am facing a situation where I need to use this package in a node-webkit environment and replace the request ...

Steps for Including a Required AMP HTML Attribute in an HTML Tag

Currently working on my website with Gatsby and would like to classify it as an AMP website. What's the best way to include the required AMP attribute in the <html> tag? ...

Organizing your web application directories with AngularJS and Node.js

As I dive into the world of learning node.js and angularjs, I find myself struggling with how to best organize and structure my folders and their contents. Despite coming across some existing questions on this topic, none have provided a solution that trul ...

What is the best way to allow my limit to be as greedy as possible?

I'm facing an issue with the code below where it currently only matches MN. How can I modify it to also match KDMN? var str = ' New York Stock Exchange (NYSE) under the symbol "KDMN."'; var patt = new RegExp("symbol.+([ ...

Learning how to implement react-toastify promises with axios is a valuable skill to have

// I am trying to implement toastify promises to show a spinner while fetching data and then display a success or failed message // However, I am encountering an error in the code below const fetchData = () => { axios .get("https://restc ...

I am looking for a setup where a checkbox triggers the opening of the next accordion

I am encountering a problem with the bootstrap accordion feature. I am looking to have the first accordion nested inside a checkbox, so that when the checkbox is clicked, the next accordion automatically opens. If the checkbox is not clicked, the next ac ...

The code threw an error stating: "Error: Unable to set a new value to the unalterable property 'children' of the object '#<Object>'"

Encountering internal server error in Next.js build with Docker when reloading all routes with getServerSideProps react: "17.0.2" next: "^11.1.2" Local setup and deployment without Docker works fine, but with Docker implementation, reloading pages leads ...

Exploring how to use React with a select component featuring objects

Hello, I am new to working with React and I have a question regarding the select component of Material UI. Here's my situation: I am creating functionality for creating and editing a User object. This User object has a primary key and some data, incl ...

The world of coding comes alive with Quartz Composer JavaScript

Seeking assistance as I navigate through a challenging project. Any help would be greatly appreciated. Thanks in advance! I have a Quartz Composition where I aim to incorporate a Streetview from Google Maps and control the navigation, but I'm unsure ...

Sharing controller methods in Angular.js is a key aspect of enhancing

In my current project, I originally used Knockout for the CMS functionality, but decided to switch to Angular because I preferred its features. One of the key sections in the CMS is dedicated to 'Users', featuring a table where headers can be cli ...

Updating language settings on-the-fly in a Vue application does not automatically refresh the translated content displayed on the website

My Vue app is quite large, built with Vuetify, and I recently integrated vue-i18n into it. The json translation files are set up correctly, and the $t() calls work fine in my components and other .js files. However, I'm struggling to change the locale ...