How can I check for null values in JavaScript? I wrote the code below but it didn't work.
if (pass == null || cpass == null || email == null || cemail == null || user == null) {
alert("fill all columns");
return false;
}
And how can I find errors in my JavaScript programs?
JavaScript is very flexible with regards to checking for "null" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:
if(!pass || !cpass || !email || !cemail || !user){
Which will check for empty strings (""), null, undefined, false and the numbers 0 and NaN.
Please note that if you are specifically checking for numbers, it is a common mistake to miss 0 with this method, and num !== 0 is preferred (or num !== -1 or ~num (hacky code that also checks against -1)) for functions that return -1, e.g. indexOf).
To check for null SPECIFICALLY you would use this:
if (variable === null)
This test will ONLY pass for null and will not pass for "", undefined, false, 0, or NaN.
Additionally, I've provided absolute checks for each "false-like" value (one that would return true for !variable).
Note, for some of the absolute checks, you will need to implement use of the absolutely equals: === and typeof.
I've created a JSFiddle here to show all of the individual tests working
Here is the output of each check:
Null Test:
if (variable === null)
- variable = ""; (false) typeof variable = string
- variable = null; (true) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Empty String Test:
if (variable === '')
- variable = ''; (true) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Undefined Test:
if (typeof variable == "undefined")
-- or --
if (variable === undefined)
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (true) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
False Test:
if (variable === false)
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (true) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Zero Test:
if (variable === 0)
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (true) typeof variable = number
- variable = NaN; (false) typeof variable = number
NaN Test:
if (typeof variable == 'number' && !parseFloat(variable) && variable !== 0)
-- or --
if (isNaN(variable))
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (true) typeof variable = number
As you can see, it's a little more difficult to test against NaN;
just replace the == with === in all places.
== is a loose or abstract equality comparison
=== is a strict equality comparison
See the MDN article on Equality comparisons and sameness for more detail.
You can check if some value is null as follows
[pass,cpass,email,cemail,user].some(x=> x===null)
let pass=1;
let cpass=2;
let email=3;
let cemail=null;
let user=5;
if ( [pass,cpass,email,cemail,user].some(x=> x===null) ) {
alert("fill all columns");
//return false;
}
BONUS: Why === is more clear than == (source)
a == b
a === b
Strict equality operator:-
We can check null by ===
if ( value === null ){
}
Just by using if
if( value ) {
}
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
false
0
At first sight, it looks like a simple trade-off between coverage and strictness.
== covers multiple values, can handle more scenarios in less code.
=== is the most strict, and that makes it predictable.
Predictability always wins, and that appears to make === a one-fits-all solution.
But it is wrong. Even though === is predictable, it does not always result in predictable code, because it overlooks scenarios.
const options = { };
if (options.callback !== null) {
options.callback(); // error --> callback is undefined.
}
In general == does a more predictable job for null checks:
In general, null and undefined both mean the same thing: "something's missing". For predictability, you need to check both values. And then == null does a perfect job, because it covers exactly those 2 values. (i.e. == null is equivalent to === null && === undefined)
In exceptional cases you do want a clear distinction between null and undefined. And in those cases you're better of with a strict === undefined or === null. (e.g. a distinction between missing/ignore/skip and empty/clear/remove.) But it is rare.
It is not only rare, it's something to avoid. You can't store undefined in a traditional database. And you shouldn't rely on undefined values in your API designs neither, due to interopability reasons. But even when you don't make a distinction at all, you can't assume that undefined won't happen. People all around us indirectly take actions that generalize null/undefined (which is why questions like this are closed as "opinionated".).
So, to get back to your question. There's nothing wrong with using == null. It does exactly what it should do.
// FIX 1 --> yes === is very explicit
const options = { };
if (options.callback !== null &&
options.callback !== undefined) {
options.callback();
}
// FIX 2 --> but == covers both
const options = { };
if (options.callback != null) {
options.callback();
}
// FIX 3 --> optional chaining also covers both.
const options = { };
options.callback?.();
Improvement over the accepted answer by explicitly checking for null but with a simplified syntax:
if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
// your code here ...
}
// Test
let pass=1, cpass=1, email=1, cemail=1, user=1; // just to test
if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
// your code here ...
console.log ("Yayy! None of them are null");
} else {
console.log ("Oops! At-lease one of them is null");
}
Firstly, you have a return statement without a function body. Chances are that that will throw an error.
A cleaner way to do your check would be to simply use the ! operator:
if (!pass || !cpass || !email || !cemail || !user) {
alert("fill all columns");
}
you can use try catch finally
try {
document.getElementById("mydiv").innerHTML = 'Success' //assuming "mydiv" is undefined
} catch (e) {
if (e.name.toString() == "TypeError") //evals to true in this case
//do something
} finally {}
you can also throw your own errors. See this.
In JavaScript, no string is equal to null.
Maybe you expected pass == null to be true when pass is an empty string because you're aware that the loose equality operator == performs certain kinds of type coercion.
For example, this expression is true:
'' == 0
In contrast, the strict equality operator === says that this is false:
'' === 0
Given that '' and 0 are loosely equal, you might reasonably conjecture that '' and null are loosely equal. However, they are not.
This expression is false:
'' == null
The result of comparing any string to null is false. Therefore, pass == null and all your other tests are always false, and the user never gets the alert.
To fix your code, compare each value to the empty string:
pass === ''
If you're certain that pass is a string, pass == '' will also work because only an empty string is loosely equal to the empty string. On the other hand, some experts say that it's a good practice to always use strict equality in JavaScript unless you specifically want to do the type coercion that the loose equality operator performs.
If you want to know what pairs of values are loosely equal, see the table "Sameness comparisons" in the Mozilla article on this topic.
to check for undefined and null in javascript you need just to write the following :
if (!var) {
console.log("var IS null or undefined");
} else {
console.log("var is NOT null or undefined");
}
Actually I think you may need to use
if (value !== null && value !== undefined)
because if you use if (value) you may also filter 0 or false values.
Consider these two functions:
const firstTest = value => {
if (value) {
console.log('passed');
} else {
console.log('failed');
}
}
const secondTest = value => {
if (value !== null && value !== undefined) {
console.log('passed');
} else {
console.log('failed');
}
}
firstTest(0); // result: failed
secondTest(0); // result: passed
firstTest(false); // result: failed
secondTest(false); // result: passed
firstTest(''); // result: failed
secondTest(''); // result: passed
firstTest(null); // result: failed
secondTest(null); // result: failed
firstTest(undefined); // result: failed
secondTest(undefined); // result: failed
In my situation, I just needed to check if the value is null and undefined and I did not want to filter 0 or false or '' values. so I used the second test, but you may need to filter them too which may cause you to use first test.
This is a comment on WebWanderer's solution regarding checking for NaN (I don't have enough rep yet to leave a formal comment). The solution reads as
if(!parseInt(variable) && variable != 0 && typeof variable === "number")
but this will fail for rational numbers which would round to 0, such as variable = 0.1. A better test would be:
if(isNaN(variable) && typeof variable === "number")
You can use lodash module to check value is null or undefined
_.isNil(value)
Example
country= "Abc"
_.isNil(country)
//false
state= null
_.isNil(state)
//true
city= undefined
_.isNil(state)
//true
pin= true
_.isNil(pin)
// false
Reference link: https://lodash.com/docs/#isNil
AFAIK in JAVASCRIPT when a variable is declared but has not assigned value, its type is undefined. so we can check variable even if it would be an object holding some instance in place of value.
create a helper method for checking nullity that returns true and use it in your API.
helper function to check if variable is empty:
function isEmpty(item){
if(item){
return false;
}else{
return true;
}
}
try-catch exceptional API call:
try {
var pass, cpass, email, cemail, user; // only declared but contains nothing.
// parametrs checking
if(isEmpty(pass) || isEmpty(cpass) || isEmpty(email) || isEmpty(cemail) || isEmpty(user)){
console.log("One or More of these parameter contains no vlaue. [pass] and-or [cpass] and-or [email] and-or [cemail] and-or [user]");
}else{
// do stuff
}
} catch (e) {
if (e instanceof ReferenceError) {
console.log(e.message); // debugging purpose
return true;
} else {
console.log(e.message); // debugging purpose
return true;
}
}
some test cases:
var item = ""; // isEmpty? true
var item = " "; // isEmpty? false
var item; // isEmpty? true
var item = 0; // isEmpty? true
var item = 1; // isEmpty? false
var item = "AAAAA"; // isEmpty? false
var item = NaN; // isEmpty? true
var item = null; // isEmpty? true
var item = undefined; // isEmpty? true
console.log("isEmpty? "+isEmpty(item));
The 'Object.is()' method can be used to determine if two values are the same value. So, you can use it to check whether the object is null or not.
Check for null values
let testA = null; //null
//console.log(Object.is(testA, null)); //true //null === null
if(Object.is(testA, null)) {
console.log("This is a Null Value");
}
Output:
This is a Null Value
let x = null;
if (x === null) {
console.log("x is null");
}
Output:
x is null
Check for undefined values (A variable has been declared, but a value has not been assigned.)
let testB; //undefined
//console.log(Object.is(testB, undefined)); //true //undefined === undefined
if(Object.is(testB, undefined)) {
console.log("This is an undefined Value");
}
Output:
This is an undefined Value
If the object has not been declared, this cannot be used. As an alternative, you may try this:
if (typeof x === "undefined") {
console.log("x is undefined");
}
Output:
The value is either undefined or null
Mozilla Object.is():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
I found a another way to test if the value is null:
if(variable >= 0 && typeof variable === "object")
null acts as a number and object at the same time. Comparing null >= 0 or null <= 0 results in true. Comparing null === 0 or null > 0 or null < 0 will result in false. But as null is also an object we can detect it as a null.
I made a more complex function natureof witch will do better than typeof and can be told what types to include or keep grouped
/* function natureof(variable, [included types])
included types are
null - null will result in "undefined" or if included, will result in "null"
NaN - NaN will result in "undefined" or if included, will result in "NaN"
-infinity - will separate negative -Inifity from "Infinity"
number - will split number into "int" or "double"
array - will separate "array" from "object"
empty - empty "string" will result in "empty" or
empty=undefined - empty "string" will result in "undefined"
*/
function natureof(v, ...types){
/*null*/ if(v === null) return types.includes('null') ? "null" : "undefined";
/*NaN*/ if(typeof v == "number") return (isNaN(v)) ? types.includes('NaN') ? "NaN" : "undefined" :
/*-infinity*/ (v+1 === v) ? (types.includes('-infinity') && v === Number.NEGATIVE_INFINITY) ? "-infinity" : "infinity" :
/*number*/ (types.includes('number')) ? (Number.isInteger(v)) ? "int" : "double" : "number";
/*array*/ if(typeof v == "object") return (types.includes('array') && Array.isArray(v)) ? "array" : "object";
/*empty*/ if(typeof v == "string") return (v == "") ? types.includes('empty') ? "empty" :
/*empty=undefined*/ types.includes('empty=undefined') ? "undefined" : "string" : "string";
else return typeof v
}
// DEMO
let types = [null, "", "string", undefined, NaN, Infinity, -Infinity, false, "false", true, "true", 0, 1, -1, 0.1, "test", {var:1}, [1,2], {0: 1, 1: 2, length: 2}]
for(i in types){
console.log("natureof ", types[i], " = ", natureof(types[i], "null", "NaN", "-infinity", "number", "array", "empty=undefined"))
}
I made this very simple function that works wonders:
function safeOrZero(route) {
try {
Function(`return (${route})`)();
} catch (error) {
return 0;
}
return Function(`return (${route})`)();
}
The route is whatever chain of values that can blow up. I use it for jQuery/cheerio and objects and such.
Examples 1: a simple object such as this const testObj = {items: [{ val: 'haya' }, { val: null }, { val: 'hum!' }];};.
But it could be a very large object that we haven't even made. So I pass it through:
let value1 = testobj.items[2].val; // "hum!"
let value2 = testobj.items[3].val; // Uncaught TypeError: Cannot read property 'val' of undefined
let svalue1 = safeOrZero(`testobj.items[2].val`) // "hum!"
let svalue2 = safeOrZero(`testobj.items[3].val`) // 0
Of course if you prefer you can use null or 'No value'... Whatever suit your needs.
Usually a DOM query or a jQuery selector may throw an error if it's not found. But using something like:
const bookLink = safeOrZero($('span.guidebook > a')[0].href);
if(bookLink){
[...]
}
What about optional check with operator ?
for example:
// check mother for null or undefined and
// then if mother exist check her children also
// this 100% sure it support and valid in JS today.
// Apart of that C# have almost the same operator using the same way
if (mother?.children) {
}
else {
// it is null, undefined, etc...
}
Simple Solution for empty values:
function isEmpty(value) {
return (
value === null || value === undefined || value === '' ||
(Array.isArray(value) && value.length === 0) ||
(!(value instanceof Date) && typeof value === 'object' && Object.keys(value).length === 0)
);
}
This is a very non-human code. But works:
if((pass, cpass, email, cemail, user !== null)){
Just try it out and help the answer
Try this:
if (!variable && typeof variable === "object") {
// variable is null
}
This will not work in case of Boolean values coming from DB
for ex:
value = false
if(!value) {
// it will change all false values to not available
return "not available"
}
Checking error conditions:
// Typical API response data
let data = {
status: true,
user: [],
total: 0,
activity: {sports: 1}
}
// A flag that checks whether all conditions were met or not
var passed = true;
// Boolean check
if (data['status'] === undefined || data['status'] == false){
console.log("Undefined / no `status` data");
passed = false;
}
// Array/dict check
if (data['user'] === undefined || !data['user'].length){
console.log("Undefined / no `user` data");
passed = false;
}
// Checking a key in a dictionary
if (data['activity'] === undefined || data['activity']['time'] === undefined){
console.log("Undefined / no `time` data");
passed = false;
}
// Other values check
if (data['total'] === undefined || !data['total']){
console.log("Undefined / no `total` data");
passed = false;
}
// Passed all tests?
if (passed){
console.log("Passed all tests");
}
Related
I usually used if(value) to check value is null or not. But now I know false or 0 can be false. So I used if(value == null) but in this time, that null doesn't contain '' like.
I want to check that 0, false(have specific value) as true, and I want to check that '', undefined, null as false
What will be good way to check these values simply? Is there something to notice bout like this more?
Maybe this small helper function helps? Play with it in Stackblitz.
test();
test(42);
test(Infinity);
test(null);
test(0);
test({});
test(new Map());
function test(someValue) {
if (hasValue(someValue)) {
return console.log(`${someValue} is truthy`);
}
return console.log(`${someValue} is falsy`);
}
function hasValue(v) {
// Objects are always considered values
if (v instanceof Object) {
return true;
}
const falsies2Check = [false, 0, '', null, undefined, Infinity];
return falsies2Check.find(f => f === v || isNaN(v)) === undefined ? true : false;
}
Just check for the possible values normally.
const isFalsy = param => (param === null) || (param === "") || (typeof param === "undefined")
isFalsy(null); // true
isFalsy(0); // false
I want to check that 0, false(have specific value) as true.
if(!isFalsy(value))
Does anyone know how can I check whether a variable is a number or a string in JavaScript?
If you're dealing with literal notation, and not constructors, you can use typeof:.
typeof "Hello World"; // string
typeof 123; // number
If you're creating numbers and strings via a constructor, such as var foo = new String("foo"), you should keep in mind that typeof may return object for foo.
Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here),
var toString = Object.prototype.toString;
_.isString = function (obj) {
return toString.call(obj) == '[object String]';
}
This returns a boolean true for the following:
_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true
Best way to do that is using isNaN + type casting:
Updated all-in method:
function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }
The same using regex:
function isNumber(n) { return /^-?[\d.]+(?:e-?\d+)?$/.test(n); }
------------------------
isNumber('123'); // true
isNumber('123abc'); // false
isNumber(5); // true
isNumber('q345'); // false
isNumber(null); // false
isNumber(undefined); // false
isNumber(false); // false
isNumber(' '); // false
The best way I have found is to either check for a method on the string, i.e.:
if (x.substring) {
// do string thing
} else{
// do other thing
}
or if you want to do something with the number check for a number property,
if (x.toFixed) {
// do number thing
} else {
// do other thing
}
This is sort of like "duck typing", it's up to you which way makes the most sense. I don't have enough karma to comment, but typeof fails for boxed strings and numbers, i.e.:
alert(typeof new String('Hello World'));
alert(typeof new Number(5));
will alert "object".
Since ES2015 the correct way to check if a variable
holds a valid number is Number.isFinite(value)
Examples:
Number.isFinite(Infinity) // false
Number.isFinite(NaN) // false
Number.isFinite(-Infinity) // false
Number.isFinite(0) // true
Number.isFinite(2e64) // true
Number.isFinite('0') // false
Number.isFinite(null) // false
You're looking for isNaN():
console.log(!isNaN(123));
console.log(!isNaN(-1.23));
console.log(!isNaN(5-2));
console.log(!isNaN(0));
console.log(!isNaN("0"));
console.log(!isNaN("2"));
console.log(!isNaN("Hello"));
console.log(!isNaN("2005/12/12"));
See JavaScript isNaN() Function at MDN.
Check if the value is a string literal or String object:
function isString(o) {
return typeof o == "string" || (typeof o == "object" && o.constructor === String);
}
Unit test:
function assertTrue(value, message) {
if (!value) {
alert("Assertion error: " + message);
}
}
function assertFalse(value, message)
{
assertTrue(!value, message);
}
assertTrue(isString("string literal"), "number literal");
assertTrue(isString(new String("String object")), "String object");
assertFalse(isString(1), "number literal");
assertFalse(isString(true), "boolean literal");
assertFalse(isString({}), "object");
Checking for a number is similar:
function isNumber(o) {
return typeof o == "number" || (typeof o == "object" && o.constructor === Number);
}
Try this,
<script>
var regInteger = /^-?\d+$/;
function isInteger( str ) {
return regInteger.test( str );
}
if(isInteger("1a11")) {
console.log( 'Integer' );
} else {
console.log( 'Non Integer' );
}
</script>
Best way to do this:
function isNumber(num) {
return (typeof num == 'string' || typeof num == 'number') && !isNaN(num - 0) && num !== '';
};
This satisfies the following test cases:
assertEquals("ISNUMBER-True: 0", true, isNumber(0));
assertEquals("ISNUMBER-True: 1", true, isNumber(-1));
assertEquals("ISNUMBER-True: 2", true, isNumber(-500));
assertEquals("ISNUMBER-True: 3", true, isNumber(15000));
assertEquals("ISNUMBER-True: 4", true, isNumber(0.35));
assertEquals("ISNUMBER-True: 5", true, isNumber(-10.35));
assertEquals("ISNUMBER-True: 6", true, isNumber(2.534e25));
assertEquals("ISNUMBER-True: 7", true, isNumber('2.534e25'));
assertEquals("ISNUMBER-True: 8", true, isNumber('52334'));
assertEquals("ISNUMBER-True: 9", true, isNumber('-234'));
assertEquals("ISNUMBER-False: 0", false, isNumber(NaN));
assertEquals("ISNUMBER-False: 1", false, isNumber({}));
assertEquals("ISNUMBER-False: 2", false, isNumber([]));
assertEquals("ISNUMBER-False: 3", false, isNumber(''));
assertEquals("ISNUMBER-False: 4", false, isNumber('one'));
assertEquals("ISNUMBER-False: 5", false, isNumber(true));
assertEquals("ISNUMBER-False: 6", false, isNumber(false));
assertEquals("ISNUMBER-False: 7", false, isNumber());
assertEquals("ISNUMBER-False: 8", false, isNumber(undefined));
assertEquals("ISNUMBER-False: 9", false, isNumber(null));
//testing data types accurately in JavaScript (opposed to "typeof")
//from http://bonsaiden.github.com/JavaScript-Garden/
function is(type, obj) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
}
//basic usage
is('String', 'test'); // true
is('Array', true); // false
Or adapt it to return an unknown type:
function realTypeOf(obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
}
//usage
realTypeOf(999); // 'Number'
May 12, 2012 Update:
Full example at Javascript: A Better typeof.
Simple and thorough:
function isNumber(x) {
return parseFloat(x) == x
};
Test cases:
console.log('***TRUE CASES***');
console.log(isNumber(0));
console.log(isNumber(-1));
console.log(isNumber(-500));
console.log(isNumber(15000));
console.log(isNumber(0.35));
console.log(isNumber(-10.35));
console.log(isNumber(2.534e25));
console.log(isNumber('2.534e25'));
console.log(isNumber('52334'));
console.log(isNumber('-234'));
console.log(isNumber(Infinity));
console.log(isNumber(-Infinity));
console.log(isNumber('Infinity'));
console.log(isNumber('-Infinity'));
console.log('***FALSE CASES***');
console.log(isNumber(NaN));
console.log(isNumber({}));
console.log(isNumber([]));
console.log(isNumber(''));
console.log(isNumber('one'));
console.log(isNumber(true));
console.log(isNumber(false));
console.log(isNumber());
console.log(isNumber(undefined));
console.log(isNumber(null));
console.log(isNumber('-234aa'));
Here's an approach based on the idea of coercing the input to a number or string by adding zero or the null string, and then do a typed equality comparison.
function is_number(x) { return x === x+0; }
function is_string(x) { return x === x+""; }
For some unfathomable reason, x===x+0 seems to perform better than x===+x.
Are there any cases where this fails?
In the same vein:
function is_boolean(x) { return x === !!x; }
This appears to be mildly faster than either x===true || x===false or typeof x==="boolean" (and much faster than x===Boolean(x)).
Then there's also
function is_regexp(x) { return x === RegExp(x); }
All these depend on the existence of an "identity" operation particular to each type which can be applied to any value and reliably produce a value of the type in question. I cannot think of such an operation for dates.
For NaN, there is
function is_nan(x) { return x !== x;}
This is basically underscore's version, and as it stands is about four times faster than isNaN(), but the comments in the underscore source mention that "NaN is the only number that does not equal itself" and adds a check for _.isNumber. Why? What other objects would not equal themselves? Also, underscore uses x !== +x--but what difference could the + here make?
Then for the paranoid:
function is_undefined(x) { return x===[][0]; }
or this
function is_undefined(x) { return x===void(0); }
Or just use the invert of isNaN():
if(!isNaN(data))
do something with the number
else
it is a string
And yes, using jQuery's $.isNumeric() is more fun for the buck.
Can you just divide it by 1?
I assume the issue would be a string input like: "123ABG"
var Check = "123ABG"
if(Check == Check / 1)
{
alert("This IS a number \n")
}
else
{
alert("This is NOT a number \n")
}
Just a way I did it recently.
I think converting the var to a string decreases the performance, at least this test performed in the latest browsers shows so.
So if you care about performance, I would, I'd use this:
typeof str === "string" || str instanceof String
for checking if the variable is a string (even if you use var str = new String("foo"), str instanceof String would return true).
As for checking if it's a number I would go for the native: isNaN; function.
uh, how about just:
function IsString(obj) {
return obj !== undefined && obj != null && obj.toLowerCase !== undefined;
}
After further review many months later, this only guarantees obj is an object that has the method or property name toLowerCase defined. I am ashamed of my answer. Please see top-voted typeof one.
Beware that typeof NaN is... 'number'
typeof NaN === 'number'; // true
jQuery uses this:
function isNumber(obj) {
return !isNaN( parseFloat( obj ) ) && isFinite( obj );
}
This solution resolves many of the issues raised here!
This is by far the most reliable method I have used by far. I did not invent this, and cannot recall where I originally found it. But it works where other techniques fail:
// Begin public utility /getVarType/
// Returns 'Function', 'Object', 'Array',
// 'String', 'Number', 'Boolean', or 'Undefined'
getVarType = function ( data ){
if (undefined === data ){ return 'Undefined'; }
if (data === null ){ return 'Null'; }
return {}.toString.call(data).slice(8, -1);
};
// End public utility /getVarType/
Example of correctness
var str = new String();
console.warn( getVarType(str) ); // Reports "String"
console.warn( typeof str ); // Reports "object"
var num = new Number();
console.warn( getVarType(num) ); // Reports "Number"
console.warn( typeof num ); // Reports "object"
var list = [];
console.warn( getVarType( list ) ); // Reports "Array"
console.warn( typeof list ); // Reports "object"
Jsut an FYI, if you're using jQuery you have
$.isNumeric()
to handle this. More details on http://api.jquery.com/jQuery.isNumeric/
the best way i found which also thinks of positive and negative numbers is from :
O'Reilly Javascript and DHTML Cookbook :
function isNumber(elem) {
var str = elem.value;
var oneDecimal = false;
var oneChar = 0;
// make sure value hasn't cast to a number data type
str = str.toString( );
for (var i = 0; i < str.length; i++) {
oneChar = str.charAt(i).charCodeAt(0);
// OK for minus sign as first character
if (oneChar = = 45) {
if (i = = 0) {
continue;
} else {
alert("Only the first character may be a minus sign.");
return false;
}
}
// OK for one decimal point
if (oneChar = = 46) {
if (!oneDecimal) {
oneDecimal = true;
continue;
} else {
alert("Only one decimal is allowed in a number.");
return false;
}
}
// characters outside of 0 through 9 not OK
if (oneChar < 48 || oneChar > 57) {
alert("Enter only numbers into the field.");
return false;
}
}
return true;
}
Errr? Just use regular expressions! :)
function isInteger(val) {
return val.match(/^[0-9]$/)
}
function isFloat(val) {
return val.match(/^[0-9]*/\.[0-9]+$/)
}
since a string as '1234' with typeof will show 'string', and the inverse cannot ever happen (typeof 123 will always be number), the best is to use a simple regex /^\-?\d+$/.test(var). Or a more advanced to match floats, integers and negative numbers, /^[\-\+]?[\d]+\.?(\d+)?$/
The important side of .test is that it WON'T throw an exception if the var isn't an string, the value can be anything.
var val, regex = /^[\-\+]?[\d]+\.?(\d+)?$/;
regex.test(val) // false
val = '1234';
regex.test(val) // true
val = '-213';
regex.test(val) // true
val = '-213.2312';
regex.test(val) // true
val = '+213.2312';
regex.test(val) // true
val = 123;
regex.test(val) // true
val = new Number(123);
regex.test(val) // true
val = new String('123');
regex.test(val) // true
val = '1234e';
regex.test(val) // false
val = {};
regex.test(val) // false
val = false;
regex.test(val) // false
regex.test(undefined) // false
regex.test(null) // false
regex.test(window) // false
regex.test(document) // false
If you are looking for the real type, then typeof alone will do.
#BitOfUniverse's answer is good, and I come up with a new way:
function isNum(n) {
return !isNaN(n/0);
}
isNum('') // false
isNum(2) // true
isNum('2k') // false
isNum('2') //true
I know 0 can't be dividend, but here the function works perfectly.
typeof works very well for me in most case. You can try using an if statement
if(typeof x === 'string' || typeof x === 'number') {
console.log("Your statement");
}
where x is any variable name of your choice
Type checking
You can check the type of variable by using typeof operator:
typeof variable
Value checking
The code below returns true for numbers and false for anything else:
!isNaN(+variable);
XOR operation can be used to detect number or string.
number ^ 0 will always give the same number as output and string ^ 0 will give 0 as output.
Example:
1) 2 ^ 0 = 2
2) '2' ^ 0 = 2
3) 'Str' ^ 0 = 0
function IsNumeric(num) {
return ((num >=0 || num < 0)&& (parseInt(num)==num) );
}
For detecting numbers, the following passage from JavaScript: The Good Parts by Douglas Crockford is relevant:
The isFinite function is the best way of determining whether a value can be used as a number because it rejects NaN and Infinity . Unfortunately, isFinite will attempt to convert its operand to a number, so it is not a good test if a value is not actually a number. You may want to define your own isNumber function:
var isNumber = function isNumber(value) { return typeof value === 'number' &&
isFinite(value);
};
Simply use
myVar.constructor == String
or
myVar.constructor == Number
if you want to handle strings defined as objects or literals and saves you don't want to use a helper function.
Very late to the party; however, the following has always worked well for me when I want to check whether some input is either a string or a number in one shot.
return !!Object.prototype.toString.call(input).match(/\[object (String|Number)\]/);
At the moment I have an if condition like this:
if(
(variable != null && variable != '' && !variable) &&
(variable2 != null && variable2 != '' && !variable2) &&
(variable3 != null && variable3 != '' && !variable3)
//etc..
)
I need to use it to check if multiple variables have value (were not left out), but I feel like this is a messy solution and wanted to ask if there is a more efficient way? Maybe additional checks as well?
Because if(variable) ignores any falsy value, this will work for you
if(variable && variable2 && variable3)
The following values are always falsy in JS:
false.
0 (zero)
"" (empty string)
null.
undefined.
NaN (a special Number value meaning Not-a-Number!)
Update:-
If there is a case when you want to execute if block even if the value is 0, you have to add an extra check saying either 0 or some other value.
if((variable || variable === 0) && (variable2 || variable2 === 0) && (variable3 || variable3 === 0))
If IE support matter to you (IE9+), you could use the following solution.
You could use Array.prototype.some(). In a nutshell this array method will return true if any of the elements in the array meet a certain condition. This condition will be el == null this will work because undefined == null and null == null both resolve in true
See this stackoverflow post for more information
Which equals operator (== vs ===) should be used in JavaScript comparisons?
Array.prototype.some() browser support (93% time of writing) here
var a = 5;
var b = null;
var c = undefined;
if ( [a,b,c].some(el => el == null) ) {
console.log("You f*d up")
}
Or you could use Array.prototype.includes()
See support (93% time of writing) here here
var a = 5;
var b = null;
var c = undefined;
if ( [a,b,c].includes(undefined) || [a,b,c].includes(null) ) {
console.log("You f*d up")
}
If you want good browser support and you don't mind an external library, use lodash.
var a = 5;
var b = null;
var c = undefined;
if ( _.some([a,b,c], el => _.isNil(el)) ) {
console.log("You f*d up")
}
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
If your variables are containing some values that are truthy, like a string, and that is considered positive in your condition, then you could simply check using Array.prototype.every()...
if (![var1, var2, var3].every(Boolean)) {
throw new exc;
}
Which will check to ensure every variable has a truthy value.
I assume you are checking for truthy values? If so, you can just do:
variable && variable2 && variable3
See JavaScript: What is the difference between if (!x) and if (x == null)?
!variable will be true for all falsy values so you only have to
if(variable1 && variable2 && variable3 && ...)
Long hand -
if (var1 !== null || var1 !== undefined || var1 !== '') {
let var2 = var1;
}
Short hand -
const var2 = var1 || '';
let variable null;
let variable2 undefined;
let variable3 'string';
let variable4 '';
let variable5 true;
let variable6 false;
let variable7 0;
let variable8 1;
Validating multiple values using the filter function. One could expect this example to return true as the count would be 5 for (variable, variable2, variable4, variable6, variable7)
if([variable, variable2, variable3, variable4, variable5, variable6, variable7, variable8]
.filter(q=>!q).length > 0) {
//take action
}
How can I check if a variable's type is of type Boolean?
I mean, there are some alternatives such as:
if(jQuery.type(new Boolean()) === jQuery.type(variable))
//Do something..
But that doesn't seem pretty to me.
Is there a cleaner way to achieve this?
That's what typeof is there for. The parentheses are optional since it is an operator.
if (typeof variable == "boolean") {
// variable is a boolean
}
With pure JavaScript, you can just simply use typeof and do something like typeof false or typeof true and it will return "boolean"...
But that's not the only way to do that, I'm creating functions below to show different ways you can check for Boolean in JavaScript, also different ways you can do it in some new frameworks, let's start with this one:
function isBoolean(val) {
return val === false || val === true;
}
Or one-line ES6 way ...
const isBoolean = val => 'boolean' === typeof val;
and call it like!
isBoolean(false); //return true
Also in Underscore source code they check it like this(with the _. at the start of the function name):
isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
Also in jQuery you can check it like this:
jQuery.type(true); //return "boolean"
In React, if using propTypes, you can check a value to be boolean like this:
MyComponent.propTypes = {
children: PropTypes.bool.isRequired
};
If using TypeScript, you can use type boolean also:
let isDone: boolean = false;
Also another way to do it, is like converting the value to boolean and see if it's exactly the same still, something like:
const isBoolean = val => !!val === val;
or like:
const isBoolean = val => Boolean(val) === val;
and call it!
isBoolean(false); //return true
It's not recommended using any framework for this as it's really a simple check in JavaScript.
If you just want to check for a primitive value
typeof variable === 'boolean'
If for some strange reason you have booleans created with the constructor, those aren't really booleans but objects containing a primitive boolean value, and one way to check for both primitive booleans and objects created with new Boolean is to do :
function checkBool(bool) {
return typeof bool === 'boolean' ||
(typeof bool === 'object' &&
bool !== null &&
typeof bool.valueOf() === 'boolean');
}
function checkBool(bool) {
return typeof bool === 'boolean' ||
(typeof bool === 'object' &&
bool !== null &&
typeof bool.valueOf() === 'boolean');
}
console.log( checkBool( 'string' )); // false, string
console.log( checkBool( {test: 'this'} )); // false, object
console.log( checkBool( null )); // false, null
console.log( checkBool( undefined )); // false, undefined
console.log( checkBool( new Boolean(true) )); // true
console.log( checkBool( new Boolean() )); // true
console.log( checkBool( true )); // true
console.log( checkBool( false )); // true
There are three "vanilla" ways to check this with or without jQuery.
First is to force boolean evaluation by coercion, then check if it's equal to the original value:
function isBoolean( n ) {
return !!n === n;
}
Doing a simple typeof check:
function isBoolean( n ) {
return typeof n === 'boolean';
}
Doing a completely overkill and unnecessary instantiation of a class wrapper on a primative:
function isBoolean( n ) {
return n instanceof Boolean;
}
The third will only return true if you create a new Boolean class and pass that in.
To elaborate on primitives coercion (as shown in #1), all primitives types can be checked in this way:
Boolean:
function isBoolean( n ) {
return !!n === n;
}
Number:
function isNumber( n ) {
return +n === n;
}
String:
function isString( n ) {
return ''+n === n;
}
You can use pure Javascript to achieve this:
var test = true;
if (typeof test === 'boolean')
console.log('test is a boolean!');
If you want your function can validate boolean objects too, the most efficient solution must be:
function isBoolean(val) {
return val === false || val === true || val instanceof Boolean;
}
I would go with Lodash: isBoolean checks whether the passed-in variable is either primitive boolean or Boolean wrapper object and so accounts for all cases.
BENCHMARKING:
All pretty similar...
const { performance } = require('perf_hooks');
const boolyah = true;
var t0 = 0;
var t1 = 0;
const loops = 1000000;
var results = { 1: 0, 2: 0, 3: 0, 4: 0 };
for (i = 0; i < loops; i++) {
t0 = performance.now();
boolyah === false || boolyah === true;
t1 = performance.now();
results['1'] += t1 - t0;
t0 = performance.now();
'boolean' === typeof boolyah;
t1 = performance.now();
results['2'] += t1 - t0;
t0 = performance.now();
!!boolyah === boolyah;
t1 = performance.now();
results['3'] += t1 - t0;
t0 = performance.now();
Boolean(boolyah) === boolyah;
t1 = performance.now();
results['4'] += t1 - t0;
}
console.log(results);
// RESULTS
// '0': 135.09559339284897,
// '1': 136.38034391403198,
// '2': 136.29421120882034,
// '3': 135.1228678226471,
// '4': 135.11531442403793
The most reliable way to check type of a variable in JavaScript is the following:
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
toType(new Boolean(true)) // returns "boolean"
toType(true); // returns "boolean"
The reason for this complication is that typeof true returns "boolean" while typeof new Boolean(true) returns "object".
the easiest way to check for true and false is :
(typeof value === "boolean") ,
but if value is an instance of the Boolean class, then it will return "object". so to handle that we must add another condition to check if :
(value instanceof Boolean)
the code snippet :
const value = false;
//const value = new Boolean(10);
//const value = new Boolean("hi");
if((typeof value === "boolean") || (value instanceof Boolean))
console.log("boolean");
else
console.log("not boolean");
You can create a function that checks the typeof for an argument.
function isBoolean(value) {
return typeof value === "boolean";
}
Sometimes we need a single way to check it. typeof not working for date etc. So I made it easy by
Date.prototype.getType() { return "date"; }
Also for Number, String, Boolean etc. we often need to check the type in a single way...
Creating functions like isBoolean which contains oneliner typeof v === "boolean" seems very unhandy in long term. i am suprised that almost everyone suggest to create your own function. It seems to be same cancer as extending native prototypes.
you need to recreate them in every project you are involved
other developers might have different habits,, or need to check source of your function to see which impementation of check you use, to know what are weak points of your check
you will be fruustrated when you will try to write one liner in console on site which doesn't belong to your project
just memoize typeof v === "boolean" and that's all.
Add a template to your IDE to be able to put it by some three letter shortcut and be happy.
if(['true', 'yes', '1'].includes(single_value)) {
return true;
}
else if(['false', 'no', '0'].includes(single_value)) {
return false;
}
if you have a string
One more decision with es2015 arrow function
const isBoolean = val => typeof val === 'boolean';
The most readable: val === false || val === true.
Also readable: typeof variable == typeof true.
The shortest, but not readable at all: !!val === val.
Explanation:
[!!] The double exclamation mark converts the value into a Boolean.
[===] The triple equals test for strict equality: both the type (Boolean) and the value have to be the same.
If the original value is not a Boolean one, it won't pass the triple equals test. If it is a Boolean variable, it will pass the triple equals test (with both type & value).
Tests:
!!5 === 5 // false
!!'test' === 'test' // false
let val = new Date(); !!val === val // false
!!true === true // true
!!false === false // true
Update: The previous solution is more specific, you can choose which value you want to consider as a boolean and you can add that in regex, If you need a more general solution and don't want to add a library then check out the below solution(taken from lodash's boolean)
function getTag(value) {
if (value == null) {
return value === undefined ? '[object Undefined]' : '[object Null]'
}
return toString.call(value)
}
function isObjectLike(value) {
return typeof value === 'object' && value !== null
}
function isBoolean(value) {
return value === true || value === false ||
(isObjectLike(value) && getTag(value) == '[object Boolean]')
}
Previous Solution
const isBoolean = (val) => {
const boolValuesRegex = /true|false/; // Add other /true|false|1|0|on|off/
if (val === undefined || val === null) return false;
return boolValuesRegex.test(val.toString().toLowerCase());
}
const values = [true, false, 'true', 'false', 'TRUE', 'FALSE', 'sampletext', 1, undefined, null, (() => {}), {}, []];
document.body.innerHTML = values.map(x => `${x} - ${isBoolean(x)}`).join('</br>');
In nodejs by using node-boolify we can use isBoolean();
var isBoolean = require('node-boolify').isBoolean;
isBoolean(true); //true
isBoolean('true'); //true
isBoolean('TRUE'); //false
isBoolean(1); //true
isBoolean(2); //false
isBoolean(false); //true
isBoolean('false'); //true
isBoolean('FALSE'); //false
isBoolean(0); //true
isBoolean(null); //false
isBoolean(undefined); //false
isBoolean(); //false
isBoolean(''); //false
I have the following code:
var store = window.localStorage;
var a = store.getItem('AccountID');
var b = store.getItem('CityID')
How can I make it so my refreshGrid("Page"); function only runs if both of these are set to values?
If you want to check that they are explicity null, just compare the values to null:
if(a !== null && b !== null) {
//Neither is null
}
If you are storing values in there that should always evaluate to true, you can skip the equality checks (if nothing is stored in that particular storage item this will still fail, since null is falsy):
if(a && b) {
//Neither is falsy
}
You can use this:
var a; var b;
if (a == null && b == null) {
//a and b are null
}
OR
if (!a && !b) {
//a and b are null, undefined, 0 or false
}
For James: alert(null == undefined) // returns true
Hope this helps.
Use a guard condition at the top of your function:
function myFunction() {
if(a==null || b==null) return;
// ... rest of the code here
}
I think the following code is what your looking for.
if(!!a && !!b){
alert("this is not null")
}else{
alert("this is null")
}