Why does the code require the use of window when the Javascript error object is not functioning properly?

I'm struggling to grasp the distinction between

var maxResult = window.max(maxValInt1, maxValInt2);

which functions properly, and

var maxResult = max(maxValInt1, maxValInt2);

which gives an error "object is not a function".

Why do I have to include window. before the max function?

I am new to JavaScript and would appreciate it if you could explain in detail.

<div id="maxOfTwo">Max function: <input type = "number" name="val1" value="0">, <input type = "number" name="val2" value="0"> = <span></span></div>

<script type="text/javascript">

function max(val1, val2){
    if(val1 > val2){
        return val1;
    }else{
        return val2;
    }
}

window.onload = function() {
    var max = document.getElementById("maxOfTwo");
    var maxNumber1 = max.children[0];
    var maxNumber2 = max.children[1];
    maxNumber1.addEventListener("blur", doMax);
    maxNumber2.addEventListener("blur", doMax);
    function doMax() {
        var maxValue1 = maxNumber1.value;
        var maxValue2 = maxNumber2.value;
        var maxValInt1 = parseInt(maxValue1);
        var maxValInt2 = parseInt(maxValue2);
        var maxResult = window.max(maxValInt1, maxValInt2);
        max.children[2].innerHTML = maxResult;
    }
}
</script>

Answer №1

let maximumValue = document.getElementById("maxOfTwo");

Beware of naming conflicts with locally scoped variables.

Remember to explicitly access properties of the window object to prevent scope chain conflicts.

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

Converting a string to a date in JavaScript

Is there a way to convert a string like "20150415" into a date with the format "2015, April, 15th"? I've come across multiple examples, but they all involve splitting with "-" or "/", which doesn't work for my case. Below is my current code snip ...

Exceptionally high memory usage detected in AngularJS

My AngularJS application is running into performance issues due to high memory consumption. There are around 200-250 repeated elements, each containing inner items with nested ng-repeats. The JS Heap memory allocation reaches up to 70MB, causing the webpag ...

Is it possible to declare variables using the "this" keyword?

Consider the scenario where this.x=5 is declared and assess the accessibility of all relevant places. <script> $(document).ready(function(){ $("button").click(function(){ this.x=!this.x; $("#div1").fadeTo(400,this.x ? 0.4 : 1); }); }); & ...

Troubleshooting issue: PHP INSERT Prepared statement not working when using AJAX

Currently, I am trying to construct an INSERT statement using AJAX along with a prepared statement in PDO. This is my first attempt at combining AJAX and PDO, so there might be mistakes due to lack of experience. In its current state, I keep encountering ...

How to Resolve ENOENT ERROR When Using fs.unlink in an Express.js Simple Application?

Currently, I am developing a basic blog using express.js. For managing the posts, I have opted for Typicode/lowdb as my database. The posts are created, updated, and deleted based on unique IDs stored in a data.json file. Additionally, I utilize the slug d ...

JavaScript code in AJAX response functions properly in browsers like Firefox, Chrome, and Opera. However, it encounters issues in Internet Explorer 11, displaying an error message stating

After searching through various posts, I was unable to find a solution to my question. My query involves requesting a jQuery Datepicker via AJAX. I have provided an example for you to review in Firefox, Chrome or Opera: Ajax javascript example Unfortuna ...

React.js: Dynamically Highlighting Menu Items Based on Scrolling位置-GaidoWhen a

Having trouble finding a solution for this issue. I'm currently working on creating a navigation bar with scroll-to functionality, where clicking on a menu item scrolls the page to the corresponding section. However, I am unsure how to change the colo ...

The Next Js 13 API route is failing to retrieve accurate data following a post request

I've been working on a project involving authentication using Django backend and Next.js frontend. For state management, I'm utilizing Redux Toolkit. However, I've encountered an issue with the Next.js API that communicates data to the backe ...

When viewing the material-ui Chip component at normal zoom, a border outlines the element, but this border disappears when zoomed in or out, regardless of

Edit I have recently discovered a solution to the unusual problem I was facing with the material-ui Chip Component. By adding the line -webkit-appearance: none; to the root div for the Chip, the issue seems to resolve itself. However, this line is being a ...

Electron Developer: "An issue has occurred within the primary process - Callback function missing"

My Electron application runs smoothly when launched from the command line with npm start. However, I am now looking to distribute the application as user-friendly installers for Mac/Windows/Linux. To achieve this, I am utilizing Electron-Builder for packag ...

XPath using JScript

I'm a beginner with Selenium and I'm curious about how the value in the text box is loaded when there's no value visible in the HTML tag: <input type="text" name="qty" id="qty" maxlength="5" value="" title="Qty" class="quantity-input qty ...

What is the process for generating an HTTP response that results in a pipe error being thrown

In my NestJS application, I have created a custom pipe that validates if a given value is a valid URL. If the URL is invalid, an error is thrown. This pipe is utilized in a controller to save an item into the database. Recently, I discovered that the pipe ...

jQuery registers the enter event, but does not proceed to trigger the enter action

Hey there, I've been experimenting with jQuery to capture the enter event. Something peculiar is happening though - after pressing enter in the text area, an alert pops up but the text gets entered only after that. Despite trying various solutions, I ...

What is the best way to retrieve a variable within an AngularJS controller?

I am working with a binding parameter eid: '@' Inside my constructor, you will find the following method: this.$onInit = () => { console.log('eid: ', this.eid) } console.log("eid in another section: ", this.eid) Upon running t ...

When placed within a setInterval loop, the event.clientY variable becomes inaccessible

I am working on a script to move an element around a web page, and I have encountered a problem. Whenever I try to put it in a loop using setInterval while the mouse is down and moving, I receive an error message stating 'Uncaught TypeError: Cannot re ...

Color key in square shape for graph legend

I am looking for legend colors in square shape, but I don't want them to appear as square boxes on the graph. https://i.stack.imgur.com/Of0AM.png The squares are also showing up on the graph, which is not what I want. https://i.stack.imgur.com/Az9G ...

Utilizing d3.js to filter a dataset based on dropdown selection

I am working with a data set that contains country names as key attributes. When I select a country from a dropdown menu, I want to subset the dataset to display only values related to the selected country. However, my current code is only outputting [obje ...

How can I reset the DefaultValue of my Autocomplete input field after submitting?

Is there a way to reset the default value of my <TextField> inside Autocomplete after form submission? Even after submitting the form, the state of formValues remains as the default value. What can I do to fix this issue? I've attempted to mod ...

How can I display lowercase am/pm instead of uppercase AM/PM with angularjs date filtering?

Hi there, I'm a newcomer to AngularJS and I have a specific requirement. The server is sending me two dates: start_date and end_date. In the scenario where both dates are in 'pm', such as Sun 29 Jan 5.00 pm to Sun 29 Jan 6.00 pm, I would li ...

Having trouble with the automatic closing feature of Bootstrap drop down in React?

While using the drop button feature of Bootstrap, I have encountered a situation where it works fine when clicked on, but disabling it by clicking outside using autoClose='outside' does not seem to work as expected. When I click on my hamburge ...