If (the variable myVar does not equal "undefined")

I was trying to determine if a value had been assigned to an item in localWebstorage. My initial approach involved the following code snippet:

    //Change localStorage.intervalSetting from 'Undefined' to 'Never'
    function initialIntervalSetting() {
        var getValue = localStorage.intervalSetting;
        if (typeof getValue === undefined) {
            localStorage.intervalSetting = "option1";
            alert("Changed the localWebstorage item from undefined to 'option1'");
        }
        else {
            alert("JavaScript believes that the item is not undefined");
        }
    }

Even though this method did not yield the desired results, I stumbled upon a valuable discussion on the matter at: How to check for "undefined" in JavaScript?. A user shared the following solution:

        if (typeof getValue != "undefined") {
            localStorage.intervalSetting = "option1";
        }

The advice given was to use != instead of ===. Surprisingly, making this change solved the issue. But why does it work? Shouldn't (getValue != "undefined") evaluate to false since != signifies NOT EQUAL??

Answer â„–1

Looking at your code, I noticed that you were comparing the type of getValue with the literal value undefined. However, since typeof returns a string, it is important to compare this value with the string "undefined".

You can either use:

if (typeof getValue !== "undefined")

or

if (getValue !== undefined)

to achieve the desired outcome.

Answer â„–2

In my opinion, it's advisable to utilize a "truthy" validation. This technique helps in verifying whether the object is null or undefined. You can achieve this by simply checking your getValue.

if(getValue) {
    // not undefined
}

For further insights, here is another valuable discussion on the topic: Understanding JavaScript Truthy and Falsy

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

Filtering an array within an array based on user input

I am currently facing a challenge in filtering the child elements of an array. I am puzzled on how to specifically target children elements. So far, my filter is only functioning at the top level. Array: options: [ {name: 'Ð’Ñ‹Ñ…Ð ...

Generate or acquire basic data types based on function behavior using TypeScript

Imagine you have an object like this: const exampleObject = { key1: {id: 1}, key2: {id: 1}, key3: {id: 1}, key4: {id: 1}, .... } and a function that transforms the object to: const transformedObject = { key1: 1, key2: 1, key3: 1, ...

Receiving blank response when trying to access server variable on the client side

Query: On the server side, I set the value of SessionData(EmployeeID) = "12345", which is first executed during page_load. Later, on the client side: function getEmployeeId() { return "<%# SessionData("EmployeeID")%>"; } When I use th ...

Error message received while converting webm video to images using Kagami/ffmpeg.js: Unable to locate an appropriate output format for '%04d.jpg'

These are the current versions: node v12.9.1, npm 6.10.2, [email protected] Repository: https://github.com/Kagami/ffmpeg.js The code in decode.js looks like this: const fs = require('fs'); const ffmpeg = require('ffmpeg.js'); c ...

What is the best way to send data back to a separate JavaScript file in ExtJS when working with records in a

I'm currently working on implementing a pop-up editing feature on a grid in extjs4. Progress so far includes successfully transferring the grid record to a popup panel located in a separate JavaScript file using the following code: handler: function( ...

Avoid having Vue CLI delete all files in the dist folder

As I work on my Vue project, I am facing a challenge in syncing the dist folder with Git. Previously, this process ran smoothly when using webpack. However, after transitioning to @vue/cli and creating my project with vue create myProject instead of vue in ...

Refreshing a single HTML element in ASP.NET MVC - the simple way!

Recently, I put together an image gallery using the unite gallery jquery plugin and now I want to change up the images it displays. My plan is to have a button labeled "art" that, when clicked, triggers a function to update the directory path and load ne ...

Eliminate redundant elements during the process of arranging an array

I have a collection of objects in an array that needs to be sorted and have duplicates removed based on specific values within each object. Currently, I am using two separate loops (not nested) - one for sorting and another for removing duplicates. Is ther ...

Ways to track the number of distinct users visiting a webpage

I am trying to find a reliable method to track unique visitors on my webpage using JavaScript (ReactJS + NodeJS(Express). I want the system to identify each user when they load the page and add their data to the database if they are unique. So far, I have ...

Loading routes directly in Angular 2

I've encountered an issue with my Angular application where navigating to certain routes results in an error. The two routes in question are: http://localhost:8080/ /* Landing page */ http://localhost:8080/details/:id /* Result page */ For instance, ...

Exploring the Functionality of the Back Button in JavaScript

I am currently working on a website and running into an issue with the tab-panes on one of my pages. Whenever a user clicks on a tab-pane, it updates the browser's history, which interferes with the back button functionality in a way that is not ideal ...

"Counting Down with PHP and jQuery : A Dynamic

I recently received a tutorial on how to combine PHP date function with jQuery. I am looking to modify the script so that when a specific time is reached, it redirects to another page. I attempted to make the changes myself but encountered some issues. Y ...

Can JavaScript be accessed from a background thread in a Cordova Android plugin?

In my Cordova application, I am utilizing a native plugin on Android (with plans for other platforms in the future). The plugin is loaded when the application starts (<param name="onload" value="true" /> in plugin.xml) and the native code performs t ...

Strategies for consistently receiving updates of Iframe content body within a react useEffect hook

When loading html into an iframe using srcDoc with the sandbox="allow-same-origin", I face a challenge. Despite the content displaying properly, the property frameRef.contentDocument.body.innerHTML remains empty. This issue persists even after s ...

AngularJS provides a way to create opening pages with clickable buttons for a

I'm struggling to implement buttons that switch ons-templates when clicked. I've been following this example as a reference: Here's the code snippet I've been working on, but it just won't cooperate: <!doctype html> &l ...

What is the method to assign multiple values to ng-disabled in AngularJS?

Is there a way to assign multiple values for ng-disabled in AngularJS? The issue I'm facing is demonstrated in the following JS Fiddle: http://jsfiddle.net/FJf4v/10/ <div ng-app> <div ng-controller="myCnt"> <h3>A ->> ...

Trigger an AJAX request by clicking a button using PHP

I've seen this question asked multiple times, but none of the answers seem to relate to my specific situation. I have a button that when clicked, should call a JavaScript function, passing it a PHP variable. The AJAX will then send that variable to a ...

Error encountered when attempting to pass more than one value to a function due to syntax

My goal is to call a function, but I am encountering issues with properly escaping values and passing them correctly. The current setup looks like this: function selectdone(sel, title_id, status_type) { ... } $(function() { $("td.status-updates").click ...

Is there a way to conceal the loading screen until the website has completely loaded?

I've been working on my personal portfolio/website and encountered a bug that I can't seem to fix on my own. The issue is with the logo (aa) and text under it showing even after the content page has fully loaded, taking around 3 seconds to hide. ...

The conditional statement for multiplying in JavaScript

I have a JavaScript function that selects a report number based on multiple parameters (2 checkboxes, 3 dropdown fields), and the current implementation involves a complex conditional statement as shown below: switch(ReportNumDrop) { case 0 ...