JavaScript is displaying an error message stating that the array variable has not been

I'm currently going through a Javascript tutorial on YouTube and I've encountered an error that's puzzling me. Everything seems to be in order with the array definition.

Uncaught ReferenceError: words is not defined

window.addEventListener("load",initial());
//Global variables
let time = 5;
let score =0;
let isPlaying;

//DOM variables
const wordInput_input= document.querySelector('#word-input');
const currentWord_h2 = document.querySelector('#current-word');
const scoreDisplay = document.querySelector('#score');
const timeDisplay = document.querySelector('#time');
const message = document.querySelector('#message');
const seconds = document.querySelector('#seconds');

const words = ['hat', 'river', 'lucky', 'state'];

//Initialize game
function initial(){
    //Load word from the array
    showWord(words);
}

//Pick and display random word
function showWord(words){
    //Generate random array index
    const randIndex = Math.floor(Math.random() * words.length);
    // Display random word
    currentWord_h2.innerHTML = words[randIndex];
}

Answer №1

Don't forget that when you use initial as an event listener on the first line (

window.addEventListener("load",initial());
), the variable words may not be defined yet.

To avoid this issue, consider moving the event listener to the bottom of your code.

This scenario is related to Hoisting in Javascript. Remember, variables declared with const are not hoisted. For more information on hoisting, refer to this resource.

Answer №2

Instead of calling the initial function directly, make sure to attach it as an event listener. Modify

window.addEventListener("load",initial());
to
window.addEventListener("load",initial);
. Also, be cautious when invoking the showWords function with words before its initialization.

window.addEventListener("load", initial);
//Global variables
let time = 5;
let score = 0;
let isPlaying;

//DOM variables
const currentWord_h2 = document.querySelector('#current-word');

const words = ['hat', 'river', 'lucky', 'state'];

//Initialize game
function initial() {
  //Load word from the array
  showWord(words);

}

//Select and display random word
function showWord(words) {
  //Generate random index within the array length
  const randIndex = Math.floor(Math.random() * words.length);
  // Output randomly selected word
  currentWord_h2.innerHTML = words[randIndex];
}
<h2 id="current-word">Test</h2>

Answer №3

By declaring the variable 'words' as a global constant, you can access it from any function. If you are encountering an undefined error, it may be due to the script executing too quickly and trying to use the variable before it's fully created. Adding a small delay, like 100 milliseconds, in the function can resolve this issue. Here is an example of how you can implement it:

window.addEventListener("load",initial());
//Global variables
let time = 5;
let score =0;
let isPlaying;

//DOM variables
const wordInput_input= document.querySelector('#word-input');
const currentWord_h2 = document.querySelector('#current-word');
const scoreDisplay = document.querySelector('#score');
const timeDisplay = document.querySelector('#time');
const message = document.querySelector('#message');
const seconds = document.querySelector('#seconds');

const words = ['hat', 'river', 'lucky', 'state'];

//Initialise game
function initial(){
    //Load word from the array
      showWord();
}

//Pick and show random word
function showWord(){
  setTimeout(function(){
    //Test Call to words Now is Completed
    console.log(words);
    //Generate random array index
    const randIndex = Math.floor(Math.random() * words.length);
    // Output random word
    currentWord_h2.innerHTML = words[randIndex];
    },100);
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8>
  <title>Document</title>
</head>
<body>
<input type="text" value="word" id="word-input">
<input type="text" value="current" id="current-word">
<input type="text" value="20" id="score">
<input type="text" value="05:00" id="time">

</body>
</html>

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

Avoid the automatic scrolling of a datatable to the top when clicking on a button within a column using jQuery

https://i.sstatic.net/Jx5G6.png Is there a method to stop the datatable from automatically scrolling to the top when any of the buttons is clicked? ...

"Exploring the various configurations for session handling in NodeJs

I am trying to implement a login system using the express-session module. I'm unsure if I have set everything up correctly, especially when it comes to the secret option. Currently, my initialization code for express-session looks like this: app.use( ...

Async ngInit does not function properly when using $q promises

Edit: Plunker seems to be working fine, but the actual code is not functioning as expected. You can check it out here: http://plnkr.co/edit/5oVWGCVeuTwTARhZDVMl?p=preview The service contains the usual getter\setter methods and works well. I have omi ...

Implementing authentication fallback during re-login when a session expires in a web application built with React, Node.js, and Mariadb database

Greetings everyone, this is my debut post here so kindly bear with me :D. Currently, I am in the process of developing a social app where I am incorporating a fallback mechanism for situations when my database goes offline. Within my Login.jsx component, I ...

Alter the background color of a React application with a single click in a spontaneous manner

When I attempted to change the background color of the entire page randomly by clicking a button, it only changed the background of the div element. Here is the code snippet I used: import React from "react"; class Home extends React.Component { ...

Transferring information in Laravel with the help of Axios and Vue Framework

While following the Laracasts tutorial on integrating Stripe, I noticed that a lot has changed since the release of Laravel 5.4. Although I managed to navigate through most of it, I encountered an issue when trying to submit a payment form using Vue and Ax ...

Implementing Checkbox Functionality within a Dropdown Menu using AngularJS or JavaScript

I am interested in finding a multi-select checkbox solution similar to the one demonstrated here: Instead of using jQuery, I would prefer options in AngularJS or pure JavaScript. Does such a solution already exist in these frameworks, or is there guidance ...

JavaScript: The hyperlink provided in the data-href attribute is not functioning properly within the carousel

I have a carousel with images that I want to link to specific pages: JS Fiddle. My goal is to have each image in the carousel direct users to a different webpage when clicked. For example: Clicking on the wagon image should go to wagon.com Clicking on th ...

Is there a way to verify if an email is already registered within a MERN stack application

I am in the process of creating a registration form and need to verify if an email already exists within the system. Below is the React code snippet showcasing the structure for better understanding. In the schema, emails are defined as unique. AuthContr ...

sort the array based on its data type

Recently diving into typescript... I have an array that is a union of typeA[] | typeB[] but I am looking to filter based on the object's type interface TypeA { attribute1: string attribute2: string } interface TypeB { attribute3: string attri ...

Discovering the total of elements in specific locations within two arrays

Hey there! I have a question that I need help with. Given arrays A and B containing natural numbers in incremental order, along with an arbitrary natural number K, how can we efficiently find all index pairs (i, j) where the sum of elements at those indexe ...

How to eliminate spaces while preserving line breaks in a textarea using JS or jQuery

I have been trying to figure out how to remove extra spaces from the beginning and end of lines while keeping the line breaks intact. Here's what I attempted: function removeSpaces(string) { return string.split(' ').join(''); } ...

The functionality of jQuery date picker and time picker is compromised when the fields are generated dynamically

I am currently utilizing the jQuery code below to dynamically create multiple input fields, which include time pickers and date pickers. However, I am encountering an issue where they are not functioning as expected. $('#add_another_event').clic ...

Retrieving components from Ajax response data

While I have a good grasp of PHP, diving into AJAX and dealing with JSON is proving to be quite challenging for me. My PHP script simply delivers a straightforward JSON string like this: {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": ...

Elevate the functionality of your table in BoostrapVue by customizing it to display items

How can I modify the code below to turn the items into input fields that the user must enter? Instead of listing the items, I would like to replace them with input fields. <template> <div> <b-form-input v-for="(item, index) in items" ...

Expanding Gridview Width within a Container in ASP.Net: A Step-by-Step Guide

https://i.stack.imgur.com/ZaJE7.jpg After viewing the image above, I am facing a challenge with stretching and fixing a gridview to contain the entire div where it is placed. The issue arises when the gridview adjusts automatically based on the content&ap ...

Executing a function from a JavaScript file within Robot Framework

It is possible to run javascript from a file. Run JavaScript ${CURDIR}/js_to_run.js However, I am wondering how to call a function by its name from this file? ...

Angular formly - Enhancing User Input Focus

I have created a field wrapper that converts normal text into an input when hovered over with the mouse. Additionally, I have a directive that sets focus on the field when it is activated. Now, I am looking for a solution where the field remains open as l ...

Execute a PHP function through an AJAX request to dynamically update a template variable in PHPBB

Should you require a condensed version of the details provided below, do not hesitate to ask for a summary. My objective is to execute a function in my PHP file which will update a template variable. Here is an example of such a function: function get_ve ...

Transitioning from SJAX to AJAX

I am in the process of updating a portion of my script to use AJAX instead of Synchronous JAX to prevent the page from freezing. My goal is to check if a password is valid before sending it to the server. If the password is not valid, I want the password f ...