JavaScript does not allow the use of variables outside of functions

As someone diving into the world of Javascript after working extensively with server-side languages like PHP, I've noticed a peculiar issue. It seems that I am unable to access variables defined outside of a function from within the function itself. To circumvent this problem, I find myself constantly duplicating these variables inside the function. Let me illustrate this with an example:

    var num1 = document.getElementById("num1");
    var num2 = document.getElementById("num2");

    function calculateSum() {
        alert(Number(num1.value) + Number(num2.value));
    }

Answer №1

It seems like the issue may be related to your script running before the full page has finished loading, causing it to not recognize the "first" and "second" elements.

The variables are accessible, but they are initially set to "undefined" when created. Placing the variables inside a function delays their initialization until the function is actually called, ensuring they are only accessed after the page has completed loading.

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

Dealing with the Spread operator in React and Redux causes issues

As a newcomer to the world of React and Redux, I find myself facing compilation errors while working on a reducer due to my attempt to utilize the spread operator. export default function chaptersReducer( state = { chapters: {}, isFetching: false, error ...

Create seamless communication between Angular application and React build

I am currently engaged in a project that involves integrating a React widget into an Angular application. The component I'm working on functions as a chatbot. Here is the App.tsx file (written in TypeScript) which serves as the entry point for the Rea ...

Wordpress functionality for filtering Ajax posts using radio buttons

I am in the process of creating an Ajax post filter system using radio buttons to allow users to filter through multiple categories. Below is the code I have implemented: Front-end form: <form id="filter"> <?php if( ...

Implementing shallow routing with the Next.js 13 framework while having appDir functionality activated

Previously in Next 13 (or with appDir disabled), you could achieve the following: const MyComponent = () => { const router = useRouter(); const toggleStatic = () => { if (router.query.static) { router.push(router.pathname, router.pa ...

Accordions housing Bootstrap 3 pills in a sleek design

I'm working on integrating pills and an accordion in Bootstrap 3. Everything seems to be functioning correctly, but there are a couple of issues I am encountering: When the accordion is open, clicking on another tab closes the accordion. I would li ...

Arrange the HTML DOM elements in the order of their appearance in a list

Is it possible to rearrange the order of <div> and its elements based on database information? For example, consider the following HTML structure: <div id="container"> <div id="A"> Form elements for A</div> <div id="B"& ...

Utilizing JavaScript to trigger an alert message upon selecting various options and blocking the onclick event

Setting up a simpleCart(js) with selectable options presents a challenge. The task at hand is to display an alert if not all drop-downs meet specific requirements and to prevent the "Add to cart" button from adding items to the cart when these conditions a ...

Issue: The data type 'void' cannot be assigned to the data type 'ReactNode'

I am encountering an issue while calling the function, this is just for practice so I have kept everything inside App.tsx. The structure of my class is as follows: enum Actor { None = '', } const initializeCard = () => { //some logic here ...

Exploring JSON objects in React for improved search functionality

Hey there! I'm working on implementing a search bar that updates the list of JSON entries based on user queries. Below is the code snippet that displays the video list (<Videos videos={this.state.data}/>). Initially, when the page loads, I have ...

Combining CSR and SSR in the next iteration of our project will

In my application, I have three main user roles: Consumer, Merchant, and Admin. I want the pages that Consumers access to be SEO friendly and server rendered. However, for Merchants and Admins, I prefer them to be client rendered with their own respective ...

Check to see if modifying the HTML using jQuery results in any errors

Although it may sound straightforward, let me clarify. I am utilizing ajax calls to update the content of the body and I aim to trigger an alert if the updating process fails on the client side, specifically after receiving a response from ajax in case of ...

Kudos to the information provided in the table!

My JSON data is structured like this: { description : "Meeting Description" name : "Meeting name" owner : { name: "Creator Name", email: "Creator Name" } } I want to present the details in a table format as follows: Meeti ...

Sliding and repositioning elements using jQuery

My goal is to build a simple slideshow for learning purposes. I want the list items to slide automatically to the left in a continuous loop. I've written some code that makes the slides move, but I'm struggling to set the correct position for ea ...

Including a Javascript library (jsencrypt) in an Angular 2 application

I have gone through countless tutorials on this particular issue, but unfortunately, I have not yet found a solution. Let me provide some context first. I am working on an Angular 2 application and I need to incorporate this JS library for encryption: http ...

Ways to resolve the issue of an invalid hexlify value error in ethers.js

Error: hexadecimal value is not valid (argument="value", value="PRIVATE_KEY", code=INVALID_ARGUMENT, version=bytes/5.7.0) During the development process of an application that transfers a token from one wallet to another using Ethers.j ...

A guide on implementing multiline properties in a property file for Selenium WebDriver

At the moment, I am focusing on utilizing Selenium WebDriver with code that is developed in Java. In the snippet below, I have successfully verified if the dropdown values match the UI for one dropdown. Now, I aim to extend this capability to check multip ...

Can you provide the regular expression that will successfully match this specific string of text?

Can you solve this fruit riddle? apple is 2kg apple banana mango is 2kg apple apple apple is 6kg banana banana banana is 6kg If the fruits are limited to "apple", "banana", and "mango", how can we write a regex that extracts the names of ...

Saving data for editing on a Laravel page can be achieved by leveraging the powerful features

I have implemented my create page using vue.js. I called the vue.js file using a component. Now, for the edit page, I followed the same procedure by calling the vue component in the blade. However, I am unsure how to save data for the edit page. Can anyone ...

Can a webpage be sent to a particular Chromecast device without using the extension through programming?

My organization has strategically placed multiple Chromecasts across our facility, each dedicated to displaying a different webpage based on its location. Within my database, I maintain a record of the Chromecast names and their corresponding URLs. These d ...

Executing file upload in parent component with Angular 2

Is there a way to initiate a file upload from the parent component of the router? Specifically, I need to execute two functions located in the parent component - openFileSelect and uploadSelectedFile to manage the <input type="file"> element. This i ...