Using regular expression ,if and else conflict with .test() function - javascript

In the given code, best.test(password) is returning true but when I am using it in if()
condition in takes it as a false.
Code:
if(best.test(password)) //It takes it as a false .
{
document.write(best.test(password));
tdPwdStrength.innerHTML="best"+best.test(password); //but in actual it is true and returning true.
}
Please Suggest!

What is best? Is it a ‘global’ RegExp, that is, one with the g flag set?
If so, then each time you call test or exec you will get a different answer, as it remembers the previous string index and searches from there:
var r= /a/g; // or new RegExp('a', 'g')
alert(r.test('aardvark')); // true. matches first `a`
alert(r.test('aardvark')); // true. matches second `a`
alert(r.test('aardvark')); // true. matches third `a`
alert(r.test('aardvark')); // false! no more matches found
alert(r.test('aardvark')); // true. back to the first `a` again
JavaScript's RegExp interface is full of confusing little traps like this. Be careful.

Related

What is the purpose of adding a negation operator in the while condition?

can i use the check to find out if yourName variable is false, instead of using the negation operator to change its type.
let yourName;
do {
yourName = prompt("Who are you?");
}
while (!yourName);
console.log(yourName);
the results are the same
Out of the past 5 years of professional enterprise work I've never once seen a do..while loop simply because while() works just fine I understand in certain scenario's you'd want at least 1 loop but in those cases look to see how you're triggering this function. I can only see a small snippet of it but I wouldn't recommend using this.
JavaScript has a fun time with if, while when applying the negation operator.
There's plenty of information on this topic, typically I like to reference MDN for new devs to JavaScript as Mozilla has great tutorials https://developer.mozilla.org/en-US/docs/Glossary/Truthy.
If yourName is of type undefined or null or false or "" it'll be fine but be careful as there's times when you want to check if 0 value is true. It will return false since it's interpreted 0 as false, example you want to check if value does equal zero if(0) will return false. But if(yourName == 0) and yourName is 0 it'll return true.
There's a fun bit with double vs triple equality comparisons in JavaScript as well https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
What is the purpose of adding a negation operator in the while condition
To make sure the value is not an empty string "", undefined, or null.
Can i use the check to find out if yourName variable is false, instead of using the negation operator to change its type
yes you can check to see if yourName is false and it'll work fine without negation it's just a shortcut.
I don't understand what you mean by change its type?
Before explaining the purpose of the negation (!) in the while statement, we must back up and understand while loops.
while will continue to loop (repeatedly run the code within the brackets) when the condition evaluates to true.
while(true){
// this will run forever
}
When the condition evaluates to false the looping stop.
while(false) {
// this will never run
}
We can use a variable for a boolean evaluation based on "truthyness".
Truthyness: A funky thing in javascript where boolean evaluations can recognize nil things like 0, null, undefined, "" as "false", and existing things like 1, "something", object, array -- anything that "is" or has a value as "true".
var bob = true;
while(bob) {
// this will run one time.
bob = false;
}
You can flip things around using the ! operator:
var bob = false; // <-- this is opposite of above
while( ! bob ) { // <-- so we'll use the ! to flip it
// this will run one time.
bob = true;
}
So the tricky part is that the "negation" operator leverages the funky "truthiness" understanding in the language... we can leverage this and "flip" truthiness entities like string, array, object to check if they "are" or "are not".
So based on our understanding of "truthyness" we can say:
var bob = "silly";
bob == true; // true
!bob == false; // true
var sally = 0;
sally == false; // true
!sally == true; // true
NOTE: Strict type evaluation is handled through triple equals === and !==
Now to the point (let's make things simpler):
let yourName;
while ( ! yourName ) {
// "prompt" will
// 1. Block all javascript execution, including this while loop.
// 2. Return null (falsy) or a text string (truthy)
yourName = prompt("Who are you?");
}
So in the above, we are preventing the script from execution until the prompt returns a valid name.
The purpose is to execute a statement while Boolean expression evaluates to false
!false === true

Difference between includes and hasOwnProperty in array search in JS

What is the difference between includes and hasOwnProperty for searching an element in an Array in JS in terms of time and space complexity?
Both can be used to find whether an element exists in an Array or not.
hasOwnProperty returns a boolean value indicating whether the object on which you are calling it has a property with the name of the argument and as everyone The includes() method determines whether a string contains the characters of a specified string. include method returns true if the string contains the characters, and false if not. Also, it's the case sensitive.
and at the end, I think the question is based on a false assumption.
Both can be used to find whether an element exists in an Array or not.
Incorrect. includes checks if any of the elements in the array match the argument. hasOwnProperty checks to see if the Array has a property that matches the argument
$ const array = ['test', 'another'];
$ array.includes('test')
true
$ array.hasOwnProperty('test')
false
$ array.includes('length')
false
$ array.hasOwnProperty('length')
true
You can see that includes and hasOwnProperty do not return the same result, so it is pointless to compare efficiency.
includes is checking if your array contains specified value, while hasOwnProperty checks if your array has specified property name in its __proto__:
const arr = [1, 2, 3];
arr.prop = 'Some prop';
arr.includes(2); // -> true
arr.hasOwnProperty(2); // -> false
arr.includes('prop'); // -> false
arr.hasOwnProperty('prop'); // -> true

JavaScript - include() - A check to see if multiple elements are in an array

hope you can help. I've got an empty array in my project which fill up as certain buttons are pressed (using push()). I want to know when a certain set of elements are in the array.
In the below code, it seems to work, the 3 elements are all in the array so it prints 'yes'. If I take out the last element ("TR"), it prints 'nope'. However, if I take out either of the first 2 elements, it prints 'yes'. It seems to be only focusing on the last element in the includes() function.
Is there any way to have the include() or something similar, check to see if all elements are in my array? Keep in mind that the array could have many more elements and they won't be sorted.
Thanks in advance.
var arr = ["TL", "TM", "TR"];
if (arr.includes("TL" && "TM" && "TR")){
console.log("yes");
} else {
console.log("nope");
}
The issue is in your if statement because includes() returns a boolean based on the string parameter. A better way of doing this would be to use something like:
if(arr.includes("TL") && arr.includes("TM") && arr.includes("TR")) {
console.log("yes");
}
If you have lots of elements in your array I would suggest something more along the lines of:
var flag = true;
for(i=0; i<arr.length; i++) {
if(!arr.includes(arr[i])) {
flag = false;
}
}
if(flag) {
console.log("yes");
}
Even though the above answers show methods to get your desired result, I'm surprised no one has addressed why your original attempt didn't work. This gets into some foundational rules that JavaScript follows: how functions are called, logical operator evaluation, and operator precedence.
Calling arr.includes()
First off, you have a function includes which takes a single string argument. You have given this argument an expression instead of a string, so it is going to evaluate the expression. If the evaluation produces a string, it will return that value. If it produces a different type, it will attempt to convert the result to a string. So to clear it up, you haven't given it 3 strings to look for, but one expression that will be evaluated and become the string you are looking for.
Logical Operator Evaluation
But what is the value of that string? In JavaScript, the logical operators work in a way that can shortcut and return one of the values being evaluated. In most cases, we'd be comparing boolean values, and get true or false from the evaluation, but we're working with strings here, not booleans. Strings in JavaScript can be evaluated as "truthy" or "falsy", the former being any string that has length and the latter being a string with no length (an empty string). With this in mind, the shortcut functionality of the logical AND && operator will look at the first value in the expression, and if that value is "falsy" it will return that value. If that value is "truthy" it will look at the other side of the expression and return its value.
MDN describes this logic pretty well. Given expr1 && expr2 here's the logic:
Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
Order Precendence
Finally, a note on order precedence. Logical AND && is of equal precendence to itself, so your expression will read from left-to-right. If, say, your expression was "TL" || "TM" && "TR" the "TM" && "TR" expression would be evaluated first since logical AND && has a higher precendence than logical OR ||.
Evaluating Your Expression
Knowing all of this, we can pick apart what your expression is doing:
"TL" && "TM" && "TR" is comprised of all logical AND operators, so we will read this from left-to-right, starting with "TL" && "TM". Since "TL" is a truthy string, the other side of the expression is returned which is "TM". The next expression is then "TM" && "TR", of which "TM" is a truthy value, so "TR" is returned. In the end, the includes function is checking if the value of "TR" exists in the array, and ultimately returns true.
Again, do mark one of the others as answers here. Looping through the values you want to search for in the array is what you're looking for, and writing your own loop or using reduce accomplishes that, but I wanted to explain why your initial attempt probably seemed odd and clear up just what was happening.
This can be done cleanly using the reduce method of arrays. Here's how to do it with your example:
var arr = ["TL", "TM", "TR"];
var fails = ["TL"] // This will return false
var succeeds = ["TL", "TM", "TR"] // This will return true
var includesAll = (array_to_check) => arr.reduce(
(accumulator, current) => accumulator && array_to_check.includes(current),
true
)
if (includesAll(succeeds)){
console.log("yes");
} else {
console.log("nope");
}

Regular expressions in JavaScript with the global flag

It appears that the RegExp intrinsic is stateful.
So calling it twice on the same string will yield different results when the global flag g is supplied, as it advances a search along the string.
So:
var r = /(\d{3})/g;
console.log(r.test('123')); // true
console.log(r.test('123')); // false - because the search has moved past the first match
But if I add an intermediate test, I get the following:
var r = /(\d{3})/g;
console.log(r.test('123')); // true
console.log(r.test('456')); // true
console.log(r.test('123')); // true!
So is it correct to say that RegExp instances operate on the principle of considering only the last string evaluated? If the string differs from the last, it is effectively reset?
So is it correct to say that RegExp instances operate on the principle of considering only the last string evaluated?
yes
If the string differs from the last, it is effectively reset?
correct
If the global flag is omitted, is the regular expression reset in between tests?
right
Check out RegExp#lastIndex

What does an exclamation mark before a variable mean in JavaScript

I'm trying to learn JavaScript by going through some code in an application and I keep seeing !variable in if conditions. For example:
if (!variable.onsubmit || (variable.onsubmit() != false)) {
What is it? Some kind of test if the variable is empty?
! is the logical not operator in JavaScript.
Formally
!expression is read as:
Take expression and evaluate it. In your case that's variable.onsubmit
Case the result of that evaluation and convert it to a boolean. In your case since onsubmit is likely a function, it means - if the function is null or undefined - return false, otherwise return true.
If that evaluation is true, return false. Otherwise return true.
In your case
In your case !variable.onsubmit means return true if there isn't a function defined (and thus is falsy), otherwise return false (since there is a function defined).
Simply put - !variable means take the truth value of variable and negate it.
Thus, if (!variable) { will enter the if clause if variable is false (or coerces to false)
In total
if (!variable.onsubmit || (variable.onsubmit() != false)) {
Means - check if variable.onsubmit is defined and truthy (thus true), then it checks if calling onsubmit returns a result that coerces to true. In a short line it checks if there is no onsubmit or it returns true.
Next time, how do I find this myself?
MDN has a list of operators here.
The language specification specifies such operators, though being the official specification it does contain some jargon which might be hard to understand.
It is a negation operator used for truth tests on a variable.
var myVariable = 1;
if ( ! myVariable )
{
// myVariable evaluates as false
}
if ( myVariable )
{
// myVariable evaluates as true
}
The selected answer already answers the question. One thing to add in this is that ! operator can be used in a rather interesting fashion.
obj = {}
if (!!obj) {console.log('works')} // !!obj = true
obj = undefined
if (!!obj) {console.log('does not work')} // !!obj = false
So double !! will change any expression to a boolean value with no exceptions.
This has a very peculiar use case in some cases.
Lets say there is a function that returns either true or false and nothing else. In that case one could just change return returnValue to return !!returnValue for extra caution (although not need in most of the cases)
Conversely, if a function only accepts true or false and nothing else, one could just call the function as functionA(!!parameter) instead of functionA(parameter), which again is not needed in most of the cases, but could ensure extra security
! is a logic reversal operator, if something was true it will change it to false, if something is false, it will change to true.
example, we know that empty string or 0 in boolean is false.
let a = Boolean("")
console.log(a) // shows false, because empty string in boolean is false
console.log(!a) // shows true, because logic is reversed
easier example:
let a = 5
let b = 1
let c = a > b
console.log(c) // shows true, since a,5 is bigger than b,1
console.log(!c) // shows false, since logic is now reversed

Categories

Resources