# man > BSON::Code

---
type: CommandReference
command: BSON::Code
mode: perldoc
section: 3pm
source: perldoc
---

## Quick Reference
- `bson_code("function() { return x; }")` — create a BSON code object with no scope
- `bson_code("function() { return x; }", { x => 1 })` — create a BSON code object with scope
- `$code->code` — get or set the Javascript code string
- `$code->scope` — get or set the scope hashref (defaults to `undef`)
- `$code->length()` — length of the code string
- `$code->TO_JSON` — returns extended JSON representation (requires `BSON_EXTJSON`)

## Name
BSON::Code - BSON type wrapper for Javascript code

## Synopsis
perl
use BSON::Types ':all';

$code = bson_code($javascript);
$code = bson_code($javascript, $scope);
## Options
### Attributes
- `code` — A string containing Javascript code. Defaults to the empty string.
- `scope` — An optional hash reference containing variables in the scope of `code`. Defaults to `undef`.

### Methods
- `length()` — Returns the length of the `code` attribute.
- `TO_JSON` — If `BSON_EXTJSON` is true, returns a hashref compatible with [MongoDB extended JSON](https://github.com/mongodb/specifications/blob/master/source/extended-json.rst):
  - `{"$code" : "<code>"}`
  - `{"$code" : "<code>", "$scope" : { ... } }`  
  Throws an error if `BSON_EXTJSON` is false.

## See Also
- [BSON::Types](http://localhost/phpMan.php/perldoc/BSON%3A%3ATypes/markdown)