473,748 Members | 6,161 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

The use of the in keyword in a comparision??

Hi all,

I was messing around with someone elses script when I noticed that he
had used the in keyword in an if conditional to compare a string with a
object. I've never seen this used and was wondering about the logic
behind it. I had previously assumed that the in keyword passed the
properties of an object to a variable, as you do in a for/in loop. How
is it that it can be used in a comparsion?

example:

var elements = {'html':true}

var myElement = "html";

if(myElement in elements)
alert("True");

Dec 12 '05 #1
8 4787
Morgan wrote:
I was messing around with someone elses script when I noticed that
he had used the in keyword in an if conditional to compare a string
with a object.


The `in' operation in a boolean expression does not compare a string
with an object, it evaluates to `true' iff the referred object has a
property with the string as name or inherits that from its prototype.

RTFM: <URL:http://jibbering.com/faq/#FAQ3_2>
PointedEars
Dec 12 '05 #2
RobG wrote:
Thomas 'PointedEars' Lahn wrote:
Morgan wrote:
I was messing around with someone elses script when I noticed that
he had used the in keyword in an if conditional to compare a string
with a object. The `in' operation in a boolean expression does not compare a string
with an object, it evaluates to `true' iff the referred object has a
property with the string as name or inherits that from its prototype.

RTFM: <URL:http://jibbering.com/faq/#FAQ3_2>


Gee Thomas, that was a bit obscure - Section 3.2 has 30 links. :-p
[...]


I explained the operator _and_ referred the OP to the reference materials
that he obviously had never considered to read before posting. "messing
around with someone elses script" and "compare a string with a object"
clearly indicates that it is a Good Idea to do that now.
For the OP, it's covered in the ECMAScript Language Specification
Therefore the link to the list of all online resources.
Section 11.8.7 and Mozilla Developer Center here:


JavaScript is not the only ECMAScript implementation discussed here.
Therefore ...
HTH

PointedEars
Dec 13 '05 #3
Thomas 'PointedEars' Lahn wrote:
Morgan wrote:

I was messing around with someone elses script when I noticed that
he had used the in keyword in an if conditional to compare a string
with a object.

The `in' operation in a boolean expression does not compare a string
with an object, it evaluates to `true' iff the referred object has a
property with the string as name or inherits that from its prototype.

RTFM: <URL:http://jibbering.com/faq/#FAQ3_2>


Gee Thomas, that was a bit obscure - Section 3.2 has 30 links. :-p

For the OP, it's covered in the ECMAScript Language Specification
Section 11.8.7 and Mozilla Developer Center here:

<URL:
http://developer.mozilla.org/en/docs...rs:in_Operator


Another way of writing it is:

var elements = {'html':true}
var myElement = "html";
if( elements[myElement] ) {
alert("True");
}
Presumably the idea is to use the value if the property exists, so using
a style that even Thomas should be happy with:

var o = elements && elements[myElement];
// if elements exists and has a property with a name that
// matches the value of myElement, 'o' is set to the
// value of elements[myElement]
// Otherwise 'o' will be set to undefined.

if ('undefined' == typeof o){ // Or test for ! a specific type

// Handle not getting (a specific typeof) o.
alert('No property with name ' + myElement);
return;
}

// Use o...
alert( o );

--
Rob
Dec 13 '05 #4
RobG wrote:
[...]
Another way of writing it is:

var elements = {'html':true}
var myElement = "html";
if( elements[myElement] ) {
alert("True");
}
That is _not_ equivalent to the `in' operation. That latter boolean
expression will only evaluate to `true' as long as there is a property
of that name _and_ the value of that property is a true-value.

var
elements = {html: null},
myElement = "html";

if (elements[myElement])
{
// this will never be called although the property exists
alert("True");
}
Presumably the idea is to use the value if the property exists, so using
a style that even Thomas should be happy with:
I am not. And I am not unhappy with it. It is simply not equivalent.
var o = elements && elements[myElement];
// if elements exists and has a property with a name that
// matches the value of myElement, 'o' is set to the
// value of elements[myElement]
// Otherwise 'o' will be set to undefined.
This will break with a ReferenceError if `elements' is not
variable-instantiated before, i.e. if `elements' does not exist.
if ('undefined' == typeof o){ // Or test for ! a specific type
// Handle not getting (a specific typeof) o.
alert('No property with name ' + myElement);
return;
}


As I pointedEars^H^H ^H^H out ;-) before, comparing the value of the
`typeof` operation against the string value "undefined" also is not
equivalent to the `in' operation [I do not think there is an equivalent
-- hasOwnProperty( ) returns `true' only if the object itself has the
property]. It merely serves as a viable alternative for AOM/DOM
feature testing. Try this:

var o = {foo: undefined};
alert(typeof foo.bar); // "undefined"

That is probably a theoretical construct, however, if the `foo' property
would be assigned a variable (not fixed) value, entirely possible (ignoring
that implementations may allow to redefine the global `undefined' property
in which case it would be already a variable value.)
PointedEars
Dec 13 '05 #5
>> Another way of writing it is:
var elements = {'html':true}
var myElement = "html";
if( elements[myElement] ) {
alert("True");
}
That is _not_ equivalent to the `in' operation.
No luck there then, Rob. ;-) Imagine getting this guy a christmas gift.
I explained the operator _and_ referred the OP to the reference materials
that he obviously had never considered to read before posting.


I did make an effort to look for a defination of the in keyword,
however I couldn't find topics on it in the groups history or on google
search, lots of web pages appear to match the word "in". Also your faq
is does not have a list of keyword definations, considering the amount
of quizzes about the "this" keyword generally, this might be a good
idea. Whats more I do have an ECMAScript spec on my desktop, and this
is what I found under in operator:

11.8.7 The in operator
The production RelationalExpre ssion : RelationalExpre ssion in
ShiftExpression is evaluated as follows:
1. Evaluate RelationalExpre ssion.
2. Call GetValue(Result (1)).
3. Evaluate ShiftExpression .
4. Call GetValue(Result (3)).
5. If Result(4) is not an object, throw a TypeError exception.
6. Call ToString(Result (2)).
7. Call the [[HasProperty]] method of Result(4) with parameter
Result(6).
8. Return Result(7).

return WTF???;

Forgive me, if I didn't have a burning fascination to find to crawl
through 188 pages worth at the time. Frankly it was just something that
I was mildly interested in. I really didn't think it would be such a
big deal for you.

Here is a new keyword for you: pedantic

Dec 13 '05 #6
Morgan wrote:
11.8.7 The in operator
The production RelationalExpre ssion : RelationalExpre ssion in
ShiftExpression is evaluated as follows:
[...]
return WTF???;
I already told (you) what it evaluates to. If you are not able
to understand the abstract specification, you are free to try the
Client-Side JavaScript Reference at developer.mozil la.org or
the MSDN Library at msdn.microsoft. com/library. Both are included
in the FAQ section I pointed to.
[...]
Here is a new keyword for you: pedantic


Here is a new keyword for you: ignorant.
score adjusted

PointedEars
Dec 13 '05 #7
Thomas 'PointedEars' Lahn said the following on 12/13/2005 4:18 PM:
Morgan wrote:


<snip>
[...]
Here is a new keyword for you: pedantic

Here is a new keyword for you: ignorant.


Too bad they both apply to you Thomas.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Dec 13 '05 #8
Morgan wrote:
Another way of writing it is:
var elements = {'html':true}
var myElement = "html";
if( elements[myElement] ) {
alert("True");
}

That is _not_ equivalent to the `in' operation.

No luck there then, Rob. ;-) Imagine getting this guy a christmas gift.


I'm OK with Thomas... particularly since I baited him anyway.

I did make an effort to look for a defination of the in keyword,
however I couldn't find topics on it in the groups history or on google
search, lots of web pages appear to match the word "in".
A bit like searching for keywords like 'and' or 'not' I imagine! :-)
[...]
Forgive me, if I didn't have a burning fascination to find to crawl
through 188 pages worth at the time.


In order to find it you would either have to have done that or known
that you were looking for a relational operator, in which case you would
already have known the answer. It's a perfectly reasonable question to
ask here.

--
Rob
Dec 14 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1475
by: Florian Lindner | last post by:
Hello, I've read the chapter in the Python documentation, but I'm interested in a a more in-depth comparision. Especially regarding how pythonic it is and how well it performs and looks under Windows. I've some C++ experiences with Qt, so I'm very interested to have PyQt compared to wxWindows and Tk. How fast does PyQt catches up with the versiones released from Trolltech? etc.. Thx, Florian
1
1738
by: John Black | last post by:
Hi, In using find_if() you need to name a comparision function which normally is a static function, but sometimes it is really inconvinient for this, let's take this example, class MyClass{ vector<int> myVec; void func(); };
2
2991
by: Ashwin Kambli | last post by:
Hi, I am doing a study on the performance comparision of C# and Java. Links to any articles on this topic will be greatly appreciated. Thanking you, Ashwin
9
1474
by: jaym1212 | last post by:
Execution of the following simple code results in variable z being assigned the value of 1 ... x = 234; y = 234; z = (x == y); .... but I wanted z to be 234. What is the most efficient method (min CPU cycles) of doing this? (I realize it could be accomplished as follows)
3
1641
by: kd | last post by:
Hi All, How to perform case-insensitive comparision of strings? Would there be some kind of an indicator, which when set to true, would allow case-insenitive comparision of strings using if/select case, etc; after performing the case-insenisitive compare, the indicator can be reset to allow the conventional comparision of strings? kd
2
1026
by: I Don't Like Spam | last post by:
I know this should be simple but I can't find it. Dim A as new object Dim B as object B = A Do Bunch of stuff Check if B still = A
3
1114
by: krallabandi | last post by:
Hi, I have a requirement to compare 2 ASCII text files and show the results in an aspx form. The comparision algorithnm, out put should be similar to VSS (differences between 2 files). I really appreciate if you can tell me the best way of doing this and what web controls suits this requirement.
2
2664
by: nirav.lulla | last post by:
I have been given the task to come up with Requirements, Comparision and Migration document from Shadow Direct to DB2 Connect. I am very new much to all this, but kind of know a little bit about both of them. There has been a lot of pressure from business to move to DB2 Connect from Shadow Direct which the company is currently using since almost 7 years. I would greatly appreciate if any one of you can help or send me some comparision...
3
4278
by: abctech | last post by:
I have an Html page, user enters a Date (dd-mm-yyyy) here. There's a servlet connected in the backend for processing this submitted information, it must have a method to compare this entered date with the dates obtained from the backend table which again are retrieved as strings (dd-mm-yyyy). Can anyone suggest how to carry out comparision between these date strings? Eg: String Entered Date: "28-02-2007" String Backend Date:...
0
8989
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8828
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9367
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9319
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9243
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3309
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2213
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.