index.md 2.31 KB
Newer Older
Shane A. Stillwell's avatar
Shane A. Stillwell committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
---
title: JavaScript Casting Tricks
date: "2013-10-22T06:23:26-05:00"
tags:
- JavaScript
---

Here I want to go through some casting tricks that can be used for better data manipulation.


## Booleans

### Build in Boolean()

The easiest way is to use the builtin `Boolean()` method.

```javascript
Boolean('true'); // true
Boolean(1); // true

Boolean('false'); // true !!!!GOTCHA!!!!!
Boolean(0); // false

// Careful
Boolean([]); // true

```

### Double Negative

This will cast anything as either `true` or `false`, there are of course a few quirks that may not be obvious.

```javascript
// FALSE
!!false;
!!null;
!!undefined;
!!0;
!!'';

// TRUE
!!true;
!!'true';
!!1;
!!-1;
!!{};
!!function(){};


// GOTCHA!!! ... TRUE
!!'false';
```

### JSON.parse

This will parse the text `'true'` to the boolean `true`

```javascript
// TRUE
JSON.parse('true');

// FALSE
JSON.parse('false');

// If using a variable, you'll want a fallback
JSON.parse(undefined || 'true');
JSON.parse('' || 'true');
```

## Numbers

### Check for a decimal using modulo

```javascript
5.5 % 1 != 0; // true
5 % 1 != 0; // false
```
Reference: http://stackoverflow.com/a/2304062/179335

## Strings 

### Built in tools toString() and String()

```javascript
var hello = String('hello')
10.0.toString();
```

### Casting an Array as a String

Strings are of course mostly just an array of characters so arrays and strings have a lot in common. You can cast an array to a string simply by joining them with *nothing*.

```javascript
var hello = ['h', 'e', 'l', 'l', 'o'];
hello.join('');  // Yields "hello"
```

### Convert from an Array to a String

Strings can be converted to an array easily using `split`. Here's how.

```javascript 
var hello = "hello";
hello.split('');  // ['h', 'e', 'l', 'l', 'o'];
```


## Arguments
In JavaScript the [arguments](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments) object in a function is array like, but to convert it to an actually array you can just use a simple trick.

```javascript
Array.prototype.slice.call(arguments);
```

Or more simply if [Array generics](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array#Array_generic_methods) are available (like in node.js).

```javascript
Array.slice(arguments);
```


## Have one to add? Comment below.