javascript - NOT vs NULL with Local storage - javascript

So I want to get a variable from local storage. If it doesn't exist in local storage, then I want to create that variable. I was using if (x==null) to see if it existed, then I noticed if(!x) has the same result. Is it ok to use ! in this situation? I didn't know ! and null are the same here. Also when checking for null, should I use === or is == ok?
Here's two examples that give me the same results.
<script>
localStorage.clear();
a=localStorage.getItem('a');if (!a) a='hello';
alert(a);
x=localStorage.getItem('x');if (!x) x=0.7;
alert(x);
</script>
<script>
localStorage.clear();
a=localStorage.getItem('a');if (a==null) a='hello';
alert(a);
x=localStorage.getItem('x');if (x==null) x=0.7;
alert(x);
</script>

https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem
localStorage.getItem returns null if the key doesn't exist. So a === null would be the most specific check for if the key didn't exist. However, null is falsy in javascript. So you could reduce the check to this:
a = localStorage.getItem('a') || 'hello';
Which functions the same as your if with the not operator

Is not exactly the same... This !x is checking for a truthy value but anything between null, undefined, or even 0 will return false.
There is also a significant difference between == and === where == will try an automatic type conversion in order to check if the values are in some way compatible, but the === will check for an strict equality.
You can learn more about the JavaScript types and their interaction with the different operators in this link Values, Types, and Operators

Related

Why JavaScript null check doesn't working?

function readProperty(property)
{
console.log(localStorage[property]) //Alerts “null”
if(localStorage[property] == null)
{
console.log('Null chek')
return false;
}
return localStorage[property];
}
log outputs "null", but 'if()' doesn't work. I try with ===, its not work too. Help please.
UPD: Thanks everyone this change helped me if(localStorage[property] == 'null')
The keys and the values stored with localStorage are always in the
UTF-16 string format, which uses two bytes per character. As with
objects, integer keys are automatically converted to strings.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Try:
localStorage[property] === 'null'
Although: console.log(localStorage[property]) may report null, the actual value is undefined.
So, in your if statement, if you test against undefined, you'll get a match.
Better yet though, just test for the existence or non existence of a value with:
if(localStorage[property])... // Tests for any "truthy" value
or
if(!localStorage[property])... // Tests for any "falsey" value
Well, I don't know if you're trying to use the global localStorage or if it's a defined variable in your code.
If you're using the localStorage API, you should check if a key exists like this...
if (!localStorage.getItem("my-item")) {
console.log("item doesn't exist.");
}
The .getItem() method returns null when the key isn't defined so checking using ! or item !== null work.
.getItem() reference from MDN, https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem.
you have to get item from localStorage using getItem() function like that
if(!localStorage.getItem(property) || localStorage.getItem(property)===null){
// there is no item in localStorage with the property name
}

How to check if javascript variable exist, empty, array, (array but empty), undefined, object and so on

How to check if javascript variable exist, empty, array, (array but empty), undefined, object and so on
As mentioned in the title, I need a general overview how to check javascript variables in several cases without returning any error causing the browser to stop processing the pageload.
(now I have several issues in this topic.
For example IE stops with error in case _os is undefined, other browsers doesnt:
var _os = fbuser.orders;
var o =0;
var _ret = false;
for (var i = 0; i < _os.length; i++){
...
Furthermore i also need a guide of the proper using operators like == , ===.
As mentioned in the title, I need a general overview how to check
javascript variables in several cases without returning any error
causing the browser to stop processing the pageload.
To check whether or not variables is there, you can simply use typeof:
if (typeof _os != 'undefined'){
// your code
}
The typeof will also help you avoid var undefined error when checking that way.
Furthermore i also need a guide of the proper using operators like ==
, ===.
Both are equality operators. First one does loose comparison to check for values while latter not only checks value but also type of operands being compared.
Here is an example:
4 == "4" // true
4 === "4" // false because types are different eg number and string
With == javascript does type cohersion automatically. When you are sure about type and value of both operands, always use strict equality operator eg ===.
Generally, using typeof is problematic, you should ONLY use it to check whether or not a variables is present.
Read More at MDN:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof
The typeof operator is very helpful here:
typeof asdf
// "undefined"
Perhaps you want something like this in your case:
// Handle cases where `fbuser.orders` is not an array:
var _os = fbuser.orders || []

does ""===null?

when comparing string to see if it is empty, is there any difference between:
if($string==NULL){
//do work
}
and
if($string==""){
/do work
}
Just wondering beacuse I want to know which one is more effective in detecting blank input.
You're kind of asking several vaguely-related questions here. PHP and JavaScript aren't the same language, and you're referencing different operators in the question title and body. In any event:
PHP:
'' == null true
'' === null false
JavaScript:
'' == null false
'' === null false
You might want to consider these tests for general "did I get something in this string variable":
PHP:
if(!empty($string)) {
// do work
}
JavaScript:
if($string) {
// do work
}
Yes, there is a difference. Checking if $string==Null will actually check to see if the variable has been initialized at all, and $string=="" looks to see that the string actually exists, but that it just holds a 0-length string
To test in PHP:
<?php echo var_dump("" === NULL); ?>
To test in JavaScript:
console.log("" === null)
Both produce false, so you can't do that in either language.
Even if it worked, it is not obvious what you mean by comparing with null; this isn't C where it's constantly used for missing values. If you're going to get a string as input, comparing to the empty string is more clear.
I`am using empty() function in PHP. It is not depends on type of the variable. However, when comparing with "==" (not "==="!), NULL becomes empty string ("") when comparing to string.
does “”===null?
No.
Behold the power of testing... for javascript anyway.
alert("" === null);
In JavaScript, the answer is no. An empty string does not equal null, though both are falsey values.
Check the manual, "" is not identical to null because the former is a string and the latter is null, and === checks for equal types as well as equal values.
Take a look at this: http://php.net/manual/en/language.operators.comparison.php

Checking to see if a value exists in Javascript

How do I prevent a Javascript alert from firing if the alert value is undefined? In other words, something like this:
if (alert(message) != 'undefined') {
alert(message);
}
Use typeof:
if (typeof message !== 'undefined')
Don't put alert(message) into the if expression, otherwise you will execute alert (which we want to avoid before we know the type of message) and the return value (which is also undefined btw ;)) will be compared to undefined.
Update Clarification for !==:
This operator not only compares the value of two operands but also the type. That means no type coercion is done:
42 == "42" // true
42 === "42" // false
In this case it is not really necessary because we know that typeof always returns a string but it is good practice and if you use it thoroughly and consistently, it is more clear where you really want to have type coercion and where not.

Falsey values in JavaScript

I had an interesting interview question today that stumped me a little. I was asked about falsey values. So undefined, NaN, null, 0, and an empty string all evaluate to false. What is the reason this is useful to know in JavaScript? The only thing I can think of is instead of having to do this:
if (mystring === '' || mystring === undefined) { }
I can do this:
if (!mystring)
Is this the only useful application?
One dangerous issue of falsey values you have to be aware of is when checking the presence of a certain property.
Suppose you want to test for the availability of a new property; when this property can actually have a value of 0 or "", you can't simply check for its availability using
if (!someObject.someProperty)
/* incorrectly assume that someProperty is unavailable */
In this case, you must check for it being really present or not:
if (typeof someObject.someProperty == "undefined")
/* now it's really not available */
Also be aware that NaN isn't equal to anything, even not to itself (NaN != NaN).
There are two separate issues with 'falsey' values in JavaScript.
Firstly there is the official conversion scheme, which is what is returned by Boolean(x). This returns false when x is false or 0 or NaN or null or undefined or "" and true otherwise. This is the same behaviour as the
if (condition) {/*true path*/} else {/*false path*/}
that is, the false path is executed if Boolean(condition) would have returned false and the true path is executed otherwise. This behaviour is often used to check to see if a property is defined. However, doing that is not safe unless you are certain that the property would be an object or an array if it is defined. The safest way to test if a property is defined is to do
if (property != null) { /*property is defined*/}
which makes sure that the property is not null or undefined. If you only want to make sure the property is not undefined do
if (property !== undefined) { /*property is not undefined (but may be null)*/ }
(notice the extra = in !==).
Secondly, there are all the values that == false. This is everything that can be coerced to 0 (which is what false gets coerced to). This includes all the values that convert to false except NaN (which can't == false by virtue of it never == anything), null and undefined. But it also includes all objects that when converted to a string and then converted to a number are equal to 0. For example, this includes everything that when converted to a string is either the empty string "" or "0" or "-0" or "+0" or "0x00" or "000" or "0e0" or "0.0000"...., for example,
({toString: function() {return "-00.0e000";}}) == false
is true. Interestingly, this includes the empty array, and any nesting of arrays containing only a single other item that returns an empty or 0 string since arrays rendered as strings show only the contents without the surrounding brackets. That is,
[[[[0]]]] == false; // Because [[[[0]]]].toString() === "0"
[] == false;
[[[""]]] == false;
["0"] == false;
[[({toString: function() {return "0";}})]] == false;
The full algorithm for calculating == false is described here.
The reason this matters is because it can lead to subtle, difficult to find bugs if you don't understand most of these rules. Most important takeaways are probably how the if (condition) works and that using === avoids most of the other crazy stuff.
It's important to understand how this works in JS, so you're not surprised. Not necessarily just what is falsey, but what is truthy and how they compare to each other.
One example is that '0' is considered equal to 0 with ==, but it is not equal to '' - though 0 is. JavaScript comparison isn't always transitive.
So this means that just because (foo==bar && bar==fizz) is true, (foo==fizz) is not always true. To go with the above example, '0'==0, and 0=='', but '0'!='' - because you're comparing strings in the latter instance, so they are compared as strings and not coerced to numbers.
It is important to know that 0 evaluates to false to prevent doing things like:
if(str.indexOf('foo'))
It's useful to detect if a browser is has specific predefined objects:
if(!!navigator.geolocation){
// executes if the browser has geolocation support
}
if(!!document.createElement('canvas').getContext){
// executes if the browser supports <canvas>
}
Explanation: navigator.geolocation is an object or undefined. In the case it's an object !navigator.geolocation will return false, if it's undefined it'll return true. So, to check if a browser has geolocation enabled, you want to 'flip' the boolean once more, by adding another !.
They're also useful for setting default values...
function foo(bar){
alert(bar || "default");
}
I know a lot of people try to do
if (typeof(foo) === "undefined"){}
to get around falsiness, but that's got its own problems because
typeof(null) === "object"
for some reason

Categories