Guide to converting a variable name into a string in JavaScript

I'm working on creating a handy wrapper for console logging in JavaScript, and I want to display the variables passed in along with their values.

Is there a way to convert a variable name into a string in JavaScript?

Answer №1

If you're looking for a similar solution, here's one suggestion:

function Print(logData)
{
    console.print(input name, logData);
}

Unfortunately, achieving this exact functionality may not be possible:

As an alternative approach, you could try something like

console.log({ "specified variable": specifiedValue});

This method transforms the input into an object that includes the desired variable name for logging purposes. It requires more keystrokes but can enhance readability in the console output.

Answer №2

It is certainly a possibility. Let me explain how it can be done:

let dynamicVariable = '42'; // The actual variable
let referenceName = 'dynamicVariable'; // The name of the variable stored in another variable

Instead of passing the actual variable, pass around the referenceName. When you need to access the value of the variable, you can simply use:

console.log(referenceName, ' : ', window[referenceName]); // Outputs, dynamicVariable : 42

I suggest finding an alternative method if possible. :)

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

The dimensions of HTML elements can vary when viewed in browser developer tools versus retrieving their size using JavaScript

In my Javascript file, I have implemented various methods to determine the height of a fixed header on my website and use that value as padding for the main content. However, I am encountering inconsistencies in the results obtained through different metho ...

What is the best method for displaying multiple slices within an SVG circle?

I'm currently working on a project involving a reactJS application. The goal is to display an svg circle that, when clicked, divides into n equal slices. I have successfully generated the individual slices with the following code: renderSlices = () ...

Issue with moment library causing date to appear incorrect on 31st day

I am experiencing an issue when finding the difference between 2 dates in years. Specifically, when I choose the 31st date, it returns an invalid result as NaN. However, with other dates, the calculation displays the correct outcome. const selectedValu ...

jQuery provides the ability to execute multiple functions simultaneously

Here is the JavaScript code snippet I am working with: function RHL(a,b,c) { return rx.removeClass(a).addClass(b); return rhpfc.html(parseInt( rhpfc.html() ) -1 ); } I am struggling a bit with the formatting and syntax. My goal is to combine ...

What issues are hindering the successful export of my Vue component packaged with npm?

I created a small local npm package called fomantic-ui-vue with the following main js file: import Vue from 'vue' // Import vue component import button from './elements/button/button.vue' import buttonGroup from './elements/butt ...

Connect ngOptions to an array beyond the current scope

Can the ngOptions be bound to a value that is not within the $scope? I have enums that will be generated as JavaScript code. These enums are not currently part of "the angular domain", but I want to bind an ngOptions to one of the arrays without manually ...

Shift attention away from AG-Grid

AG Grid is being used on a website and when a user clicks a cell, it becomes focused with a blue outline. I am looking to remove this focus when the user clicks on specific elements on the site, but I am unsure of how to achieve this. Is there a method or ...

Adjusting table rows in Vuejs based on different screen sizes

I am working with a table that has two <tr> tags in its first row (I know, it's not ideal but it has to be this way): First tag: <tr class="abc" @click="expanFunc"> Second tag: <tr class="abc"> My goal is to display only the ...

Extract precise information from a database using node.js

Hey there, I have set up routes for fetching data from my database. Here's what I have so far: router.get('/', expressAsyncHandler(async (req,res) => { const products = await Product.find({}) res.json(products) ...

Encountering MySQL PUT and DELETE Error 500 when using Express and Axios

An unexpected project has landed in my lap, pieced together using tools that are unfamiliar to me. It utilizes Express, Bookshelf, and Axios to connect with a MySQL database. While the GET and PUT routes in Express seem to be functioning properly, issues a ...

Accessing the URL causes malfunctioning of the dynamic routing in Angular 2

I am currently working on implementing dynamic routing functionality in my Angular application. So far, I have successfully achieved the following functionalities: Addition of routing to an existing angular component based on user input Removal of routin ...

Angular directive to delete the last character when a change is made via ngModel

I have 2 input fields where I enter a value and concatenate them into a new one. Here is the HTML code: <div class="form-group"> <label>{{l("FirstName")}}</label> <input #firstNameInput="ngMode ...

Optimal method for storing large arrays of numbers in localStorage using JavaScript

*"Efficient" in this context refers to smaller size (to reduce IO waiting time) and fast retrieval/deserialization times. Storing times are less important in this scenario. I need to store multiple arrays of integers in the browser's localStorage, ea ...

phpHTML: Form to update password with verification of current password

How can I implement a function in my form to ask for the current password before allowing users to change their password in the database? Code snippet to update the database: $result = mysqli_query($con,"SELECT * FROM admin"); if ($row = mysqli_fetch ...

Here is an example of how to use a script tag to check the value of a select tag in HTML:

Hi there! I'm working on a piece of code where I need to retrieve the selected value from a dropdown menu in an HTML select tag and display it in the element with the id='h1' at the bottom. The script tag is already included within the head ...

Error: Attempting to access the 'toString' property of an undefined object is not permitted (apex-charts)

While working on a personal project, I considered using apexcharts. However, an error shown in the image kept popping up. It seemed to disappear when I set the width and height properties in the Chart component or when the site was in production. Currently ...

Storing data to database using Ajax technology

I am facing a situation where I need to send a large amount of text to the server using ajax and PHP. Each text is added by clicking on an add button. To minimize round trips, I am considering adding a "save all" button so that I can store everything local ...

Issue with constructor including an interface

I'm facing an issue with a typescript class that has an interface implemented in the constructor parameter: interface responseObject { a: string; b: boolean; c?: boolean; } class x { a: string; b: boolean; ...

Resetting the value of an object property

My query concerns a provider: AdviceList.provider('$adviceList',function(){ this.$get = function ($rootScope,$document,$compile,$http,$purr){ function AdviceList(){ $http.post('../sys/core/fetchTreatments.php'). ...

Sending table data with files or input string data to the server in .NET ASPX web forms is not allowed

When the add button is clicked, the product type, name, and file are added to the table. The variables are declared globally. document.getElementById("addBtn").addEventListener("click", function () { var entryExists = false; var documentName = doc ...