Global flag in javascript [duplicate] - javascript

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 3 years ago.
function countSmileys(arr) {
let regex = /^([:;])([-~])*([)D])$/
if(arr.length === 0) {
return 0;
}
return arr.filter(el => {
return regex.test(el);
})
}
console.log(countSmileys([':(', ';)', ':)', ';o>', ':(', ':>', ';~D']));
I wrote the code that verify to see if that is smiley face or not.
for eyes, it takes only ':/;' , for nose, '-/~' (it is fine if there is a nose)
for lips, ')/D'.
So, I wrote the regular expression with global flag first. then
it only gives
[';)', ';~D']
I finally got the right result when I eliminated g flag.
[';)', ':)', ';~D']
I have been confused to use g flags. can anyone explain this?

The issue here is using test() with the global flag on a string advances the regex's lastIndex - even if you are testing a different string in a subsequent run.
Citing from the MDN: Using test() on a regex with the global flag
If the regex has the global flag set, test() will advance the
lastIndex of the regex.
A subsequent use of test() search at the substring of str specified by lastIndex (exec() will also advance the lastIndex property).
It is worth noting that the lastIndex will not reset when testing a different string.

Related

Difference between return ("abcd") and return "abcd"? [duplicate]

This question already has answers here:
Why use parentheses when returning in JavaScript?
(9 answers)
Closed 6 years ago.
I'm struggling with some JavaScript code that has examples that return a string in parens. Is there any difference between this:
var x = function() {
return "abcd";
}
And
var x = function() {
return ("abcd");
}
They are the same.
The parenthesis, i.e. grouping operator, here will just work as higher precedence, so that'll be evaluated first, and then the value will be returned.
There's no difference, at least in the way it is written.
Consider,
var x = 1 + 2;
vs
var x = (1 + 2);
Some prefer writing brackets around return statement but it is optional and often unnecessary. But I would advise stick to your existing code style.
In reference to this question the parenthesis do not have a specific meaning as a string is being returned. There is no expression evaluation involved so both the return statements work in the same way. In case we have an expression that needs to be evaluated, the parenthesis will provide a liberty to first evaluate the expression and then return the desired value according to the precedence rules.

Why is the !! preferable in checking if an object is true? [duplicate]

This question already has answers here:
What is the difference between if(!!condition) and if(condition)
(3 answers)
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 8 years ago.
Some JavaScript examples use !! to check if an object is available
// Check to see if Web Workers are supported
if (!!window.Worker) {
// Yes, I can delegate the boring stuff!
}
Why is this preferred to just if (window,Worker) and in what context would this fail?
It isn't preferable, or even different, in this case. The double-bang converts the variable that follows it into a Boolean value (similar to wrapping in the Boolean() constructor). Gets around potential problems with truthy and falsey variables.
However, putting the variable alone in an if() clause does the same thing (it also resolves the contents of the if's parens to a hard Boolean).
The double-bang can prove helpful in other cases, such as if you want to return a true or false at the end of a function based on a variable's truthiness/falsiness. That would be rather than:
if(condition) {
return true;
} else {
return false;
}
You could simply write:
return !!condition;
It isn't.
!! is useful when you are passing an object into a function that (like jQuery's toggle()) checks to see if its argument is a boolean, or when the function might stash its argument and thereby prevent the object from being collected.
The case you cite is neither of those. Use a bare if.
In the condition of an if statement both versions will do the same thing and its a stylistic choice. Some people prefer use !! to highlight that Worker is not a boolean and is being converted tto boolean.

Can anyone explain why linebreaks make return statements undefined in JavaScript? [duplicate]

This question already has answers here:
Why does the value returned should be on the same line as the return statement in JavaScript?
(4 answers)
Closed 6 years ago.
This has been the source of my pain for many hours. Can anyone explain why this is the case?
function x(){
return //when there's a line break it doesn't work
2;
};
alert(x());
function y(){
return 4; //when there's no line break it works
};
alert(y());
//Can anyone explain this?
I always thought that JavaScript didn't care about line breaks. If you have links to ECMA official documentation on this, I'd be grateful. Thanks!
Here are the ECMAScript rules for Automatic Semicolon Insertion. The relevant section is:
When a continue, break, return, or throw token is encountered and a LineTerminator is encountered before the next token, a semicolon is automatically inserted after the continue, break, return, or throw token.
In short, your code is parsed as if it were:
return;
2;
Unlike most other languages, JavaScript tries to "fix" your code by adding semicolons where it thinks you have forgotten them.
Return statements are such a case - if there is a linebreak after a return statement, it will be interpreted as return;
JavaScript treats a endline after return as if there was an ;
So in:
return
2;
2; is unreachable code.
And a sole return in JavaScript returns undefined. Like a function without a return does.
JS gramma from mozilla
http://www-archive.mozilla.org/js/language/grammar14.html#N-Statement
Note:
the OptionalSemicolon grammar state can sometimes reduce to «empty»

Is JavaScript test() saving state in the regex? [duplicate]

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 7 years ago.
Open up a browser console and execute the following code:
var foo = /foo/g;
Then,
foo.test("foo") // true
Then,
foo.test("foo") // false
If you continue to execute foo.test("foo"), you will see alternating true/false responses as if the var foo is actually being modified.
Anyone know why this is happening?
Yes, that's how .test() and .exec() work when the regex is g global. They start at the end of the last match.
You can observe the current last index on the regular expression object using the .lastIndex property.
It's a writeable property, so you can reset it to 0 when/if you need. When the regex is run without finding a match, it automatically resets to 0.
The regex keeps the position of the last test. This allows searching of long strings. You can reset this by setting lastIndex = 0;

Why is the JavaScript RegExp.test() method behaving as a toggle? [duplicate]

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 6 years ago.
Can anyone explain why the alert() in the following JavaScript code is firing? It appears to be a bug in the RegExp.test() method which reverses its previous decision each time you run the method. I'm using IE7.
I've found a replacement that appears solid, using the string.search(regex) method instead. But, I'm curious whether anyone knows something about this.
var styleHasWidthRegex = /\bwidth\s*\:/ig;
var styleText = "WIDTH: 350px";
var result1 = styleHasWidthRegex.test(styleText);
var result2 = !styleHasWidthRegex.test(styleText);
if (result1 == result2) {
alert("This should never happen!");
}
Your regex has the global (g) flag set. Every time it is executed, it'll update an internal index (the lastIndex property) specifying where it left off, and begin searching at that point the next time through.
Of course, you don't really want that - you want it to start at the beginning every time. So ditch the g flag.
See also: Inconsistent javascript logic behavior
In this scenario, you should be needing a global tag anyways, since in css declarations a property should only be declared once.

Categories

Resources