Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript test function [duplicate]

Tags:

javascript

Possible Duplicate:
Question on this JavaScript Syntax (“What Does This Do?”)

in this article i found this:

/xyz/.test(function(){xyz;})

i looked at this and i coudn't figure out how does the xyz passed to the invoker. so i did some similar test in the console:

/xyz/.test(function(){xya;}) > false
/xyz/.test(function(){xyz;}) > true    

/xyz/.test(function(){'xya';}) > false
/xyz/.test(function(){'xyz';}) > true

/xyz/.test(function(){console.log('xya');}) > false
/xyz/.test(function(){console.log('xyz');}) > true

/xyz/.test(function(xya){}) > false
/xyz/.test(function(xyz){}) > true

/fuc/.test(function(){}) > false
/func/.test(function(){}) > true

it seems that the .test() function converts the argument to string and then does the test. so why /xyz/.test(function(){xyz;}) used rather than /xyz/.test('xyz')?

like image 569
Gergely Fehérvári Avatar asked Dec 14 '11 11:12

Gergely Fehérvári


People also ask

How do you check if an element is repeated in a list JavaScript?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.

Can JavaScript Set have duplicate values?

The Set object lets you store unique values of any type, whether primitive values or object references. you are passing new object not reference so it is allowing to add duplicate.


1 Answers

Its effectively testing that:

(function(){xyz;}).toString()

returns recognizable javascript source code:

"(function(){xyz;})"

as opposed to something funky that some implementations may return.

It uses .test to convert the function to a string then verifies that an internal token (xyz) is visible in the result.

like image 159
Alex K. Avatar answered Oct 12 '22 04:10

Alex K.