What could be causing the error "SyntaxError: Expected token ']' to appear" to pop up?

Recently, I have been working on implementing a 'night mode' feature for a website.

However, every time I attempt to execute the script, an error message pops up:

"SyntaxError: Expected token ']'" on line 9.

The problematic line in question reads as follows:

this.pageElements[0] = ['element': document.body, 'background': ['day': '#f1f1f1', 'night': '#0e0e0e']];

I cannot seem to figure out why it is not functioning properly.

Below is the complete code snippet:

window.nightMode = {};

//Functions
nightMode.init = function () {
    this.pageElements = [];

    //Format: ['element': Element, 'background': ['day': Day background color, 'night': Night background color], 'text': ['day': Day text color, 'night': Night text color]];
    this.pageElements[0] = {
        'element': document.body,
        'background': {
            'day': '#f1f1f1',
            'night': '#0e0e0e'
        }
    };
    this.pageElements[1] = {
        'element': document.getElementById('yt-masthead-container'),
        'background': {
            'day': '#fff',
            'night': '#000'
        }
    };
    this.pageElements[2] = {
        'element': document.getElementById('search-btn'),
        'background': {
            'day': '#fff',
            'night': '#000'
        }
    };
    this.pageElements[3] = {
        'element': document.getElementById('masthead-search-terms'),
        'background': {
            'day': '#fff',
            'night': '#000'
        },
        'text': {
            'day': '#666',
            'night': '#999'
        }
    };


    this.isNight = false;
}

nightMode.setNight = function () {
    for (var i = 0; i < this.pageElements.length; i++) {
        this.pageElements[i].element.style.background = this.pageElements[i].background.night
        if (this.pageElements[i].text) {
            this.pageElements[i].element.style.color = this.pageElements[i].text.night
        }
    }
    alert('Night mode');

    this.isNight = true;
}

nightMode.setDay = function () {
    for (var i = 0; i < this.pageElements.length; i++) {
        this.pageElements[i].element.style.background = this.pageElements[i].background.day
        if (this.pageElements[i].text) { 
            this.pageElements[i].element.style.color = this.pageElements[i].text.day
        }
    }
    alert('Day mode');

    this.isNight = false;
}

nightMode.toggle = function () {
    if (this.isNight) {
        this.setDay();
    } else {
        this.setNight();
    }
}


//Startup Code
nightMode.init();

nightMode.toggle();

Answer №1

Arrays are collections of elements in a specific order, while objects consist of key-value pairs.

It seems like you are attempting to nest object literals within array literals.

Instead, try using object literals {}.

Answer №2

When dealing with object literals, it is important to remember that they are enclosed in curly braces {}, not square brackets []. Square brackets are typically used for arrays which have keys as non-negative indexes. The correct syntax for defining an object literal would be:

this.pageElement[0] = {
    element: document.body,
    background: {
        day: '#f1f1f1',
        night: '#0e0e0e'
    }
};

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

React: Avoid the visible display of conditional rendering component fluctuations

In my current React project, I am developing a page that dynamically displays content based on the user's login status. The state variable "loggedIn" is initially set to null, and within the return statement, there is a ternary operator that determine ...

Navigating through tables and selecting rows

I am currently facing an issue with my HTML table that consists of 1000 rows and 26 columns. To navigate between rows and make selections, I have implemented a jQuery plugin on the table. The problem lies in the performance of the plugin, even with the la ...

Oops! An error occurred while trying to find the _mongodb._tcp.blog-cluster-0hb5z.mongodb.net. Please check your query settings and try again

My free Mongo Atlas cluster suddenly stopped connecting, even though everything was working fine before. Strangely, I can see that data has been collected on the MongoDB website. It's puzzling why this issue occurred and now my entire site won't ...

Launching a Node.js Express application on Heroku

I'm facing an issue while trying to deploy my app on Heroku, as I keep encountering the following error: 2022-08-11T12:49:12.131468+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306 2022-08-11T12:49:12.131469+00:00 app[web.1]: at TCPConnect ...

Tips for eliminating fade effect during hover in networkD3 chart in R

Currently, I have been exploring the usage examples of networkd3 in r I am curious if there is a way to eliminate the hover effect where everything else fades when hovering over a specific node in the graph. For reference, check out "Interacting with igra ...

Why does the pound symbol in z-index always show up in Angular?

Having an issue with my code where I set a z-index in the CSS like this: .mat-mini-fab { position: absolute; right: 5px; top: 4px; z-index: 999; box-shadow: none !important; } However, whenever I visit my site, the z-index is not being appl ...

Prevent redirection in JavaScript

My current script is designed to detect an Android device and then redirect the user to "android.html". Once on the "android.html" page, the user has the option to either download an app or click "CONTINUE" to proceed to "index.html". However, there seems ...

Utilizing React to adapt to varying HTML layouts while maintaining consistent component usage

How can I create an App with two different views for mobile and desktop without relying solely on CSS Media Queries? I have been searching for guidance but so far haven't found a solution. Any advice or direction on where to find documentation or oth ...

How can I pass a JavaScript variable through the URL in a Rails 4 application to access it in the controller?

Struggling to pass the value of a JavaScript variable in the URL and then retrieve it in my Rails 4 app controller using param[:my_variable]. Despite trying various methods, none seem to work for me. I am unable to successfully pass my JavaScript variable ...

Tally of number series in an array

If my array looks like [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10] How do I determine the number of times a sequence of 10's occurs with at least 3 repetitions. In this example, the output would be 2 because there are 2 s ...

The number range filter in ng-table is malfunctioning

what I am trying to accomplish My goal is to create a column that can accommodate two numbers in order to filter numeric data within a specific range for that column. While sorting, pagination, and filtering by 'contain text' are working correct ...

Selenium: The function moveToElement is not valid for the driver.actions() method

After creating all my tests using Selenium IDE, I decided to export them to JavaScript Mocha for running in travis. While the tests run smoothly in Selenium IDE and can be exported, I encountered an issue when trying to run them which resulted in the erro ...

Set the class of an element dynamically using ng-class and detect changes with ng-change

I want the input field to initially have the class .form-control-error. When the user clicks on the field and starts typing, I would like it to change to .form-control-success. I attempted the following code but couldn't get it to update. The ng-chan ...

Ways to execute a JavaScript function upon a button click instead of during the page load completion

I searched on Google but couldn't find the answer, so I'm asking here for help. In the attached screenshot located at the end, when the user clicks on the download button, some backend actions are performed such as file transfer. Once the proces ...

Destructuring part of an object within function parameters in JavaScript

Is it possible to selectively destructure specific object properties in function arguments, while keeping the rest accessible within the object? Let's explore this concept with a React example. (Although React is used here, the question pertains to J ...

Tips for automatically closing the Toggle Navigation feature in Vue JS when a user clicks outside of the navigation container

Is there a way to close the toggled navigation menu automatically when the user clicks outside of the navigation container? I have implemented two ul menus inside the navigation menu and would like the subNavActive, safNavAcitve, and repNavUl variables to ...

When I type text into the form field, JavaScript causes a disruption in the form

I'm attempting to implement a dual-stage user onboarding procedure. Initially, users will input the industry they belong to and then provide a description. Upon clicking submit, my intention is to conceal that portion of the form and reveal the "Creat ...

Adding a detached element under certain conditions

When attempting to add a detached span based on a specific condition, I encountered the following situation. const arrow = d3 .create('span') .classed('arrow', true) .text('\u2192'); //d3.select('bod ...

Stopping XSS Attacks in Express.js by Disabling Script Execution from POST Requests

Just starting to learn ExpressJs. I have a query regarding executing posted javascript app.get('/nothing/:code', function(req, res) { var code = req.params.code; res.send(code) }); When I POST a javascript tag, it ends up getting execut ...

How to hide an item in Ionic 2 using navparams

Is there a way to dynamically hide or show a list item on page load depending on certain parameters? Here is an example of the code I am currently using: HTML <button ion-item (tap)="goToPage2()" [hidden]="shouldHide">Page 2</button> TS ex ...