The code seems to have encountered an unexpected token, it was

I am eager to implement the ternary operator in my code, but I keep encountering the following error message:

" Unexpected token, expected : "

Can someone enlighten me as to why this is happening?

Here is the initial code snippet I wrote:

const GetUp = (num) => {
  for (let i = 1; i <= num; i++) {
    if (i % 3 === 0) {
      console.log('Get')
    }
    if (i % 5 === 0) {
      console.log('Up')
    }
    if (i % 3 === 0 && i % 5 === 0) {
      console.log('GetUp')
    } else {
      console.log(i)
    }
  }
}
GetUp(200)

And here is the updated version of my code:

const SetRuc = (num) => {
  for (let i = 1; i <= num; i++) { 
    (i % 3 === 0) ? console.log('Set') :
    (i % 5 === 0) ? console.log('Ruc') :
    (i % 3 === 0 && i % 5 === 0) ? console.log('SetRuc') : console.log(i)
  }
}

SetRuc(100)

Answer №1

Utilize the && operator for shorthand if statements without an else clause.

Remember to add semicolons ; to indicate the end of each instruction, as failing to do so may cause all three lines to be evaluated as a single instruction.

const SetRuc = (num) => {
  for (let i = 1; i <= num; i++) { 
    (i % 3 === 0) && console.log('Set');
    (i % 5 === 0) && console.log('Ruc');
    (i % 3 === 0 && i % 5 === 0) ? console.log('SetRuc') : console.log(i);
  }
}

SetRuc(100)

Answer №2

For instance:

(i % 3 === 0) ? alert('Activated')

does not offer a : alternative for the ?. If you wish to have nothing occur if the ? condition is false, you can simply specify an empty object or undefined:

(i % 3 === 0) ? alert('Activated') : {}

Answer №3

In the scenario where you don't want to execute any specific action when a false result is obtained in a ternary operator, you can simply include null as the alternative expression. For example: statement ? 'expression' : null

To implement this, just incorporate null in the respective section. Here is an example:

const SetRuc = (num) => {
  for (let i = 1; i <= num; i++) { 
    (i % 3 === 0) ? console.log('Set') : null;
    (i % 5 === 0) ? console.log('Ruc') : null;
    (i % 3 === 0 && i % 5 === 0) ? console.log('SetRuc') : console.log(i);
  }
}

SetRuc(100)

Answer №4

You've incorrectly utilized the ternary operator. The correct syntax is as follows:

condition ? expr1 : expr2

This means that if the condition is true, expr1 will be executed, otherwise expr2 will be.

A revised version of your code could look like this:

const SetRuc = (num) => {
  for (let i = 1; i <= num; i++) { 
    (i % 3 === 0) ? console.log('Set') :
    (i % 5 === 0) ? console.log('Ruc') :
    (i % 3 === 0 && i % 5 === 0) ? console.log('SetRuc') : console.log(i)
  }
}

SetRuc(100)

Answer №5

function printSetRuc(num) {
  for (let i = 1; i <= num; i++) { 
    if (i % 3 === 0) {
      console.log('Set');
    } else if (i % 5 === 0) {
      console.log('Ruc');
    } else if (i % 3 === 0 && i % 5 === 0) {
      console.log('SetRuc');
    } else {
      console.log(i);
    }
  }
}

printSetRuc(100);

You should remember to add a colon after both console.log('Set') and console.log('Ruc').

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

Updating the vue data map to group items by both date and employee

I am currently facing an issue with my Vue component and template where I display employees along with their hours/scans by date. The problem is that the current mapping aggregates all hours and scans based on the first record's date. The challenge a ...

How can we dynamically extract the chosen value from a multiple selection using MaterializeCss?

(none of the similar questions provided me with a solution) Currently, I am utilizing the HtmlHelper @Html.ListBoxFor to generate a multiple select. However, I am encountering an issue where it generates the following structure: <ul id="select-option ...

Is there a way to verify whether all elements (text, email, number, and radio) within a specific div have been selected or filled

Is there a way to activate the submit button on a form only when all inputs are checked or not empty? I've come across various snippets on Google and SO that achieve something similar, but they only work for a specific type of input, not taking into ...

Using jQuery to alter the colors of a dynamically generated table based on its content

I am currently working with a div element that dynamically generates a table. Although I can generate the table and use on("click" or "mouseover", function) to achieve certain results, I need the table to update as it loads. In my initial attempts, I tri ...

Definition of Stencil Component Method

I'm encountering an issue while developing a stencil.js web component. The error I'm facing is: (index):28 Uncaught TypeError: comp.hideDataPanel is not a function at HTMLDocument. ((index):28) My goal is to integrate my stencil component i ...

Saving Data in an Angular Material Table: A How-to Guide

I have a basic angular material table and I am looking for a way to save the data displayed in each row when a button is clicked. Is it possible to save each row of data as an object and push it to an array? If so, how can I achieve this? <div class=& ...

Oops! An error occurred: fs.readFileSync is not a valid function to perform the Basic

I'm facing a dilemma - I have a relatively simple app (I'm still new to Node): App.js import * as RNFS from 'react-native-fs'; var config_full; // readFile(filepath: string, encoding?: string) RNFS.readFile('./config.toml', ...

Guide to effectively retrieving data from S3 and displaying a view at regular intervals of 4 seconds

In my current project, I am working on fetching a file from S3 and utilizing the data within that file to generate a map on a webpage. To achieve this task, I have set up an Express server along with the EJS templating engine for serving and rendering the ...

Python's method for passing an array to a Django template

If I had an array in my Python backend and needed to send it to the front end as JSON or a JavaScript array, how could I accomplish this utilizing the Django framework? A possible template implementation is as follows: <script type="text/javascript"&g ...

Carousel featuring multiple items with uniformly sized cards

Anticipated outcome: Consistent height across all cards (each card should adjust its height to match the tallest card) Actual result: Height varies based on text length Code Snippet: NOTICE DIFFERENCES IN HEIGHT AMONG SLIDES ...

Error: The text in the NativeBase Button is not displaying

I'm facing an issue where the buttons in NativeBase are not displaying their text. I followed the sample code from their website documentation, but when I run the code, the buttons appear without any titles. Any suggestions on how to fix this? Here&ap ...

Display a preview image of the video without playing the actual video

Is there a way to display a thumbnail image from a video without loading the actual video content? I only need the thumbnail displayed, not the video itself. I am looking to showcase the thumbnail after uploading a video using file upload. The thumbnail s ...

Troubleshooting the intermittent issues of JavaScript image setting with S3 CORS

While experimenting with the canvas element to save images, I encountered issues specifically in Chrome related to setting the initial image. <a href="#" data-src="https://s3.amazonaws.com/imphotos/uploads/thumb_IM_17592186048618_17592186048643.jpg"&g ...

What are some ways a Vue component can exhibit varied behaviors based on different states?

As a newcomer to the Vue framework, I find myself immersed in a project focused on creating and editing directed graphs online. One particular challenge I am facing is ensuring that components can react differently based on the application's current s ...

Creating a data structure using jQuery/JavaScript when submitting a form - a guide

Currently, I am attempting to gather form input values and organize them into an array of objects that will then be sent to MongoDB. However, I am facing difficulty in figuring out how to include an array within the objects (refer to the comment in the cod ...

Guidelines on receiving a user's color input and showcasing it with JavaScript

/* Take a color input from the user and apply it to the variable called "message". */ <script type="text/javascript"> var textcol, message = "Great choice of color!"; textcol=window.prompt("Please enter a color:&quo ...

What is the best way to set an element in an array that is nested within another array using AngularJS?

$scope.pictures=[ { name:"/images/profile2.jpg", caption:"Food and Hunger", votes:0, User:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68101112280f05090104460b0705">[email protecte ...

Retrieving the file name from the line number within the trace stack or Error object

I'm working on enhancing my error handling in Node.js/express. Does anyone know a method to retrieve the filename and line number where an error occurs in my code? error-handler.js, utilizing console.trace, only handles errors at the route level...n ...

The implicit wait feature in WebDriver JavaScript seems to be ineffective

Waiting for the error message to appear seems to be a bit tricky. I tried using browser.driver.manage().timeouts().implicitlyWait() but had to resort to using browser.driver.sleep() instead. this.getErrorMessage = function () { var defer = protracto ...

Ensure the video fills the entire width of its parent element and adjusts its height accordingly to maintain a 16:9

I am looking to make both videos fill 100% width of their parent element while keeping their aspect ratio intact. The parent element takes up 50% of the window's width, so the videos need to be responsive. I have come across numerous solutions that ...