Challenges with variables

Is there a way to assign local variables to a globally defined function? I am struggling with this concept. Below is an example of some code that I have been working on.

function error(code) {
  var errors = {
    1000: function() {
      return `Troubles with ${product}`
    },
    1001: function() {
      return 'error'
    }
    //And many errors with different variable names...
  }
  alert(errors[code]);
  //it returns error in console :(
}

function check() {
  var product = 'car';
  error(1000)
}
check();

Answer №1

Your code is working fine and does not result in an error in the console. Instead, it alerts a function definition:

function error(code) {
  var errors = {
    1000: function() {
      return `Troubles with ${product}`
    },
    1001: function() {
      return 'error'
    }
    //And many errors with different variable names...
  }
  alert(errors[code]);
  //it returns error in console :(
}

function check() {
  var product = 'car';
  error(1000)
}
check();

However, if you call the function error(1000), it may cause an error because product is not within scope. You should pass it as a parameter to the function. One way to do this is by passing an object with named properties that the template literal can utilize:

function error(code, params) {
  var errors = {
    1000: function(params) {
      return `Troubles with ${params.product}`;
    },
    1001: function() {
      return 'error';
    }
    //And many errors with different variable names...
  }
  alert(errors[code](params));
}

function check() {
  var product = 'car';
  error(1000, {product});
}
check();

I would suggest defining error differently, as there is no need to recreate your errors object and its properties each time you call error. Here's a more efficient implementation:

const error = (() => {
  const errors = {
    1000(params) {
      return `Troubles with ${params.product}`;
    },
    1001() {
      return 'error';
    }
    //And many errors with different variable names...
  };
  return function error(code, params) {
    alert(errors[code](params));
  };
})();

function check() {
  var product = 'car';
  error(1000, {product});
}
check();

Answer №2

It's important to note that the product variable is not accessible within the 1000 function when using closure. The variables in the parent scope are only available within the function where they are declared, not where they are called.

To resolve this issue, you should pass the product as an argument.


function error(code) {
  var errors = {
    1000: function(product) {
      return `Troubles with ${product}`;
    },
    1001: function() {
      return 'error';
    }
    //And many errors with different variable names...
  };
  return errors[code];
}

function check() {
  var product = 'car';
  console.log(error('1000')(product));
}
check();
      

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

Determine in Node.js whether a variable is present in the request object for each page the user visits

Currently, my authentication system utilizes passportjs to define req.user when the user is logged in. As my website expands beyond its current 5 pages, I have been checking for the existence of req.user at the top of each route. Based on whether it exist ...

Guide on duplicating a Select2 element integrated with Django and Python

I am facing an issue where the select element inside a div is not cloning correctly. The Select2 element does not retain the loaded values from the Django code when cloned. Is there a way to clone the div with all the Select2 element values intact? Current ...

Taking out arbitrary raphael shapes from the drawing board

In my current project, I am utilizing raphaeljs and socketIO to create a real-time data display. The canvas features circles that represent nodes, and these circles are stored in an object called nodeStatus, with the format nodeStatus[id].obj where the "id ...

Tips for designing a sophisticated "tag addition" feature

Currently, I am enhancing my website's news system and want to incorporate tags. My goal is to allow users to submit tags that will be added to an array (hidden field) within the form. I aim to add tags individually so they can all be included in the ...

Mastering Node.js: Writing to a Write Stream on the 'finish' Event

I'm currently using Node.js streams to process a text file line by line, apply some transformations, and then generate an SVG file based on the data. However, I am facing an issue where when I try to write the closing tag (</svg>) after all pro ...

Getting parameters from a URL with a React frontend and Express backend: A step-by-step guide

I am currently developing a react application with an express backend. I am in the process of integrating socket io chat functionality into the frontend. Everything is functioning properly, but I am now looking to extract parameters from the URL in order t ...

Enhancing Performance with Web Workers in Angular CLI

Lately, I've been tackling a challenging issue with my Angular app - heavy computation on the client side leading to UI blockage. My solution? Utilizing Web Workers in my Angular CLI project to separate UI tasks into one thread and heavy processing in ...

Issues with select options not functioning correctly in knockout framework

Currently, I am engaged in a project where data is being retrieved from an API. The main task at hand is to create a dropdown list using select binding. In order to do so, I have defined an observable object to hold the selected value within my data model. ...

When the buffer is sent through the socket in NodeJS, the console responds by stating that it is not recognized as a buffer

I've been exploring the implementation of AES encryption in ECB mode and here is the code snippet I'm working with. function encrypt (key, iv, plaintext) { if(algorithm == 'aes-128-ecb') iv = new Buffer(''); var ciphe ...

Leveraging knockout.js to define the width for kendo-ui input wrappers

In the durandal project I'm working on, where JavaScript and HTML are written on separate pages, I encountered an issue with a kendo-combo element. When I initially set the width using the wrapper-input width declaration, it worked perfectly fine. How ...

Child component in Vue is not functioning as expected due to an issue with

I am attempting to modify this code snippet [A] (refer to fiddle at the bottom): <div class="q-uploader-files scroll"> <q-item v-for="file in files" :key="file.name" > <q-progress :percentage="file.__pr ...

Error: User cannot be used as a constructor

When attempting to register a user using a Node.js app and MongoDB, I encountered the following error message: const utente = new Utente({ ||||| TypeError: Utente is not a constructor This is my model file, utente.js: const mongoose = require("mongoose") ...

Navigating through functions and saving outcomes

I need help creating a function that groups JSON elements based on a specific criteria, but I am having trouble with my loop. The goal is to create groups of 12 bottles and return a single JSON list. For example, in this case, the function should extract ...

Guide to establishing a character limit for a textfield using the jquery inputmask plugin

Can you help me with setting a mask that allows users to enter at least 5 digits, and optionally more than five but less than 10? I've tried using this code: $('#codeNumber').inputmask('99999[999999]'); Unfortunately, it's n ...

Vue JS - Issue with data reactivity not being maintained

Currently, I have implemented a pagination indicator that displays the number of results on each page. For instance, page 1 shows '1-5' and page 2 shows '6-10 out of 50 results', and so on. The logic for updating the results seems to b ...

Retrieving information using an ajax request in JavaScript

Although this question may have been asked several times before, I have yet to find a satisfactory answer. I passed a URL in an Ajax call and I am trying to retrieve data from the database through a query in the success method of the Ajax request, but for ...

Ways to add a CSS class to an ID that immediately follows

I've been working on an editable table using the HTML5 attribute contenteditable. Everything was going smoothly until I had an idea to highlight the cell that was just updated by adding a class called alert-danger from Bootstrap. Once a cell is succe ...

Looking for assistance with implementing a jQuery function for an onClick event on

I've been diving into learning jquery and managed to create a basic checkbox feature with a function that allows you to set all options as read-only by checking the "None of the above" button. <html> <body> <form id="diagnos ...

When communicating with the backend in a React application, the data is not being successfully sent using axios. An error message stating "Unsupported protocol

My current setup involves using Express.js as the backend and setting up a proxy to the backend in the package.json file of my React.js project. Initially, I encountered an error when using the fetch method, so I switched to using Axios to resolve this iss ...

Exploring the world of mobile 3D transformations

I'm hoping to find a way to incorporate 3D transformations by utilizing the accelerometer on mobile devices within the following JavaScript code. Any assistance is greatly appreciated! $(document).mousemove(rotateScene); }); function rotateScene(e) ...