Having trouble with an if/else statement - javascript

I'm trying to write a function called isVowel that takes a character (i.e. a string of length 1) and returns "true" if it is a vowel, uppercase or lowercase. The function should return "false" if the character is not a vowel.
This seems like it should work, but no matter what letter I enter, it returns "true." I've tried a bunch of different things, but I've hit a wall.
function isVowel(x){
if (x === "a" || "A" || "e" || "E" || "i" || "I"|| "o" || "O" || "u" || "U" || "y" || "Y"){
//console.log(x); // returns c
return true
} else {
return false
}
};
console.log(isVowel("c"));

To simplify your code even further, you can create an array of valid values and simply check if the value they passed in is contained in the valid values list.
function isVowel(x) {
var vowels = ["a", "e", "i", "o", "u", "y"];
return vowels.indexOf(x.toLowerCase()) > -1;
};
console.log(isVowel("a"));

Below is the improved and corrected version of your function:
Instead of checking all conditions for capital and small we first conver to small and then check using x == a/e/i/o/u.
function isVowel(x)
{
x = x.toLowerCase();
if (x === "a" || x == "e" || x == "i" || x == "o" || x == "u"){
return true
} else {
return false
}
};
console.log(isVowel("a"));
A better approach suggested by #yBrodsky is:
function isVowel(x)
{
var vowels = ['a', 'e', 'i', 'o', 'u'];
return vowels.indexOf(x.toLowerCase()) != -1;
};
console.log(isVowel("a"));

You can use /[a|e|i|o|u]/i.test(YOURTEXTHERE).
Below is a single liner to accomplish this:
var YOURTEXTHERE = 'b';
// check if it's vowel
if (/[a|e|i|o|u]/i.test(YOURTEXTHERE)) {
console.log('vowel!');
}
else
console.log('not vowel');

Your use of the || operator is incorrect. Your code is currently evaluating x === "a", then "A" which is always a truthy value. You either need to use a list of comparisons like this:
if (x === "a" || x === "A" || x === "o" || ...) {...}
Or something like this (much neater, and faster):
if (['a', 'e', 'i', 'o', 'u'].indexOf(x.toLowerCase())) {...}

You are only comparing x == "a", you need to have
x=="A"||x=="o" and so on.

A clean version might be:
function isVowel(x) {
return (['a', 'e', 'i', 'o', 'u', 'y'].indexOf(x.toLowerCase()) > -1);
};
console.log(isVowel("c"));
console.log(isVowel("a"));
console.log(isVowel("A"));

As you're passing in a string with a length of 1 you could use String.includes for a simple comparison. No need for any arrays at all.
function isVowel(x){
return 'aeiouy'.includes( x.toLowerCase() );
};
console.log( isVowel("c") ); // false
console.log( isVowel("e") ); // true

Perhaps a different approach and a cleaner solution may work better as follows.
function isVowel(character) {
// Clean the character to eliminate errors with capital letters
let cleanedChar = character.toLowerCase();
// Check if the cleaned character which is now any lower case letter matches a vowel
if (cleanedChar.match(/[aeiou]/g)) {
// Return true if it does
return true;
}
// return false if ever get to this point (it means the char was not a vowel)
return false;
}
// Call isVowel function and pass it 'c'
console.log(isVowel('c'));

Related

I have to write a javascript function that takes in a string and returns true if "the string starts and ends with a vowel"

title basically. The question says create a function that takes in a string and returns true when the string starts and ends with a vowel. I must have read every possibly helpful/similar thread on here and still stuck. Please help
Tried too many things to even list. Its been literally hours I've been bashing my head against this problem.
function test( word ){
word = word.toUpperCase();
let last = word[ word.length - 1 ];
let vowels = [ 'A', 'E', 'I', 'O', 'U' ]
if( vowels.includes( word[0]) && vowels.includes( last ) ){
return true
}else{
return false
}
}
:-)
You know how to create and execute a function?
You understand what startsWith and endsWith with does?
You know the && (and) and || (or) operators?
Try something like this:
function startsEndsWithAVowel(aString) {
return (aString.startsWith('a') || aString.startsWith('e') || aString.startsWith('i') || aString.startsWith('o') || aString.startsWith('u')) && (aString.endsWith('a') || aString.endsWith('e') || aString.endsWith('i') || aString.endsWith('o') || aString.endsWith('u'));
}
Add uppercase vowels too.
This solution uses only a few constructs. If You learn more JavaScript you come up much better solutions.

How do I get the console to print out the name, keeping in mind the name variable isn't constant? [duplicate]

Is there a string.Empty in JavaScript, or is it just a case of checking for ""?
Empty string, undefined, null, ...
To check for a truthy value:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
To check for a falsy value:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
Empty string (only!)
To check for exactly an empty string, compare for strict equality against "" using the === operator:
if (strValue === "") {
// strValue was empty string
}
To check for not an empty string strictly, use the !== operator:
if (strValue !== "") {
// strValue was not an empty string
}
For checking if a variable is falsey or if it has length attribute equal to zero (which for a string, means it is empty), I use:
function isEmpty(str) {
return (!str || str.length === 0 );
}
(Note that strings aren't the only variables with a length attribute, arrays have them as well, for example.)
Alternativaly, you can use the (not so) newly optional chaining and arrow functions to simplify:
const isEmpty = (str) => (!str?.length);
It will check the length, returning undefined in case of a nullish value, without throwing an error. In the case of an empty value, zero is falsy and the result is still valid.
For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
If you want, you can monkey-patch the String prototype like this:
String.prototype.isEmpty = function() {
// This doesn't work the same way as the isEmpty function used
// in the first example, it will return true for strings containing only whitespace
return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());
Note that monkey-patching built-in types are controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason.
All the previous answers are good, but this will be even better. Use dual NOT operators (!!):
if (!!str) {
// Some code here
}
Or use type casting:
if (Boolean(str)) {
// Code here
}
Both do the same function. Typecast the variable to Boolean, where str is a variable.
It returns false for null, undefined, 0, 000, "", false.
It returns true for all string values other than the empty string (including strings like "0" and " ")
The closest thing you can get to str.Empty (with the precondition that str is a String) is:
if (!str.length) { ...
If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces.
if(str.replace(/\s/g,"") == ""){
}
I use:
function empty(e) {
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case undefined:
return true;
default:
return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
return ""
})) // false
Performance
I perform tests on macOS v10.13.6 (High Sierra) for 18 chosen solutions. Solutions works slightly different (for corner-case input data) which was presented in the snippet below.
Conclusions
the simple solutions based on !str,==,=== and length are fast for all browsers (A,B,C,G,I,J)
the solutions based on the regular expression (test,replace) and charAt are slowest for all browsers (H,L,M,P)
the solutions marked as fastest was fastest only for one test run - but in many runs it changes inside 'fast' solutions group
Details
In the below snippet I compare results of chosen 18 methods by use different input parameters
"" "a" " "- empty string, string with letter and string with space
[] {} f- array, object and function
0 1 NaN Infinity - numbers
true false - Boolean
null undefined
Not all tested methods support all input cases.
function A(str) {
let r=1;
if (!str)
r=0;
return r;
}
function B(str) {
let r=1;
if (str == "")
r=0;
return r;
}
function C(str) {
let r=1;
if (str === "")
r=0;
return r;
}
function D(str) {
let r=1;
if(!str || 0 === str.length)
r=0;
return r;
}
function E(str) {
let r=1;
if(!str || /^\s*$/.test(str))
r=0;
return r;
}
function F(str) {
let r=1;
if(!Boolean(str))
r=0;
return r;
}
function G(str) {
let r=1;
if(! ((typeof str != 'undefined') && str) )
r=0;
return r;
}
function H(str) {
let r=1;
if(!/\S/.test(str))
r=0;
return r;
}
function I(str) {
let r=1;
if (!str.length)
r=0;
return r;
}
function J(str) {
let r=1;
if(str.length <= 0)
r=0;
return r;
}
function K(str) {
let r=1;
if(str.length === 0 || !str.trim())
r=0;
return r;
}
function L(str) {
let r=1;
if ( str.replace(/\s/g,"") == "")
r=0;
return r;
}
function M(str) {
let r=1;
if((/^\s*$/).test(str))
r=0;
return r;
}
function N(str) {
let r=1;
if(!str || !str.trim().length)
r=0;
return r;
}
function O(str) {
let r=1;
if(!str || !str.trim())
r=0;
return r;
}
function P(str) {
let r=1;
if(!str.charAt(0))
r=0;
return r;
}
function Q(str) {
let r=1;
if(!str || (str.trim()==''))
r=0;
return r;
}
function R(str) {
let r=1;
if (typeof str == 'undefined' ||
!str ||
str.length === 0 ||
str === "" ||
!/[^\s]/.test(str) ||
/^\s*$/.test(str) ||
str.replace(/\s/g,"") === "")
r=0;
return r;
}
// --- TEST ---
console.log( ' "" "a" " " [] {} 0 1 NaN Infinity f true false null undefined ');
let log1 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)} ${f(null)} ${f(undefined)}`);
let log2 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)}`);
let log3 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")}`);
log1('A', A);
log1('B', B);
log1('C', C);
log1('D', D);
log1('E', E);
log1('F', F);
log1('G', G);
log1('H', H);
log2('I', I);
log2('J', J);
log3('K', K);
log3('L', L);
log3('M', M);
log3('N', N);
log3('O', O);
log3('P', P);
log3('Q', Q);
log3('R', R);
And then for all methods I perform speed test case str = "" for browsers Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0 - you can run tests on your machine here
You can use lodash:
_.isEmpty(value).
It covers a lot of cases like {}, '', null, undefined, etc.
But it always returns true for Number type of JavaScript primitive data types like _.isEmpty(10) or _.isEmpty(Number.MAX_VALUE) both returns true.
Very generic "All-In-One" Function (not recommended though):
function is_empty(x)
{
return ( //don't put newline after return
(typeof x == 'undefined')
||
(x == null)
||
(x == false) //same as: !x
||
(x.length == 0)
||
(x == 0) // note this line, you might not need this.
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
);
}
However, I don't recommend to use that, because your target variable should be of specific type (i.e. string, or numeric, or object?), so apply the checks that are relative to that variable.
var s; // undefined
var s = ""; // ""
s.length // 0
There's nothing representing an empty string in JavaScript. Do a check against either length (if you know that the var will always be a string) or against ""
Try:
if (str && str.trim().length) {
//...
}
I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == "".
As per the comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.
A lot of answers, and a lot of different possibilities!
Without a doubt for quick and simple implementation the winner is: if (!str.length) {...}
However, as many other examples are available. The best functional method to go about this, I would suggest:
function empty(str)
{
if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
return true;
else
return false;
}
A bit excessive, I know.
check that var a; exist
trim out the false spaces in the value, then test for emptiness
if ((a)&&(a.trim()!=''))
{
// if variable a is not empty do this
}
You could also go with regular expressions:
if((/^\s*$/).test(str)) { }
Checks for strings that are either empty or filled with whitespace.
I usually use something like this,
if (!str.length) {
// Do something
}
Also, in case you consider a whitespace filled string as "empty".
You can test it with this regular expression:
!/\S/.test(string); // Returns true if blank.
If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
if ((str?.trim()?.length || 0) > 0) {
// str must not be any of:
// undefined
// null
// ""
// " " or just whitespace
}
Or in function form:
const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;
const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;
Starting with:
return (!value || value == undefined || value == "" || value.length == 0);
Looking at the last condition, if value == "", its length must be 0. Therefore drop it:
return (!value || value == undefined || value == "");
But wait! In JavaScript, an empty string is false. Therefore, drop value == "":
return (!value || value == undefined);
And !undefined is true, so that check isn't needed. So we have:
return (!value);
And we don't need parentheses:
return !value
I use a combination, and the fastest checks are first.
function isBlank(pString) {
if (!pString) {
return true;
}
// Checks for a non-white space character
// which I think [citation needed] is faster
// than removing all the whitespace and checking
// against an empty string
return !/[^\s]+/.test(pString);
}
I have not noticed an answer that takes into account the possibility of null characters in a string. For example, if we have a null character string:
var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted
To test its nullness one could do something like this:
String.prototype.isNull = function(){
return Boolean(this.match(/^[\0]*$/));
}
...
"\0".isNull() // true
It works on a null string, and on an empty string and it is accessible for all strings. In addition, it could be expanded to contain other JavaScript empty or whitespace characters (i.e. nonbreaking space, byte order mark, line/paragraph separator, etc.).
Meanwhile we can have one function that checks for all 'empties' like null, undefined, '', ' ', {}, [].
So I just wrote this.
var isEmpty = function(data) {
if(typeof(data) === 'object'){
if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
return true;
}else if(!data){
return true;
}
return false;
}else if(typeof(data) === 'string'){
if(!data.trim()){
return true;
}
return false;
}else if(typeof(data) === 'undefined'){
return true;
}else{
return false;
}
}
Use cases and results.
console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty(' ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false
I did some research on what happens if you pass a non-string and non-empty/null value to a tester function. As many know, (0 == "") is true in JavaScript, but since 0 is a value and not empty or null, you may want to test for it.
The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, Boolean, objects, expressions, etc.
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic C# behaviour by adding them to String like this:
String.IsNullOrEmpty = function (value) { ... }
You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // Could be set
myvar.IsNullOrEmpty(); // Throws error
I tested with the following value array. You can loop it through to test your functions if in doubt.
// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
['undefined', undefined],
['(var) z', z],
['null', null],
['empty', ''],
['space', ' '],
['tab', '\t'],
['newline', '\n'],
['carriage return', '\r'],
['"\\r\\n"', '\r\n'],
['"\\n\\r"', '\n\r'],
['" \\t \\n "', ' \t \n '],
['" txt \\t test \\n"', ' txt \t test \n'],
['"txt"', "txt"],
['"undefined"', 'undefined'],
['"null"', 'null'],
['"0"', '0'],
['"1"', '1'],
['"1.5"', '1.5'],
['"1,5"', '1,5'], // Valid number in some locales, not in JavaScript
['comma', ','],
['dot', '.'],
['".5"', '.5'],
['0', 0],
['0.0', 0.0],
['1', 1],
['1.5', 1.5],
['NaN', NaN],
['/\S/', /\S/],
['true', true],
['false', false],
['function, returns true', function () { return true; } ],
['function, returns false', function () { return false; } ],
['function, returns null', function () { return null; } ],
['function, returns string', function () { return "test"; } ],
['function, returns undefined', function () { } ],
['MyClass', MyClass],
['new MyClass', new MyClass()],
['empty object', {}],
['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];
I didn't see a good answer here (at least not an answer that fits for me)
So I decided to answer myself:
value === undefined || value === null || value === "";
You need to start checking if it's undefined. Otherwise your method can explode, and then you can check if it equals null or is equal to an empty string.
You cannot have !! or only if(value) since if you check 0 it's going to give you a false answer (0 is false).
With that said, wrap it up in a method like:
public static isEmpty(value: any): boolean {
return value === undefined || value === null || value === "";
}
PS.: You don't need to check typeof, since it would explode and throw even before it enters the method
Trimming whitespace with the null-coalescing operator:
if (!str?.trim()) {
// do something...
}
There is a lot of useful information here, but in my opinion, one of the most important elements was not addressed.
null, undefined, and "" are all falsy.
When evaluating for an empty string, it's often because you need to replace it with something else.
In which case, you can expect the following behavior.
var a = ""
var b = null
var c = undefined
console.log(a || "falsy string provided") // prints ->"falsy string provided"
console.log(b || "falsy string provided") // prints ->"falsy string provided"
console.log(c || "falsy string provided") // prints ->"falsy string provided"
With that in mind, a method or function that can return whether or not a string is "", null, or undefined (an invalid string) versus a valid string is as simple as this:
const validStr = (str) => str ? true : false
validStr(undefined) // returns false
validStr(null) // returns false
validStr("") // returns false
validStr("My String") // returns true
Try this:
export const isEmpty = string => (!string || !string.length);
All these answers are nice.
But I cannot be sure that variable is a string, doesn't contain only spaces (this is important for me), and can contain '0' (string).
My version:
function empty(str){
return !str || !/[^\s]+/.test(str);
}
empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty(" "); // true
Sample on jsfiddle.
There's no isEmpty() method, you have to check for the type and the length:
if (typeof test === 'string' && test.length === 0){
...
The type check is needed in order to avoid runtime errors when test is undefined or null.

Why does it always return true?

Beginner question, sorry if it's not the right place to ask
Trying to learn how logic works in JS, can't figure this out
if (firstSymbol === "A" || "a" || "D" || "d") {
if (secondSymbol === "z") {
alert("It does!");
break;
}
}
I expect it to say "It does!" and break in case if the firstSymbol is A, a, D or d AND the secondSymbol is z , but for some reason it says "It does!" and breaks regardless of what the firstSymbol is and only checks if the secondSymbol is z.
Because you're checking whether "a" is true - it is always true:
console.log(!!"a");
You should be using includes and AND && in this case:
const firstSymbol = "D";
const secondSymbol = "z";
if (["A", "a", "D", "d"].includes(firstSymbol) && secondSymbol == "z") {
console.log("It does!");
}
function matchSecondSymbol(firstSymbol, secondSymbol) {
// By making FirstSymbol Uppercase, we can remove the other two conditions
firstSymbol = firstSymbol.toUpperCase();
if (['A', 'D'].includes(firstSymbol) && secondSymbol === "z") {
console.log('it Does');
}
else {
console.log('it does not');
}
}
matchSecondSymbol('a', 'z');
matchSecondSymbol('z', 'z');
matchSecondSymbol('a', 'y');
In Javascript there's something called truthy and falsy values. In summary, is how a value evaluates in a Boolean (true or false) context.
All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).
In your code, when you wrote:
if (firstSymbol === "A" || "a" || "D" || "d")
You are checking 4 boolean conditions:
firstSymbol === "A" - The result will depend on firstSymbol
"a" - Will always evaluate to true
"D" - Will always evaluate to true
"d" - Will always evaluate to true
So, since conditions 2, 3 and 4 will always be true, your code will always enter the if statement. If even a single one of these would be true the behaviour would be the same.
You can rewrite it in some ways:
if (firstSymbol === "A" || firstSymbol === "a" || firstSymbol === "D" || firstSymbol === "d")
or
if (["A", "a", "D", "d"].indexOf(firstSymbol) > -1)
or
if (["A", "D"].indexOf(firstSymbol.toUpperCase()) > -1)
Just to add something to the boilerplate, these are some examples to accomplish what you're trying to do, with tons of possibilities.
Tests covered:
using array.includes
using array.indexOf
using array.find
using array.some
WHY didn't your code work?
It didn't work because javascript evaluates the following expression: "A" || "a" || "D" || "d" to "A", because "A" is truthy. If you need to compare with multiple values, either use an array, either write the condition for each of them:
firstSymbol === "A" || firstSymbol === "D" ||...
Examples mentioned above:
/* Original code */
/*
if (firstSymbol === "A" || "a" || "D" || "d") {if (secondSymbol === "z") alert("It does!"); break;}
*/
let firstSymbol = "d", secondSymbol = "z";
// Using .includes
if (["A","a","D","d"].includes(firstSymbol) && secondSymbol === "z") console.log('it does, with .includes');
// Cleverer .includes due to the nature of the input.
if (["a","d"].includes(firstSymbol.toLowerCase()) && secondSymbol === "z") console.log('it does, with cleverer .includes');
// Using .indexOf
if (["A","a","D","d"].indexOf(firstSymbol) > -1 && secondSymbol === "z") console.log('it does, with .indexOf');
// Using .find
if (["A","a","D","d"].find(i => i === firstSymbol) && secondSymbol === "z") console.log('it does, with .find');
// Using. some
if (["A","a","D","d"].some(i => i === firstSymbol) && secondSymbol === "z") console.log('it does, with .some');
Order of Precedence decides
In each programming language, symbols are processed in order of their precedence order.
In Short:
AS the others already explained, your assignment
firstSymbol === "A" || "a" || "D" || "d"
would be processed as
(firstSymbol === "A") || ("a") || ("D") || ("d")
Link to how logical operators are processed: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Why my condition is always true

I would like to know in this example why my condition is always true ? Thanks
function bla() {
var qix = 'z'
if (qix === 'a' || 'b' || 'c') {
console.log('condition ok!! whats wrong???')
}
}
The problem with your code is that the if expression always evaluates to true.
qix === 'a' || 'b' || 'c'
will actually become this:
false || 'b' || 'c'
as qix is set to z. Due to loose typing, JavaScript returns true for the second expression because 'b' is a truthy value. To correct that, you need to change the expression as follows:
qix === 'a' || qix === 'b' || qix === 'c'
so that it correctly means what you're expecting.
Description of expr1 || expr2 from MDN:
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true.
o1 = true || true // t || t returns true
o2 = false || true // f || t returns true
o3 = true || false // t || f returns true
o4 = false || (3 == 4) // f || f returns false
o5 = 'Cat' || 'Dog' // t || t returns "Cat"
o6 = false || 'Cat' // f || t returns "Cat"
o7 = 'Cat' || false // t || f returns "Cat"
o8 = '' || false // f || f returns false
o9 = false || '' // f || f returns ""
So this expression from your code, assuming qix is not 'a':
qix === 'a' || 'b' || 'c'
The first term qux === 'a' is false, which of course evaluates to false. This causes it to go to the next term which is 'b'. Non-empty strings evaluate to true, so it stops there and just becomes 'b'. Now your if statement can be thought of as just:
if ('b')
Again, 'b' evaluates to true. So your conditional is effectively doing nothing.
I think you are missing two concepts.
First how the || operator works and second coercion of javascript values.
In your code:
if ('z' === 'a' || 'b' || 'c') { ----}
Will always evaluate to true.
The reason for this is that the || operator will give back the first value which coerces to true without actually coercing the value. The associativity (order which the operators are executed) is left-to-right. This means that the following happens:
First the following will be evaluated because it has higher precedence:
'z' === 'a' // false
then we have the following expression which will be evaluated left to right:
false || 'b' || 'c'
let foo = false || 'b'
console.log(foo)
Then we have the following expression:
let foo = 'b' || 'c'
console.log(foo)
So the whole expression evulates to the string 'b'
After the expression inside the if statement is evaluated to the value 'b' this in turn then gets coerced into a boolean. Every string gets converted to true and that's why the value is always true.
This is because you 'if condition' is take 3 possible option
First say qix === 'a', this is false but you asking about 'b','c' and this option are values true because you are not compare var qix with 'b' or 'c', you only asking to IF condition, that if 'b' or 'c' are value
the operator || it is used so
if(First Condition || Second Condition || third condition){
if at least one of these options is true, then enter here
}
In ECMAScript 2016 incorporates an includes() method for arrays that specifically solves the answer
if (['b', 'c', 'a'].includes(qix)) {
this is false
}
if (['z', 'c', 'a'].includes(qix)) {
this is true
}
Or you can write so
function bla() {
var qix = 'z'
if (qix === 'a' || qix === 'b' || qix === 'c') {
console.log('condition ok!! whats wrong???')
}
}
As we know || (OR Logical Operators) returns true if either operand is true. In your if condition qix === 'a' || 'b' || 'c' in their second and third operand is string and Strings are considered false if and only if they are empty otherwise true. For this reason, your condition is always true.
Need to check qix like qix ==='b'
var qix = 'z'
if (qix === 'a' || qix === 'b' || qix ==='c') {
console.log('condition ok!! whats wrong???')
}
else{
console.log('else')
}
You could use Regex: qix.match(/^(a|b|c)$/)
Should return if qix is equals to a or b or c
var qix = 'z';
if (qix.match(/^(a|b|c)$/)) {
console.log('condition ok!! whats wrong???');
} else {
console.log('else');
}
JavaScript returns true for the second or expression because 'b' is always true.
You need to check each value against qix like so:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators
var qix = 'z'
if (qix === 'a' || qix === 'b' || qix === 'c') {
console.log('condition ok!! whats wrong???')
}

How do I check for an empty/undefined/null string in JavaScript?

Is there a string.Empty in JavaScript, or is it just a case of checking for ""?
Empty string, undefined, null, ...
To check for a truthy value:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
To check for a falsy value:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
Empty string (only!)
To check for exactly an empty string, compare for strict equality against "" using the === operator:
if (strValue === "") {
// strValue was empty string
}
To check for not an empty string strictly, use the !== operator:
if (strValue !== "") {
// strValue was not an empty string
}
For checking if a variable is falsey or if it has length attribute equal to zero (which for a string, means it is empty), I use:
function isEmpty(str) {
return (!str || str.length === 0 );
}
(Note that strings aren't the only variables with a length attribute, arrays have them as well, for example.)
Alternativaly, you can use the (not so) newly optional chaining and arrow functions to simplify:
const isEmpty = (str) => (!str?.length);
It will check the length, returning undefined in case of a nullish value, without throwing an error. In the case of an empty value, zero is falsy and the result is still valid.
For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
If you want, you can monkey-patch the String prototype like this:
String.prototype.isEmpty = function() {
// This doesn't work the same way as the isEmpty function used
// in the first example, it will return true for strings containing only whitespace
return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());
Note that monkey-patching built-in types are controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason.
All the previous answers are good, but this will be even better. Use dual NOT operators (!!):
if (!!str) {
// Some code here
}
Or use type casting:
if (Boolean(str)) {
// Code here
}
Both do the same function. Typecast the variable to Boolean, where str is a variable.
It returns false for null, undefined, 0, 000, "", false.
It returns true for all string values other than the empty string (including strings like "0" and " ")
The closest thing you can get to str.Empty (with the precondition that str is a String) is:
if (!str.length) { ...
If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces.
if(str.replace(/\s/g,"") == ""){
}
I use:
function empty(e) {
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case undefined:
return true;
default:
return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
return ""
})) // false
Performance
I perform tests on macOS v10.13.6 (High Sierra) for 18 chosen solutions. Solutions works slightly different (for corner-case input data) which was presented in the snippet below.
Conclusions
the simple solutions based on !str,==,=== and length are fast for all browsers (A,B,C,G,I,J)
the solutions based on the regular expression (test,replace) and charAt are slowest for all browsers (H,L,M,P)
the solutions marked as fastest was fastest only for one test run - but in many runs it changes inside 'fast' solutions group
Details
In the below snippet I compare results of chosen 18 methods by use different input parameters
"" "a" " "- empty string, string with letter and string with space
[] {} f- array, object and function
0 1 NaN Infinity - numbers
true false - Boolean
null undefined
Not all tested methods support all input cases.
function A(str) {
let r=1;
if (!str)
r=0;
return r;
}
function B(str) {
let r=1;
if (str == "")
r=0;
return r;
}
function C(str) {
let r=1;
if (str === "")
r=0;
return r;
}
function D(str) {
let r=1;
if(!str || 0 === str.length)
r=0;
return r;
}
function E(str) {
let r=1;
if(!str || /^\s*$/.test(str))
r=0;
return r;
}
function F(str) {
let r=1;
if(!Boolean(str))
r=0;
return r;
}
function G(str) {
let r=1;
if(! ((typeof str != 'undefined') && str) )
r=0;
return r;
}
function H(str) {
let r=1;
if(!/\S/.test(str))
r=0;
return r;
}
function I(str) {
let r=1;
if (!str.length)
r=0;
return r;
}
function J(str) {
let r=1;
if(str.length <= 0)
r=0;
return r;
}
function K(str) {
let r=1;
if(str.length === 0 || !str.trim())
r=0;
return r;
}
function L(str) {
let r=1;
if ( str.replace(/\s/g,"") == "")
r=0;
return r;
}
function M(str) {
let r=1;
if((/^\s*$/).test(str))
r=0;
return r;
}
function N(str) {
let r=1;
if(!str || !str.trim().length)
r=0;
return r;
}
function O(str) {
let r=1;
if(!str || !str.trim())
r=0;
return r;
}
function P(str) {
let r=1;
if(!str.charAt(0))
r=0;
return r;
}
function Q(str) {
let r=1;
if(!str || (str.trim()==''))
r=0;
return r;
}
function R(str) {
let r=1;
if (typeof str == 'undefined' ||
!str ||
str.length === 0 ||
str === "" ||
!/[^\s]/.test(str) ||
/^\s*$/.test(str) ||
str.replace(/\s/g,"") === "")
r=0;
return r;
}
// --- TEST ---
console.log( ' "" "a" " " [] {} 0 1 NaN Infinity f true false null undefined ');
let log1 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)} ${f(null)} ${f(undefined)}`);
let log2 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)}`);
let log3 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")}`);
log1('A', A);
log1('B', B);
log1('C', C);
log1('D', D);
log1('E', E);
log1('F', F);
log1('G', G);
log1('H', H);
log2('I', I);
log2('J', J);
log3('K', K);
log3('L', L);
log3('M', M);
log3('N', N);
log3('O', O);
log3('P', P);
log3('Q', Q);
log3('R', R);
And then for all methods I perform speed test case str = "" for browsers Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0 - you can run tests on your machine here
You can use lodash:
_.isEmpty(value).
It covers a lot of cases like {}, '', null, undefined, etc.
But it always returns true for Number type of JavaScript primitive data types like _.isEmpty(10) or _.isEmpty(Number.MAX_VALUE) both returns true.
Very generic "All-In-One" Function (not recommended though):
function is_empty(x)
{
return ( //don't put newline after return
(typeof x == 'undefined')
||
(x == null)
||
(x == false) //same as: !x
||
(x.length == 0)
||
(x == 0) // note this line, you might not need this.
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
);
}
However, I don't recommend to use that, because your target variable should be of specific type (i.e. string, or numeric, or object?), so apply the checks that are relative to that variable.
var s; // undefined
var s = ""; // ""
s.length // 0
There's nothing representing an empty string in JavaScript. Do a check against either length (if you know that the var will always be a string) or against ""
Try:
if (str && str.trim().length) {
//...
}
I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == "".
As per the comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.
A lot of answers, and a lot of different possibilities!
Without a doubt for quick and simple implementation the winner is: if (!str.length) {...}
However, as many other examples are available. The best functional method to go about this, I would suggest:
function empty(str)
{
if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
return true;
else
return false;
}
A bit excessive, I know.
check that var a; exist
trim out the false spaces in the value, then test for emptiness
if ((a)&&(a.trim()!=''))
{
// if variable a is not empty do this
}
You could also go with regular expressions:
if((/^\s*$/).test(str)) { }
Checks for strings that are either empty or filled with whitespace.
I usually use something like this,
if (!str.length) {
// Do something
}
Also, in case you consider a whitespace filled string as "empty".
You can test it with this regular expression:
!/\S/.test(string); // Returns true if blank.
If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
if ((str?.trim()?.length || 0) > 0) {
// str must not be any of:
// undefined
// null
// ""
// " " or just whitespace
}
Or in function form:
const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;
const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;
Starting with:
return (!value || value == undefined || value == "" || value.length == 0);
Looking at the last condition, if value == "", its length must be 0. Therefore drop it:
return (!value || value == undefined || value == "");
But wait! In JavaScript, an empty string is false. Therefore, drop value == "":
return (!value || value == undefined);
And !undefined is true, so that check isn't needed. So we have:
return (!value);
And we don't need parentheses:
return !value
I use a combination, and the fastest checks are first.
function isBlank(pString) {
if (!pString) {
return true;
}
// Checks for a non-white space character
// which I think [citation needed] is faster
// than removing all the whitespace and checking
// against an empty string
return !/[^\s]+/.test(pString);
}
I have not noticed an answer that takes into account the possibility of null characters in a string. For example, if we have a null character string:
var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted
To test its nullness one could do something like this:
String.prototype.isNull = function(){
return Boolean(this.match(/^[\0]*$/));
}
...
"\0".isNull() // true
It works on a null string, and on an empty string and it is accessible for all strings. In addition, it could be expanded to contain other JavaScript empty or whitespace characters (i.e. nonbreaking space, byte order mark, line/paragraph separator, etc.).
Meanwhile we can have one function that checks for all 'empties' like null, undefined, '', ' ', {}, [].
So I just wrote this.
var isEmpty = function(data) {
if(typeof(data) === 'object'){
if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
return true;
}else if(!data){
return true;
}
return false;
}else if(typeof(data) === 'string'){
if(!data.trim()){
return true;
}
return false;
}else if(typeof(data) === 'undefined'){
return true;
}else{
return false;
}
}
Use cases and results.
console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty(' ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false
I did some research on what happens if you pass a non-string and non-empty/null value to a tester function. As many know, (0 == "") is true in JavaScript, but since 0 is a value and not empty or null, you may want to test for it.
The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, Boolean, objects, expressions, etc.
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic C# behaviour by adding them to String like this:
String.IsNullOrEmpty = function (value) { ... }
You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // Could be set
myvar.IsNullOrEmpty(); // Throws error
I tested with the following value array. You can loop it through to test your functions if in doubt.
// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
['undefined', undefined],
['(var) z', z],
['null', null],
['empty', ''],
['space', ' '],
['tab', '\t'],
['newline', '\n'],
['carriage return', '\r'],
['"\\r\\n"', '\r\n'],
['"\\n\\r"', '\n\r'],
['" \\t \\n "', ' \t \n '],
['" txt \\t test \\n"', ' txt \t test \n'],
['"txt"', "txt"],
['"undefined"', 'undefined'],
['"null"', 'null'],
['"0"', '0'],
['"1"', '1'],
['"1.5"', '1.5'],
['"1,5"', '1,5'], // Valid number in some locales, not in JavaScript
['comma', ','],
['dot', '.'],
['".5"', '.5'],
['0', 0],
['0.0', 0.0],
['1', 1],
['1.5', 1.5],
['NaN', NaN],
['/\S/', /\S/],
['true', true],
['false', false],
['function, returns true', function () { return true; } ],
['function, returns false', function () { return false; } ],
['function, returns null', function () { return null; } ],
['function, returns string', function () { return "test"; } ],
['function, returns undefined', function () { } ],
['MyClass', MyClass],
['new MyClass', new MyClass()],
['empty object', {}],
['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];
I didn't see a good answer here (at least not an answer that fits for me)
So I decided to answer myself:
value === undefined || value === null || value === "";
You need to start checking if it's undefined. Otherwise your method can explode, and then you can check if it equals null or is equal to an empty string.
You cannot have !! or only if(value) since if you check 0 it's going to give you a false answer (0 is false).
With that said, wrap it up in a method like:
public static isEmpty(value: any): boolean {
return value === undefined || value === null || value === "";
}
PS.: You don't need to check typeof, since it would explode and throw even before it enters the method
Trimming whitespace with the null-coalescing operator:
if (!str?.trim()) {
// do something...
}
There is a lot of useful information here, but in my opinion, one of the most important elements was not addressed.
null, undefined, and "" are all falsy.
When evaluating for an empty string, it's often because you need to replace it with something else.
In which case, you can expect the following behavior.
var a = ""
var b = null
var c = undefined
console.log(a || "falsy string provided") // prints ->"falsy string provided"
console.log(b || "falsy string provided") // prints ->"falsy string provided"
console.log(c || "falsy string provided") // prints ->"falsy string provided"
With that in mind, a method or function that can return whether or not a string is "", null, or undefined (an invalid string) versus a valid string is as simple as this:
const validStr = (str) => str ? true : false
validStr(undefined) // returns false
validStr(null) // returns false
validStr("") // returns false
validStr("My String") // returns true
Try this:
export const isEmpty = string => (!string || !string.length);
All these answers are nice.
But I cannot be sure that variable is a string, doesn't contain only spaces (this is important for me), and can contain '0' (string).
My version:
function empty(str){
return !str || !/[^\s]+/.test(str);
}
empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty(" "); // true
Sample on jsfiddle.
There's no isEmpty() method, you have to check for the type and the length:
if (typeof test === 'string' && test.length === 0){
...
The type check is needed in order to avoid runtime errors when test is undefined or null.

Categories

Resources