Trouble with ES6 Arrow Functions, Syntax Error

I am encountering an issue with my JS class structure:

class Tree {   

    constructor(rootNode) {
        this._rootNode = rootNode;
        rootNode.makeRoot();
    }
      
    getRoot() {
        return this._rootNode;
    }

    findNodeWithID(id) {
       return this.findNode(this._rootNode, id);
    }

...Some more code here...
        
}

There are two main problems I need to address:

  1. The specified syntax resulted in a compilation error

    findNode = (node, id) => { ^ SyntaxError: Unexpected token =

  2. When tinkering with it and altering the function type

findNode = (node, id) => {
       ...
    }

It appears that changing the method structure disrupts the functionality of findNodeWithID. Any thoughts on why this may be happening?

Answer №1

This code snippet demonstrates the use of classes in JavaScript, specifically for creating a Tree data structure. However, if you want to ensure compatibility with all browsers and versions, it is recommended to transpile this code using Babel.

Alternatively,

// Define a Tree class
class Tree {   
  constructor(rootNode) {
    this._rootNode = rootNode;
    rootNode.makeRoot();

    // Bind `this` in the constructor
    this.findNode = this.findNode.bind(this)
    this.findNodeWithID = this.findNodeWithID.bind(this)
    this.getRoot = this.getRoot.bind(this)
}

// Get the root node of the tree
getRoot() {
    return this._rootNode;
}

// Find a node in the tree by ID
findNodeWithID(id) {
   return this.findNode(this._rootNode, id);
}

// Recursive function to find a node by ID
findNode(node, id){
    if(node.id === id) {
        return node;
    } else {
        node.getChildren().forEach(child => {
              this.findNode(child, id);
        });
    } 
    return null;
  }
}

Answer №2

If you want to utilize arrow functions as a class property, make sure to include the transform-class-properties plugin as detailed in this guide.

Answer №3

If you desire for the function findNode to be included in the prototype of Tree, you have a few options:

class Tree {
  …
  findNode(node, id) {
    …
  }
}

You can either use a regular function as shown above or assign it directly to the prototype like this:

Tree.prototype.findNode = (node, id) => {…}

If you want findNode to be initialized as a property, you can achieve that by doing it in the constructor:

class Tree {
  constructor() {
    this.findNode = (node, id) => {…}
  }
  …
}

An alternative approach is to utilize TypeScript, which will support the syntax you are using.

Note that if you are referencing this in the function, avoid using an arrow function as it will not have the correct this context.

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

Error: Attempting to assign a value to the property 'running' of an undefined variable

While working with Nuxt.js, I encountered an issue related to reading the running property of my client object. Here is the HTML code snippet: <b-button v-show="!(projectSelecter(project.ID)).isStarted" //this work just fine variant="success" c ...

Challenges with the "//" syntax in UNIX

$('#lang_choice1').each(function () { var lang = $(this).val(); $('#lang_files').empty(); $.ajax({ type: "POST", url: '< ...

The file reading code in my Node.js application suddenly stopped working

I have a basic web application that I am currently developing using Node.js and Express. This is a breakdown of my package structure: https://i.stack.imgur.com/D7hJx.png The entries in my questions.json file are outlined below: [ { "question": "Wh ...

Fixing Bugs in Checkbox Functionality using useState in Reactjs when implementing Material UI

I am working on a numeric select functionality where selecting a number renders the component multiple times. Inside the component, there are checkboxes that should not all activate at once when one is selected. You can view the code in the sandbox: http ...

Infinite scrolling made effortless with jQuery and Ajax

I am attempting to create a basic infinite scroll feature that monitors when the user scrolls to the bottom in an HTML file. Once the bottom is reached, it should then load additional content from another HTML file which contains more text. The second HTM ...

The extent of a nameless function when used as a parameter

I am currently developing a straightforward application. Whenever a user hovers over an item in the list (li), the text color changes to green, and reverts back to black when the mouse moves away. Is it possible to replace lis[i] with this keyword in the ...

Determine the height of an element within an ng-repeat directive once the data has been fetched from an

After sending an ajax request to fetch a list of products, I use angular's ng-repeat to render them. I am attempting to retrieve the height of a div element that contains one product in the list. However, the console always displays "0" as the result ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...

How can I ensure that TypeORM, Type GraphQL, Apollo Server, and Azure Functions work together seamlessly?

I have an Azure Function written in TypeScript that utilizes various technologies such as TypeORM, Apollo Server, and TypeGraphQL. The function involves creating resolvers for projects and tasks and establishing a database connection. import { createConne ...

Why is Node.js unable to locate my files?

I'm currently utilizing Node.js as my server, and I'm encountering some difficulties in serving my JS and CSS files. For some reason, index.html is unable to locate them. Whenever I try to load up my browser, I encounter the following error: htt ...

Troubles with showcasing user attributes in the view with ng-repeat and handle-bars in Angular.js

React.js, Express.js, MongoDB server.js: const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const routes = require('./routes/index'); const users = ...

Unexpected behavior observed: Title attribute malfunctioning upon double clicking span element

I recently implemented the following code: <span title="hello">Hello</span> Under normal circumstances, the title attribute functions correctly when hovering over the element. However, after double clicking on the span element (causing the t ...

What is the process for enabling HLS.js to retrieve data from the server side?

I have successfully implemented a video player using hls.js, and I have some ts files stored in https:/// along with an m3u8 file. To read the content of the m3u8 file, I used PHP to fetch it and sent the data to JavaScript (res["manifest"] = the content ...

"Select2 dropdown search bar vanishing act: The hunt for results comes up empty

Currently, I am dealing with a scenario involving two modals, each containing a select2 search dropdown. An issue has arisen where selecting modal one filters the dropdown data effectively. However, upon selecting modal two, although the data is filtered i ...

Find the value of the nearest input field using jQuery

I'm working with HTML code that looks like this: <tr> <td class='qty'><input class='narrow' value='1' /><i class='fa fa-trash' aria-hidden='true'></i></td> < ...

Filtering input based on its occurrence rate (enable/disable debounce)

Utilizing node on a raspberry pi and the module onoff to capture input. I am interested in running function B only if function A is triggered twice within one minute. var gpio = require('onoff').Gpio; var sensor = new gpio(7, 'in', &ap ...

"Creating varying lengths of time with useSpring: A Step-by-Step Guide

Is there a way for my component to have an animation that fully displays in 0.3s when my mouse enters, but disappears in 0.1s when my mouse leaves? Currently, with useSpring, I can only define one duration for both scenarios. How can I set different dura ...

Deciphering the evolution of APIs and managing internal API systems

I'm currently exploring the world of APIs and I have a few questions that are puzzling me. Question1: I understand that APIs facilitate communication between different applications. But why would a company need an API for internal use? For example, i ...

Convert a string with the characters '"' retrieved from a MySQL database into JSON

After creating a JSON object and storing it in MySQL, I encountered an issue when trying to retrieve and parse it. When I stringify the JSON object, the properties are being enclosed in double quotes causing issues when parsing the retrieved string. Below ...

How a JavaScript function handles the scope of a for loop index

Here's some Javascript code I'm working with: func1() { for(i = 2; i < 5; i ++) { console.log(i); func2(i); } } func2(x) { for(i = 100; i < 200; i ++) { do something } } I've noticed that when runni ...