Imagine you are looking to execute an if/else statement

I'm having some trouble with this code that is meant to print different values based on certain conditions, but it only seems to be printing one value consistently. See the code snippet below:

let twitterfollowers;
let websitetraffic;
let monthlyrevenue;

function displayMetrics(metric) {
  if (metric === twitterfollowers) {
    console.log("Metric A");
  } else if (metric === websitetraffic) {
    console.log("Metric B");
  } else if (metric === monthlyrevenue) {
    console.log("Metric C")
  }
};

console.log(displayMetrics(twitterfollowers));
console.log(displayMetrics(websitetraffic));
console.log(displayMetrics(monthlyrevenue));

Answer №1

Consider assigning a distinct value to each of the various choices available.

let facebookLikes = 1;
let websiteTraffic = 2;
let dailyVisits = 3;

function displayWidgets(type){
  if (type === facebookLikes){
    console.log("This is Option A");
  } else if (type === websiteTraffic){
    console.log("This is Option B");
  } else if (type === dailyVisits){
    console.log("This is Option C")
  }
}

displayWidgets(facebookLikes);
displayWidgets(websiteTraffic);
displayWidgets(dailyVisits);

You could also create an object enumeration to store all the types:

const WIDGET_TYPE = {
  FACEBOOK_LIKES: 1,
  WEBSITE_TRAFFIC: 2,
  DAILY_VISITS: 3
}

Subsequently, you can make a function call like this:

displayWidgets(WIDGET_TYPE.FACEBOOK_LIKES);

Answer №2

In Javascript, enums are not a built-in feature. When a variable is not initialized, it defaults to undefined.

For example, these two statements are equivalent:

let twitterfollowers;
let twitterfollowers = undefined

So, when you pass in y and undefined into your function, it checks if y === twitterfollowers, which is essentially undefined === undefined, resulting in true.

To mimic an enum, you can assign specific values to your variables like this:

const twitterfollowers = 'twitterfollowers';
const dailylikes = 'dailylikes';
const monthlyvisitors = 'monthlyvisitors';

function socialmediametrics(y) {
  if (y === twitterfollowers) {
    return "This is A";
  } else if (y === dailylikes) {
    return "This is B";
  } else if (y === monthlyvisitors) {
    return "This is C";
  }
};

console.log(socialmediametrics(twitterfollowers));
console.log(socialmediametrics(dailylikes));
console.log(socialmediametrics(monthlyvisitors));

Instead of using a string, you can also use a number or any object, like a Symbol if your environment supports it.

Each Symbol instance is unique, making comparisons with === work seamlessly.

const twitterfollowers = Symbol();
const dailylikes = Symbol();
const monthlyvisitors = Symbol();

function socialmediametrics(y) {
  if (y === twitterfollowers) {
    return "This is A";
  } else if (y === dailylikes) {
    return "This is B";
  } else if (y === monthlyvisitors) {
    return "This is C";
  }
};

console.log(socialmediametrics(twitterfollowers));
console.log(socialmediametrics(dailylikes));
console.log(socialmediametrics(monthlyvisitors));

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 placeholder text is not displaying with bullets in Internet Explorer. However, it is functioning correctly in Chrome

I need assistance displaying the placeholder text in IE8 as shown below: "Any relevant reference numbers, such as Direct Debits: - Name of the Branch (if applicable) - What was the original problem - Date the problem occurred " While it appears correct ...

Is it possible to utilize AngularJS' ng-view and routing alongside jade?

Currently, I am diving into the world of the MEAN stack. I noticed that Express utilizes jade by default, but I decided to experiment with it even though I can easily use html instead. When attempting to route with Angular, like so: ... body div(ng-view ...

Retrieving visual information from Google Street View entity

Looking for a solution to extract imagery from the Google Street View panorama within a web page? In my program, I navigate specific routes using Google Street View's javascript API controlled by an embedded Java applet on the same page. I am seeking ...

Match rooms using Socket.io

I am utilizing the opentok and socket.io packages in an attempt to establish 2 distinct "groups". Successfully, I have managed to pair up individual users in a 1-to-1 relationship. However, my goal is to create two separate groups of users. For instance, ...

Having trouble confirming signature with Node.js Crypto library, specifically with key pairs

I have a concise nodejs code snippet where I attempt to sign a string and then verify it using node crypto along with key pairs generated through openssl. Despite trying various methods, the result consistently shows "false" indicating that the signature c ...

"Unexpected discrepancy: Bootstrap Glyphicon fails to appear on webpage, however, is visible

I am having some trouble getting the glyphicon to display properly in my side nav. The arrow head should rotate down, which is a pretty standard feature. Here is the link to the page: The glyphicon should be visible on the "Nicky's Folders" top leve ...

Is it possible to render array items into separate divs using the .map() method without displaying commas?

After extensive searching, I have only come across solutions that involve using .join() to combine the items into a single string. const createCard = () => { const pokemonTypes = ['grass', 'fire', 'water']; return ...

What is the best method for retrieving information from MongoDB and presenting it in a table with Node.js?

I'm struggling to understand how to retrieve data from mongodb and display it in an html/ejs file. I have a button in the html/ejs file that, when clicked, should show all the data from a mongodb database collection. While I've come across simil ...

How to fetch an image from a web API using JavaScript

I have recently entered the world of web development and I am facing an issue where I am trying to retrieve a Bitmap Value from a web api in order to display it on an HTML page using JavaScript. However, despite my efforts, the image is not getting display ...

What steps can you take to stop a tab from being inserted if one is already present?

I am facing a simple issue where I need to prevent the insertion of a tab if one already exists. Issue: I have a search bar that displays results in a div with class.result_container_2 when a user inputs a name. Upon clicking on this tab, another tab is i ...

Can you suggest a more efficient method for retrieving data from a string?

Imagine having an array of strings with various information, and you need to extract specific details from them. Is there a simpler method to achieve this task? Consider the following array: let infoArr = [ "1 Ben Howard 12/16/1988 apple", "2 James S ...

Axios: Exception handling does not involve entering the catch method

Implementing a function to adjust a contract name involves making an axios request to the backend API using a specific ID. Upon each execution, a sweetalert prompt is displayed. axios({ url: '/api/contract/' + id, method: 'put ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

The Angular $digest cycle ensures that the entire view is refreshed, rather than just a portion

Encountering a peculiar problem in Angular 1 where the script is getting stuck in an endless loop, eventually causing the browser to freeze. Here's what I'm attempting: <script> $scope.A = true; $scope.B = [{blah},{blah}]; $sc ...

AngularJS ng-focus does not function properly with iframes

Why isn't ng-focus working with iframe in AngularJS? What am I missing? Take a look at my code: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <iframe src="example.com" tabindex="-1" ng-fo ...

How can you simultaneously send FormData and String Data using JQuery AJAX?

Is there a way to upload both file and input string data using FormData()? For example, I have several hidden input values that also need to be included in the server request. html, <form action="image.php" method="post" enctype="multipart/form-data"& ...

ExpressJS: How to resolve the undefined error in Express session

After using express-generator to create my project, I installed the express-session package. Below is how express-session is ordered in my app: app.js var expressSession = require('express-session'); app.use(logger('dev')); app.use( ...

The v-text-field within the activator slot of the v-menu mysteriously vanishes upon navigating to a new route within a

Working on my Nuxt project with Vuetify, I encountered an issue where the v-text-field would disappear before the page changed after a user inputs date and clicks save. This seems to be related to route changing, but I have yet to find a suitable solutio ...

React 17 Form not registering the final digit during onChange event

I am currently experiencing an issue with a form that includes an input field of type "number." When I enter a value, the last number seems to be skipped. For example: If I input 99 into the box, only 9 is saved. Similarly, when typing in 2523, only 252 ...

Flickering issue with Chart.js chart persists upon reopening the page

Utilizing mustache.js, I am injecting a view file into a designated <div>. Within this view, I have incorporated a canvas element situated inside a specific div, showcasing a chart created with Chart.js. <div> <canvas id="gesundheitsve ...