Of course that statement on it’s own can obviously be shown to be fallacy. When you consider the context of continuous improvement, learning or generally advancing our own capabilities and understanding, though, this statement can be quit liberating. Why? Because without failure, you are not learning anything.

Let’s say you are faced with a problem, a challenge, or a need that you are trying to fulfill. If your first attempt and creating a solution is successful you have learned nothing. You already knew how to provide the solution. it only took some thinking to analyze the situation and apply your existing knowledge. If, however, you stretch yourself as far as you can, put every last effort that you currently have into the solution and employ all of your existing knowledge, capabilities and resources but you still fail the first time, fail again and fail some more before finding a solution, then you are learning. You are stepping outside of your own knowledge and capabilities, learning new things and gaining new insight and experience that leads to new solutions for situations that you did not know how to previously solve.

Consider any endeavor to learn, from this light. Whether it’s adopting a new process or methodology such as an agile process or lean toolkit, using a new tool or technology, contributing to an open source project, or learning how to ride a bicycle – having the correct mentality, that failure is required, will undoubtedly help you succeed.

Mike Rother said it quite well in his book, Toyota Kata (p.138-139), when faced with people who are merely capitulating because they were told to do so, or because they want to prove that some change or new way of doing things won’t work:

Eventually it dawned on me how to deal with this question. Now, when arms fold up and people say, “Let’s see if this will work,” I say, “I can save you the time. We already know it probably won’t work. Despite our best efforts to plan this, we know that within a short time there will be ‘charred and glowing pieces’ lying around. We just don’t know in advance when, where, or why it will fail.”

Think about the last time you delivered any fragment of functionality to a customer or customer representative for feedback. Did you expect that they would be 100% satisfied and would accept it as is? Not if you were asking for feedback. When the customer responds with changes or updates that they would like, you have effectively failed. Hopefully you have failed within a very short cycle, though, and are able to incorporate the feedback of the customer into the next delivery or demonstration.

They key is not learning from mistakes and failures. The key is failing fast, failing cheap, and responding to those failures in a timely manner so that you can learn quickly and still reach your objectives. Failure is critical to success and learning, and short feedback cycles are critical to the effective use of failure as a learning tool.

]]>http://vajiv.com/blog/ti%e1%ba%bfn-si-alan-phan-c%c6%a1-h%e1%bb%99i-danh-cho-cac-b%e1%ba%a1n-tr%e1%ba%bb-luon-hi%e1%bb%87n-di%e1%bb%87n-%e1%bb%9f-kh%e1%ba%afp-m%e1%bb%8di-n%c6%a1i/feed/0Different points of Java and C#http://vajiv.com/blog/different-points-of-java-and-c/
http://vajiv.com/blog/different-points-of-java-and-c/#commentsMon, 03 Oct 2011 07:26:52 +0000http://vajiv.com/blog/?p=495Recently I’ve started discovering C# in .NET world. As my background is Java and its world, I encounter various difficulties in learning C#. It’s not a bad idea for me to take note different points of Java and C#, that would not only let me validate my understanding well, but also help those who are in a situation like me can quickly stick to the core of both worlds.

I make comparison based on:

Java 6

C# 4.0

Points of difference are written:

in pairs

one by one

in no order

Mostly I will collect materials from Internet for explanation and demonstration. Feel free to comment or drop me an email if I wrote something wrong. Thank you!

1. Class variables

Java

Member variables in a class are called fields.

public class Bicycle {
// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;
}

C#

A class can have fields and properties. They look similar from outside but from inside, a field has no logic while a property may have logic.

public class Stock

{

decimal currentPrice; // The private “backing” field

public decimal CurrentPrice // The public property

{

get { return currentPrice; }

set { currentPrice = value; }

}

}

2. Access modifiers

Java

Access Levels

Modifier

Class

Package

Subclass

World

public

Y

Y

Y

Y

protected

Y

Y

Y

N

no modifier

(package-private)

Y

Y

N

N

private

Y

N

N

N

The first data column indicates whether the class itself has access to the member defined by the access level. As you can see, a class always has access to its own members. The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member. The third column indicates whether subclasses of the class “declared outside this package” have access to the member. The fourth column indicates whether all classes have access to the member.

The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal

The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

3. Constant variables

Java

A final variablecan only be initialized once, either via an initializer or an assignment statement. It need not be initialized at the point of declaration: this is called a ‘blank final’ variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared: otherwise, a compile-time error occurs in both cases.

C#

Constants are declared with the const modifier. Only the C# built-in types (excluding System.Object) may be declared as const. For a list of the built-in types, see Built-In Types Table (C# Reference). User-defined types, including classes, structs, and arrays, cannot be const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed.

Constants must be initialized as they are declared.

class Calendar1
{
public const int months = 12;
}

When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

3. Static Constructors

Java

Static constructor is not really supported by Java, but you can use static initialization block instead. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static {
// whatever code is needed for initialization goes here
}

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

C#

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:

A static constructor does not take access modifiers or have parameters.

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

A static constructor cannot be called directly.

The user has no control on when the static constructor is executed in the program.

A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

4. Packages and Namespaces

Java

Classes and interfaces are organized into packages, which in fact are directories on operating system. Package declaration must be first and before any other statement (except comment) in a Java source file.

C#

]]>http://vajiv.com/blog/different-points-of-java-and-c/feed/0CEO vs COOhttp://vajiv.com/blog/ceo-vs-coo/
http://vajiv.com/blog/ceo-vs-coo/#commentsMon, 19 Sep 2011 16:58:54 +0000http://vajiv.com/blog/?p=485You can probably rate the effectiveness of a CEO by the stack of papers on his desk. The larger the stack, the less he or she is probably operating as a CEO. The larger the stack, the more he or she is probably operating as a COO.

As I transitioned, over the years, from an entrepreneur who is operating a one or two-person company into someone who is operating a company employing several hundred people, it occurred to me that the size of the stack has progressively diminished.

I have always been somewhat retentive with respect to the configuration of my desk. Whether I was in college, law school, or even in my law or business office, I always maintained a stack of papers, which was my “In” basket, on the left-hand side of my desk.

If an action had not been generated, it simply sat there in the stack. If I took an action on it, I made the notes or dictated and passed it along. I might get that think back at some future time but so be it.

In the meantime, it was somebody else’s problem to act on.

Over the years, I watched the nature and status of that stack shift, not only based on my effectiveness but also based on how I was operating as a manager.

Regardless of whether I was a start-up entrepreneur, someone operating at a COO capacity, or someone operating at a CEO capacity I could always tell how effective I was based upon the size of the stack. The larger the stack, the less effective I was at running an actual organization. The smaller the stack, the more the reverse was true.

An entrepreneur’s responsibility is to do absolutely everything that needs to be done to get the job accomplished correctly. Therefore, the stack is immense. You are individually taking personal responsibility for everything to be done, right down to the last farthing of money in your bank account. It’s understandable that the stack is high, and it rightfully should be, because you simply do not have the resources to be able to hire people to delegate to, not only to monitor objectives but also to accomplish those objectives.

A COO operates in fundamentally the same way with one exception.

Whereas an entrepreneur is actually doing it himself or herself, a COO is still personally doing it through other people. The bottom line, however, is that the COO is responsible. Therefore, whether the job is ultimately acquitted correctly or not is, in the final analysis, the responsibility of the COO. The COO may do something himself or herself. The COO may choose to delegate it. But either way, the COO is responsible. Therefore, the stacks shrink, but it’s still there.

The CEO moves along that continuum. The CEO’s responsibilities are to operate through executive and management teams, not through operational teams. Therefore, what should be in front of the CEO are issues associated with performance commitments from his or her executive or management teams and external communications, which need to be either handled or farmed out. Otherwise, the entire output of the CEO’s desk is the intellectual property of the CEO: those things a CEO is thinking that he or she intends on transferring to the executive or management team.

The larger the stack on the CEO’s desk, the less effective the CEO’s relationship to the executive and management teams. The smaller the stack, the more effective.

Over the past years, I remember reading about executives in major cities such as New York, San Francisco, Los Angeles, and so forth, who literally have one or two pieces of paper on their desks. Nothing else! They are not working on any component of operations. They are working on the company’s present, through executives and managers, and on its future, represented by nothing other than a one or two-page synopsis sitting on their desks. Otherwise, their desks were clear. Cleaned. Pledged. Polished.

I wondered how that could be, but I understand it better now.

The more I have to operate as an entrepreneur or as a COO, the less I have the opportunity to operate as a CEO. And, if I am truly operating as a CEO, I continue to monitor operations on an exception basis through the management team, but I remove myself from operational components of the company. What I am spending my time on is sculpting how I want it to look based on what it looks like today. That might take 100 employees or 1,000 employees. But it probably takes no more than three or four items on my desk at any one time.

The transition from entrepreneur through COO to CEO has been simultaneously interesting, challenging, and agonizing…but, I wouldn’t trade the experience in a million years.

Original writing date: November 2002

(Source: http://www.ourlifeinbusiness.com/2008/02/ceo-vs-coo/)

]]>http://vajiv.com/blog/ceo-vs-coo/feed/0String literal vs String object in Javahttp://vajiv.com/blog/string-literal-vs-string-object-in-java/
http://vajiv.com/blog/string-literal-vs-string-object-in-java/#commentsWed, 07 Sep 2011 08:12:17 +0000http://vajiv.com/blog/?p=478If you’re a Java developer, you might have ever been in trouble distinguishing String literal and String object. I myself have had the trouble too. So I make a search on the internet for this topic and collect good articles for everyone to memorize.

Question

what is difference between String str = new String(“abc”); and String str = “abc”;

Good answer

When you do this:

String str = "abc";

You are calling the intern() method on String. This method references an internal pool of ‘String’ objects. If the String you called intern() on already resides in the pool, then a reference to that String is assigned to str. If not, then the new String is placed in the pool, and a reference to it is then assigned to str.

Method description of java.lang.String

intern

Returns a canonical representation for the string object.A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned. String literals are defined in §3.10.5 of the Java Language Specification

Returns:

a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

]]>http://vajiv.com/blog/string-literal-vs-string-object-in-java/feed/0Anh Linh wedding album servicehttp://vajiv.com/blog/anh-linh-wedding-album-service/
http://vajiv.com/blog/anh-linh-wedding-album-service/#commentsTue, 23 Aug 2011 17:49:35 +0000http://vajiv.com/blog/?p=469
]]>http://vajiv.com/blog/anh-linh-wedding-album-service/feed/0CSF firewall for your CPanel VPS and FTP issuehttp://vajiv.com/blog/csf-firewall-for-your-cpanel-vps-and-ftp-issue/
http://vajiv.com/blog/csf-firewall-for-your-cpanel-vps-and-ftp-issue/#commentsSun, 21 Aug 2011 17:47:51 +0000http://vajiv.com/blog/?p=463When you have a CPanel VPS, you may also want to have a way to manage firewall easily and effectively. I found that CSF is a good option here. It is free and has UI integration with Web Host Manager. Its features and performance are not so bad. It is recommended in many VPS forums.

That means, your FTP client opens data connection in passive mode and tries to MLSD (list content of a given directory) on server, but it fails. The issue lies between CSF configuration and FTP server configuration: passive ports configured in FTP server are not opened in CSF firewall. So one way to fix is:

It is important when using an SPI firewall to ensure FTP client applications
are configured to use Passive (PASV) mode connections to the server.

On servers running Monolithic kernels (e.g. VPS Virtuozzo/OpenVZ and custom
built kernels) ip_conntrack and ip_conntrack_ftp iptables kernel modules may
not be available or fully functional. If this happens, FTP passive mode (PASV)
won’t work. In such circumstances you will have to open a hole in your firewall
and configure the FTP server to use that same hole.

For example, with pure-ftpd you could add the port range 30000:35000 to TCP_IN
and add the following line to /etc/pure-ftpd.conf and then restart pure-ftpd:
PassivePortRange 30000 35000

For example, with proftpd you could add the port range 30000:35000 to TCP_IN
and add the following line to /etc/proftpd.conf and then restart proftpd:
PassivePorts 30000 35000

FTP over SSL/TLS will usually fail when using an SPI firewall. This is because
of the way the FTP protocol established a connection between client and server.
iptables fails to establish a related connection when using FTP over SSL
because the FTP control connection is encrypted and so cannot track the
relationship between the connection and the allocation of an ephemeral port.

If you need to use FTP over SSL, you will have to open up a passive port block
in both csf and your FTP server configuration (see above).

Perversely, this makes your firewall less secure, while trying to make FTP
connections more secure.

Disable interactive logins for daemon accounts by specifying /bin/false for the user’s shell

SSH Configuration

Change the SSH port

Open your sshd_config file for editing

Locate the Port directive

Change the default SSH port – any port above the 1-1024 range is preferable (check theInternet Assigned Numbers Authority site for unassigned port numbers if you want to ensure no conflicts are encountered)

Restart SSH and connect to your VPS using the new port

Restrict SSH users and hosts in sshd_config

Use the PermitRootLogin no directive to disable root logins over SSH (if you have created a user account for yourself and plan to use su to administer your VPS)

Use the AllowUsers directive to specify which user accounts may be used to log in

Prior to closing the established SSH session, test the SSH access rule: Create an additional SSH session from the trusted source IP. Test a non-trusted IP as well. If the non-trusted IP is unable to connect and the trusted IP is allowed, the rule is working as intended.

Use the DenyHosts script to block malicious users (if restricting access to a single trusted IP is not practical)

]]>http://vajiv.com/blog/some-quick-steps-to-secure-your-vps/feed/1Instant web proxy on a Linux VPS serverhttp://vajiv.com/blog/instant-web-proxy-on-a-linux-vps-server/
http://vajiv.com/blog/instant-web-proxy-on-a-linux-vps-server/#commentsTue, 09 Aug 2011 17:10:19 +0000http://vajiv.com/blog/?p=454If you are unable to access a website because your computer is behind a firewall, with a VPS server you can make an instant SOCKS proxy for you to bypass the firewall in few minutes. Such a useful guide that I’ve found out from the net. Enjoy!

Introduction

There are many situations which call for a higher level of security and privacy than the immediate network provides: having a SOCKS proxy at your disposal is often the quickest and most convenient solution.

If you have ever checked POP3 e-mail, accessed an account on an FTP server, or encountered a website which was blocked by the local network administrator, this guide will explain how to protect your passwords over the local network and maintain access to the sites you frequent, regardless of local restrictions.

This guide will explain how to configure your VPS to act as a proxy server and configure your Linux or Windows client software to use the SOCKS proxy.

Note: The VPSLink Acceptable Use Policy expressly prohibits the operation of a public proxy. Please limit user accounts to trusted users to ensure the security of your VPS.

VPS Configuration

No special configuration is required – your VPS will be running an SSH daemon by default.

Note: We strongly recommend that you review our Linux security best practices to change the port which SSH is listening on as a security precaution.

Client Configuration

Considerations:

Ensure that the port which will act as your local proxy port is not presently active or listening for connections

Despite common port restrictions, most networks will allow traffic over port 80 (HTTP) and port 443 (SSL) – because encrypted traffic is expected over port 443, this port makes an ideal local proxy port

Client software (web browsers, e-mail clients, chat clients) must be configured to use the SOCKS proxy and perform DNS lookups over the SOCKS proxy (if you wish to keep the domains which you browse private)

Linux

Open a local console

Enter the following command:

ssh -p VPS_SSH_PORT -D LOCAL_PROXY_PORT USERNAME@VPS_IP_ADDRESS

where:

VPS_SSH_PORT – The port on your VPS which is listening for SSH connections

LOCAL_PROXY_PORT – The port on your local machine which will accept SOCKS connections

USERNAME – The username for an account with SSH login capabilities on your VPS

VPS_IP_ADDRESS – The IP address of your VPS

Log in with your user account password

Open your client applications and enable proxy use on your local SOCKS proxy port

Source port – Enter the port on your local machine which will accept SOCKS connections

Destination – Enter the IP address for your VPS

Select the Dynamic radio button

Click the Add button to add the source port association

If you would like to save your SOCKS proxy settings:

Navigate back to the Session category

Enter a label for your settings in the Saved Sessions field

Click the Save button

Click the Open button to initiate a connection with your VPS

Log in with your username and password

Open your client applications and enable proxy use on your local SOCKS proxy port

Application Configuration

Keep in mind that you will need to have an open an SSH connection to your VPS in order to use application SOCKS proxy settings. If your local machine is no longer listening for connections or your connection to your VPS is interrupted, SOCKS-enabled applications will report that no connection exists.

FireFox

The FireFox browser can easily be configured to make use of a SOCKS proxy – additionally, the FoxyProxy FireFox extension allows for domain-specific proxying rules.

Use the following steps to modify your FireFox settings to route all browsing over your proxy:

Open FireFox and select the Tools option from the menu bar

Switch to the Advanced section and select the Network tab, then click the Settings button

Select the Manual proxy configuration option

Enter localhost in the SOCKS Host field and your LOCAL_PROXY_PORT in the correspondingPort field

Browse to WhatIsMyIP.com to confirm that the IP address for your VPS appears

]]>http://vajiv.com/blog/instant-web-proxy-on-a-linux-vps-server/feed/2Javascript Data Type Conversionhttp://vajiv.com/blog/javascript-data-type-conversion/
http://vajiv.com/blog/javascript-data-type-conversion/#commentsTue, 14 Jun 2011 10:11:07 +0000http://vajiv.com/blog/?p=447Today I discover a pretty good page discussing data type conversion in javascript. I would like to include the content of the page here for my own reference. Thanks to author of the content, Jim Ley.
(Source: http://www.jibbering.com/faq/notes/type-conversion/)

Introduction

Javascript (ECMAScript) is a loosely typed language. That does not mean that it has no data types just that the value of a variable or a Javascript object property does not need to have a particular type of value assigned to it, or that it should always hold the same type of value. Javascript also freely type-converts values into a type suitable for (or required by) the context of their use.

Javascript being loosely typed and willing to type-convert still does not save the programmer from needing to think about the actual type of values that they are dealing with. A very common error in browser scripting, for example, is to read the value property of a form control into which the user is expected to type a number and then add that value to another number. Because the value properties of form controls are strings (even if the character sequence they contain represents a number) the attempt to add that string to a value, even if that value happens to be a number, results in the second value being type-converted into a string and concatenated to the end of the first string value from the from control.

That problem arises from the dual nature of the + operator used for both numeric addition and string concatenation. With which the nature of the operation performed is determined by the context, where only if both operands are numbers to start with will the + operator perform addition. Otherwise it converts all of its operands to strings and does concatenation.

The following discussion is illustrated with Javascript generated tables of values resulting from the conversion operations. The headers of those tables display the values as represented in the Javascript source code used rather than their internal representation. So, for example 123e-2 as a number was the character sequence typed into the source code, the interpreter reads that and generates the number value 1.23 from it for internal use. The various values used for the tests have been chosen to illustrate aspects of type converting, those aspects may not apply to all of the tables presented. However, all of the test values are included in all of the tables (except where no type converting occurs) for full comparison. The bodies of the tables list the results of the various type conversion operations.

If you are accepting/using this page’s CSS style suggestions the type of the values at various stages is illustrated by the colour of the text used. The following key shows those type/colour relationships, they are derived from the string values returned by the typeof operator (which returns "object" for the null type when in reality null is distinct from objects).

Key

string

number

boolean

object

function

null

undefined

The boolean values of results also have a coloured background to highlight true or false.

Converting to Boolean

When evaluating the expression of an if statement the Javascript interpreter will type-convert the result of that expression to boolean in order to make its decision. Also various operators internally type-convert their operands to boolean in order to determine what action to take. These include the logical operators like AND (&&), OR (||) and NOT (!). The NOT operator type-converts its operand to boolean and if that value is boolean true it returns false and if false it returns true. As the result of a NOT operation is a boolean value that is the inverse of the type-converted true-ness of its operand, two NOT operations together will return a boolean value that is equivalent to the result of type-converting the operand to boolean:-

var boolValue = !!x;

That technique has been used to generate the following tables.

An alternative method of generating a boolean value that represents the type-converted true-ness of a value is to pass that value to the Boolean constructor called as a function:-

var boolValue = Boolean(x);

Double NOT (!!col) : Numeric Values.

-1.6

-0

+0

1

1.6

8

16

16.8

123e-2

-Infinity

+Infinity

NaN

!!col

true

false

false

true

true

true

true

true

true

true

true

false

When numbers are converted to boolean, zero becomes false and all other numbers are true. With the excepting of the special numeric value NaN (Not a Number) which is used when another type is converted to a number but that conversion does not result in a meaningful number. NaN is always false. The values of positive and negative infinity, while not finite numbers, are non-zero numeric values and always type-convert to boolean true.

Double NOT (!!col) : String Values.

“”
(empty
string)

“-1.6″

“0″

“1″

“1.6″

“8″

“16″

“16.8″

“123e-2″

“010″
(Octal)

“0×10″
(Hex)

“0xFF”
(Hex)

“-010″

“-0×10″

“xx”

!!col

false

true

true

true

true

true

true

true

true

true

true

true

true

true

true

Type conversion rules are even simpler for string to boolean conversion as all non-empty strings always become true and empty strings become false.

Double NOT (!!col) : Other Values

undefined

null

true

false

new Object()

function(){
return;
}

!!col

false

false

true

false

true

true

For the other types, undefined and null are converted to false, boolean values are not converted and objects and functions are always true.

This is the most valuable aspect of type-converting to boolean as it allows a script to distinguish between properties in an environment that may be undefined or may refer to an object. Treating an undefined (or null) value as if it was an object will produce errors. So when there is a doubt (as there usually is where web browsers are concerned) then code can avoid generating errors by wrapping the code that wants to access an object in an if test. Supplying the suspect reference to the object as the expression. The expression will be type converted to boolean and result in false if the object does not exist and true if it does.

Converting to String

As mentioned above, type conversion to a string most often results from the action of the + operator whenever one of its operators in not a number. The easiest way of getting the string that results from type-conversion is to concatenate a value to an empty string. That technique has been used to generate the following tables.

An alternative method of converting a value into a string is to pass it as an argument to the String constructor called as a function:-

var stringValue = String(x);

type-convert to string (“” + col) : Numeric Values.

-1.6

-0

+0

1

1.6

8

16

16.8

123e-2

-Infinity

+Infinity

NaN

“” + col

-1.6

0

0

1

1.6

8

16

16.8

1.23

-Infinity

Infinity

NaN

Notice that the number generated from the source code 123e-2 has resulted in the string "1.23" because that is the string representation of the internal number created from the source code. However, Javascript’s internal number representations take the form of IEEE double precision floating point numbers and that means that they cannot represent all numbers with precision. The results of mathematical operations may only produce close approximations and when they are converted to strings the string represents the approximation and may be unexpected and undesirable. It is often necessary to use custom functions to generate string representations of numbers in an acceptable format, the type-conversion mechanism is rarely suited to generating numeric output intended for presentation.

type-convert to string (“” + col) : Other Values.

undefined

null

true

false

new Object()

function(){
return;
}

“” + col

undefined

null

true

false

[object Object]

function(){
return;
}

When objects or functions are type-converted to strings their toString method is called. These default to Object.prototype.toString and Function.prototype.toString but may be overloaded with a function assigned to a “toString” property of the object/function. Type-converting a function to a string does not necessarily result in the function’s source code. The behaviour of Function.prototype.toString is implementation depended and varies quite a lot, as do the results from “host objects” and methods (the objects and methods provided by the environment, such as DOM elements).

Converting to Number

Converting values to numbers, especially strings to numbers, is an extremely common requirement and many methods can be used. Any mathematical operator except the concatenation/addition operator will force type-conversion. So conversion of a string to a number might entail performing a mathematical operation on the string representation of the number that would not affect the resulting number, such as subtracting zero or multiplying by one.

However, the unary + operator also type-converts its operand to a number and because it does not do any additional mathematical operations it is the fastest method for type-converting a string into a number.

Incidentally, the unary - (minus) operator also type-converts its operand (if necessary) in addition to subsequently negating its value.

While unary + is the fastest method for converting a string to a number a final method is available that uses the Javascript type-conversion algorithms. The Number constructor can be called with the string value as its argument and its return value is a number representing the result of the type-conversion.

var numValue = Number(stringValue);

The Number constructor is the slowest of the type-converting methods but when speed is not an overriding consideration its use does produce the clearest source code.

The following tables show the results of type-conversion to a number using the unary + operator. Though all of the preceding alternative method produce the same results as they all use exactly the same algorithm to do the conversion.

type-convert to number (+col) : String Values.

“”
(empty
string)

“-1.6″

“0″

“1″

“1.6″

“8″

“16″

“16.8″

“123e-2″

“010″
(Octal)

“0×10″
(Hex)

“0xFF”
(Hex)

“-010″

“-0×10″

“xx”

+col

0

-1.6

0

1

1.6

8

16

16.8

1.23

10

16

255

-10

NaN

NaN

The important considerations when converting strings to numbers with the type-converting methods is the results from strings that do not represent numbers. The empty string is converted into the number zero, depending on the application this can be harmless or disastrous, but it is important to be aware that it is going to happen. In other contexts strings that follow the Javascript format for octal number (leading zero) can be problematic but type conversion treats them as base 10 anyway. However, strings that follow the format for hexadecimal numbers (leading 0x or 0X) are read as hexadecimal. Strings that cannot be read as a number type-convert to NaN, which can be tested for with the isNaN function. Strings representing numbers in an exponential format ("123e-2") are understood along with leading minus signs.

type-convert to number (+col) : Other Values.

undefined

null

true

false

new Object()

function(){
return;
}

+col

NaN

0

1

0

NaN

NaN

Objects and functions always type-convert to NaN numbers, as do undefined values but it is worth noting that null type-converts to zero. Probably because it is being type-converted to boolean first and then to number and, as is clear from the boolean results above, null would become boolean false which would then become numeric zero. There is almost no need to type convert these types of values into numbers. How they convert is only really relevant to a consideration of the accidental result of converting a value that is expected to be a string but actually turns out to be one of these (and/or performing an mathematical operation with one of these as an operand).

Parsing to Number

An alternative method of converting a string into a number is to use one of the global functions designed to parse a string and return a number. The parseFloat function accepts a string argument and returns a floating point number resulting from parsing that string. Non-string arguments are first type-converted to a string as described above.

The string parsing functions read the string character by character until they encounter a character that cannot be part of the number, at which point they stop and return a number based on the characters that they have seen that can be part of the number. This feature of their action can be usefully exploited, for example, given a string representing a CSS length value such as "34.5em"parseFloat would be able to ignore the "em" because those characters cannot be combined with the preceding set to produce a valid number. The returned number would be 34.5, the numeric part of the CSS string stripped of its units.

parseFloat

parseFloat(col) : String Values.

“”
(empty
string)

“-1.6″

“0″

“1″

“1.6″

“8″

“16″

“16.8″

“123e-2″

“010″
(Octal)

“0×10″
(Hex)

“0xFF”
(Hex)

“-010″

“-0×10″

“xx”

parseFloat(col)

NaN

-1.6

0

1

1.6

8

16

16.8

1.23

10

0

0

-10

0

NaN

With parseFloat empty strings return NaN along with strings that cannot be subject to numeric interpretation. The exponential format is understood and the leading zero in the octal format does not hinder the string’s interpretation as a decimal number. Hexadecimal strings are interpreted as the number zero because the following "x" cannot be interpreted as part of a number so parsing stops after the leading zero.

parseFloat(col) : Other Values.

undefined

null

true

false

new Object()

function(){
return;
}

parseFloat(col)

NaN

NaN

NaN

NaN

NaN

NaN

Non-string values are first converted into a string that is employed by parseFloat. As that type-conversion to a string would not normally result in a string that could be interpreted as a number the result is NaN. Objects and functions may have custom toString methods that may return strings that could be interpreted as numbers but that would be an unusual requirement.

parseInt

The parseInt function works in a similar way to parseFloat except that it is trying to interpret its string argument into an integer and as a result recognises fewer character as possible candidates to be part of that number.

parseInt is occasionally used as a means of turning a floating point number into an integer. It is very ill suited to that task because if its argument is of numeric type it will first be converted into a string and then parsed as a number, very inefficient. This can produce very wrong results with numbers such as 2e-200, for which the next smaller integer is zero, but with which parseInt returns 2. Also, because of the number format used by javascript, numbers are often represented by near approximations. So, for example, 1/2 + 1/3 + 1/6 = 0.9999999999999999, which isn’t quite one and parseInt would return zero if asked to act on the result of the operation.

For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable, and for a desired result that can be expressed as a 32 bit signed integer the bitwise operation described below might also suit.

parseInt(col) : Numeric Values.

-1.6

-0

+0

1

1.6

8

16

16.8

123e-2

-Infinity

+Infinity

NaN

parseInt(col)

-1

0

0

1

1

8

16

16

1

NaN

NaN

NaN

When it is acting on number the effect of the initial type-conversion of the argument to a string is evident in the results. Note that the value 123e-2 is internally the number 1.23 and that type converts into the string "1.23", so that entry in the table above might look odd but it is correct.

parseInt(col) : String Values.

“”
(empty
string)

“-1.6″

“0″

“1″

“1.6″

“8″

“16″

“16.8″

“123e-2″

“010″
(Octal)

“0×10″
(Hex)

“0xFF”
(Hex)

“-010″

“-0×10″

“xx”

parseInt(col)

NaN

-1

0

1

1

8

16

16

123

8

16

255

-8

-16

NaN

Strings in octal and hexadecimal number formats do represent integers and parseInt is capable of interpreting them in accordance with the rules for Javascript source code, even when they have leading minus signs.

parseInt(col) : Other Values.

undefined

null

true

false

new Object()

function(){
return;
}

parseInt(col)

NaN

NaN

NaN

NaN

NaN

NaN

As parseInt type-converts its non-string arguments to strings it always produces the same results for boolean, null, undefined, object and function arguments as parseFloat (assuming objects and functions do not have custom toString methods).

parseInt with a radix argument

It is rarely desirable to allow parseInt to deduce the base in which the number is represented from the string as leading zeros are rarely intended to indicate data in octal format (particularly with user input). To deal with this problem parseInt recognises a second, radix, argument that can be used to specify the base in which the string is to be interpreted. Specifying a second argument of 10 causes parseInt to interpret the strings as only base 10.

parseInt(col, 10) : String Values.

“”
(empty
string)

“-1.6″

“0″

“1″

“1.6″

“8″

“16″

“16.8″

“123e-2″

“010″
(Octal)

“0×10″
(Hex)

“0xFF”
(Hex)

“-010″

“-0×10″

“xx”

parseInt(col, 10)

NaN

-1

0

1

1

8

16

16

123

10

0

0

-10

0

NaN

The string in octal format is now interpreted as base 10 and the hexadecimal strings can now only be zero as parsing has to stop when the "x" is encountered.

Number bases 2 to 36 can be used with parseInt. The following is base 16.

parseInt(col, 16) : String Values.

“”
(empty
string)

“-1.6″

“0″

“1″

“1.6″

“8″

“16″

“16.8″

“123e-2″

“010″
(Octal)

“0×10″
(Hex)

“0xFF”
(Hex)

“-010″

“-0×10″

“xx”

parseInt(col, 16)

NaN

-1

0

1

1

8

22

22

4670

16

16

255

-16

-16

NaN

The hexadecimal 0x format is recognised again with the base 16 interpretation.

Finally base 3:-

parseInt(col, 3) : Numeric Values.

-1.6

-0

+0

1

1.6

8

16

16.8

123e-2

-Infinity

+Infinity

NaN

parseInt(col, 3)

-1

0

0

1

1

NaN

1

1

1

NaN

NaN

NaN

The consequences of the type-converting of numeric arguments to strings is evident again. The number 8 is coming out as NaN because the "8" character cannot be interpreted as base 3, leaving an empty sequence of acceptable characters and producing the same result as an empty string.

parseInt(col, 3) : String Values.

“”
(empty
string)

“-1.6″

“0″

“1″

“1.6″

“8″

“16″

“16.8″

“123e-2″

“010″
(Octal)

“0×10″
(Hex)

“0xFF”
(Hex)

“-010″

“-0×10″

“xx”

parseInt(col, 3)

NaN

-1

0

1

1

NaN

1

1

5

3

0

0

-3

0

NaN

ToInt32

ToInt32 is an internal function only available to the Javascript implementation and cannot be called directly from scripts in the way that parseInt can. It is a bit unusual to mention it in connection with converting Javascript values to numbers but it can be used in a limited set of circumstances. The bitwise operators such as bitwise OR (|) and bitwise AND (&) operate on numbers so they type-convert their operands to numbers. However, they also only operate on 32 bit signed integers so given the (possibly type-converted) numeric value they call the internalToInt32 function with that number as its argument and use the returned value as their operand. That returned value is always a 32 bit signed integer.

The effect can be like parseInt combined with type-converting to numbers. While the result is limited in range to 32 bits, it is always numeric and never NaN, or ± Infinity.

As with using mathematical operators in operations that have no effect on the value of any resulting number it is possible to perform a bitwise operation that will not affect the value returned from the call to ToInt32. The tables below were generated using a bitwise OR zero operation.

ToInt32 (col|0) : Numeric Values.

-1.6

-0

+0

1

1.6

8

16

16.8

123e-2

-Infinity

+Infinity

NaN

col|0

-1

0

0

1

1

8

16

16

1

0

0

0

NaN and ±Infinity become zero and floating point values are truncated to integers.

ToInt32 (col|0) : String Values.

“”
(empty
string)

“-1.6″

“0″

“1″

“1.6″

“8″

“16″

“16.8″

“123e-2″

“010″
(Octal)

“0×10″
(Hex)

“0xFF”
(Hex)

“-010″

“-0×10″

“xx”

col|0

0

-1

0

1

1

8

16

16

1

10

16

255

-10

0

0

String values that would type-convert to NaN are returned as zero from ToInt32.

ToInt32 (col|0) : Other Values.

undefined

null

true

false

new Object()

function(){
return;
}

col|0

0

0

1

0

0

0

Even undefined, objects and functions are converted to zero value numbers by this operation. Note though that boolean true is converted to the number 1.

Converting User Input

Most of the mechanisms for getting input from the user, <input type="text"> and prompt for example, provide their results in the form of strings. If the user is expected to input a number they still might enter anything (at the least they may just make a typo). If the string needs to be converted into a number for later operations one of the methods mentioned above can be chosen based on what best suits the nature of the input expected but some of the results generated with erroneous input may be difficult to detect and handle.

Prior to converting a string to a number it may be advantageous to use a Regular Expression to test the contents of the string to ensure that they conform to an acceptable format. That would serve to eliminate some of the string values that may otherwise suffer from the quirks of the string to number converting processes when applied to unexpected string values.