Unusual glitch in JavaScript

Take a look at the code below: html...

 <pre id='output'></pre>

html...

JS

 function log(text) {
    var div = document.getElementById('output');
    div.innerHTML += text + '\n';
 }

function foo() {

    var browser=0;
    if(navigator.appName.toUpperCase()=="MICROSOFT INTERNET EXPLORER")
        browser=1;
    else
    if(navigator.appName.toUpperCase()=="NETSCAPE")
        browser=2;
    log ('browser:'+browser);
    if (browser==1)
    {
        log ('IE');
    }
    if (browser==2);
    {
        log ('Chrome');
    }

    if (browser==0);
    {
            log ('Could not determine broweser type');
            return;
    }
  }

When I try this in IE, here is the output: browser:1 ie not supported Chrome extension will be loaded Could not determine broweser type

When testing on Chrome, the output shows: browser:2 Chrome extension will be loaded Could not determine broweser type


Why does the browser have multiple values in this scenario? Thanks, Nir

Answer №1

There is a common error present in your code that beginners often make

The presence of ; at the end of the if statement if (browser==0); prematurely ends the conditional, resulting in the following block of code executing regardless of the value of browser

Answer №2

It is advisable to avoid placing a ; at the end of an if statement like this one: if (browser==2);

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

The error message "TypeError: Cannot read properties of undefined (reading 'prototype')" is encountered in Next.js 13 when trying to access the prototype of an

I tried to integrate the downshift library into my project. However, when I attempted to use a basic example from the GitHub repository here, I encountered an error. Current versions: Next.js: 13.2.4 React: 18.2.0 Upon further investigation, it seems lik ...

Searching for a way to programmatically uncheck a radio button based on a specific condition

Is there a way for me to deselect the radio button under specific conditions? <input type="radio" name="XXX" value="add" data-ng-model="XXX"/>Add I am looking to have this radio button unchecked when certain conditions are met, like so: <input ...

Retrieve custom tailwind overrides from an endpoint after the build process is complete

Currently, I am working on a Next.js project utilizing Tailwind CSS. During the build process, I load in a default configuration, but I also need to wait for an API response to retrieve custom styles from an endpoint. Below is my current setup, but it see ...

React - warning - Avoid using <Link> outside of a <Router> context

Warning: Invariant failed: It is not recommended to use <Link> outside of a <Router> Encountering this while attempting to write a test for a component where test("renders post list div ", () => { const posts = [ { created: ...

The $.inArray() function returns a value of false or -1, despite the fact that the variable

My goal is to verify that my currentMedia variable (which exists in the DOM) can be located within my array media, and then return the index i, which should be 0 instead of -1. When I execute console.log(media[0]); and console.log(currentMedia);, the outc ...

Struggle encountered in obtaining the value of a DatePicker in VueJS

Currently, I am utilizing the vue-hotel-datepicker component for managing dates. It is functioning well; however, I am encountering an issue when attempting to retrieve the updated date value in my JavaScript code. Any advice or assistance on how to captur ...

Transferring information between pages through ajax communication

I am working with two pages named testing.php and submission.php. My goal is to send data from testing.php to be displayed on submission.php. For example, when a user clicks on test1, they should be directed to submission.php where I want to display the te ...

What is the process for retrieving wallet transactions using Alchemy websockets?

I am trying to retrieve all new transactions from a specific wallet using the code provided. However, I am encountering an issue when using the function tx["transaction"]["from"] to filter transactions based on the specified wallet. I am utilizing Alchemy ...

Accessing a variable outside of the function call in AngularJS is not possible

After starting to tackle AngularJS, I've encountered an issue that's been plaguing me. It seems like I'm unable to access the data returned by $http.get() outside of the method call. Here's a look at the code snippet: (function(){ ...

Ensure that only one menu with a specific class is open at any given time

My goal is to ensure that both menus cannot be open simultaneously. The desired behavior is as follows: When one menu is already open and you click on another, the first one should automatically close. For a better understanding of what I am trying to achi ...

What is causing the jQuery functions to not be executed in sequence?

Whenever I click the Start button, my function is supposed to run a cycle for 10 iterations. Each iteration generates a number between 1 and 7, which then triggers a series of functions on different objects. The problem is that these functions are not runn ...

Get selectize.js to display only options that begin with the user's input

Using selectize.js, my current setup looks like this: https://i.sstatic.net/EqhF8.png Instead of only showing words that start with 'arm', it displays words or options containing 'arm' as a substring elsewhere. I want to modify the f ...

What could be the reason for the lack of rerendering in this child component?

Currently, I'm delving into ReactJS and attempting to grasp how child component rendering functions. To illustrate, consider the following example: var externalCounterVar = 10 class Counter extends React.Component { constructor(props){ super(pr ...

Introducing HTML elements into pre-existing web pages

My interest lies in the idea of injecting HTML into existing web pages for enhanced functionality. Specifically, I am exploring the concept of creating a more efficient bookmarking system. As someone new to web development, I am unsure of how to achieve th ...

What is the reasoning behind jQuery UI employing CSS classes as opposed to pseudo-classes?

In this detailed explanation found on this website, it is discussed why jQuery UI uses CSS classes like .ui-state-active that are applied through JavaScript, rather than utilizing existing CSS pseudo-classes like :active. What is the reasoning behind thi ...

Discover exclusive outcomes within the Dropdown selection

I'm populating a select dropdown dynamically from a JSON array of objects and would like to filter by tag. The issue I'm facing is that I am getting duplicate tags because multiple results can have the same tag. How can I ensure that only unique ...

Bootstrap table styling fails to be applied to dynamically generated tables via JavaScript

Hey there, I'm diving into the world of website development for the first time, just getting started a couple of days back. Although I have some experience with Python and C# programming, I'm facing challenges in generating an HTML table using J ...

Enter the API Key for the Google Matrix API in Javascript to access and retrieve usage data

I have successfully implemented the Google Matrix API to retrieve time and distance information from location A to location B. var origins = [Task.getItem("Y") + "," + Task.getItem("X")]; var destinations = [LAT + "," + LNG]; var ...

What's the best way to remove all &#160; siblings from a JSON string using JavaScript?

Is there a way to remove all instances of "&#160;" in a JSON string? { "Cat": "laps&#160;milk", "Dog": "Woofs&#160;at&#160;Postman", "Bird": "Jumps&#160;over&#160;the&#160;river", "I": "Want&#160;to&#160;learn&a ...

Change the defaultValue of a React component following a successful request

In my project, I am dealing with a DropDown component from a separate library that renders various options. The component supports an array of objects as its source and setting a default value is straightforward when the list is static. However, I'm f ...