BOOLEAN_TO_JSVAL
DOUBLE_TO_JSVAL
INT_FITS_IN_JSVAL
INT_TO_JSVAL
JS::Add*Root
JS::AutoIdArray
JS::AutoSaveExceptionState
JS::AutoValueArray
JS::AutoVectorRooter
JS::BooleanValue
JS::Call
JS::CallArgs
JS::CloneFunctionObject
JS::Compile
JS::CompileFunction
JS::CompileOffThread
JS::CompileOptions
JS::Construct
JS::CreateError
JS::CurrentGlobalOrNull
JS::DeflateStringToUTF8Buffer
JS::DoubleNaNValue
JS::DoubleValue
JS::Evaluate
JS::FalseValue
JS::Float32Value
JS::GetDeflatedUTF8StringLength
JS::GetFirstArgumentAsTypeHint
JS::GetSelfHostedFunction
JS::Handle
JS::HandleValueArray
JS::IdentifyStandardInstance
JS::Int32Value
JS::IsCallable
JS::MutableHandle
JS::NewFunctionFromSpec
JS::NullHandleValue
JS::NullValue
JS::NumberValue
JS::ObjectOrNullValue
JS::ObjectValue
JS::OrdinaryToPrimitive
JS::PersistentRooted
JS::PropertySpecNameEqualsId
JS::PropertySpecNameIsSymbol
JS::PropertySpecNameToPermanentId
JS::ProtoKeyToId
JS::Remove*Root
JS::Rooted
JS::SetLargeAllocationFailureCallback
JS::SetOutOfMemoryCallback
JS::SourceBufferHolder
JS::StringValue
JS::SymbolValue
JS::ToBoolean
JS::ToInt32
JS::ToInt64
JS::ToNumber
JS::ToPrimitive
JS::ToString
JS::ToUint16
JS::ToUint32
JS::ToUint64
JS::TrueHandleValue
JS::TrueValue
JS::UndefinedHandleValue
JS::UndefinedValue
JS::Value
JSAutoByteString
JSAutoCompartment
JSBool
JSCheckAccessOp
JSClass
JSClass.call
JSClass.flags
JSConstDoubleSpec
JSConvertOp
JSDeletePropertyOp
JSEnumerateOp
JSErrorFormatString
JSErrorReport
JSExceptionState
JSExnType
JSExtendedClass
JSExtendedClass.outerObject
JSExtendedClass.wrappedObject
JSFUN_BOUND_METHOD
JSFUN_GLOBAL_PARENT
JSFastNative
JSFinalizeOp
JSFreeOp
JSFunction
JSFunctionSpec
JSGetObjectOps
JSHasInstanceOp
JSID_EMPTY
JSID_IS_EMPTY
JSID_IS_GCTHING
JSID_IS_INT
JSID_IS_STRING
JSID_IS_SYMBOL
JSID_IS_VOID
JSID_IS_ZERO
JSID_VOID
JSIdArray
JSIteratorOp
JSMarkOp
JSNative
JSNewEnumerateOp
JSNewResolveOp
JSObject
JSObjectOp
JSObjectOps.defaultValue
JSObjectOps.defineProperty
JSObjectOps.destroyObjectMap
JSObjectOps.dropProperty
JSObjectOps.enumerate
JSObjectOps.getAttributes
JSObjectOps.getProperty
JSObjectOps.getRequiredSlot
JSObjectOps.lookupProperty
JSObjectOps.newObjectMap
JSObjectOps.setProto
JSObjectPrincipalsFinder
JSPRINCIPALS_HOLD
JSPrincipals
JSPrincipalsTranscoder
JSProperty
JSPropertyDescriptor
JSPropertyOp
JSPropertySpec
JSProtoKey
JSReserveSlotsOp
JSResolveOp
JSRuntime
JSSecurityCallbacks.contentSecurityPolicyAllows
JSString
JSStringFinalizer
JSTraceOp
JSType
JSVAL_IS_BOOLEAN
JSVAL_IS_DOUBLE
JSVAL_IS_GCTHING
JSVAL_IS_INT
JSVAL_IS_NULL
JSVAL_IS_NUMBER
JSVAL_IS_OBJECT
JSVAL_IS_PRIMITIVE
JSVAL_IS_STRING
JSVAL_IS_VOID
JSVAL_LOCK
JSVAL_NULL
JSVAL_ONE
JSVAL_TO_BOOLEAN
JSVAL_TO_DOUBLE
JSVAL_TO_GCTHING
JSVAL_TO_INT
JSVAL_TO_OBJECT
JSVAL_TO_STRING
JSVAL_TRUE
JSVAL_UNLOCK
JSVAL_VOID
JSVAL_ZERO
JSVersion
JSXDRObjectOp
JS_ASSERT_STRING_IS_FLAT
JS_Add*Root
JS_AddArgumentFormatter
JS_AddExternalStringFinalizer
JS_AddFinalizeCallback
JS_AliasElement
JS_AliasProperty
JS_AlreadyHasOwnProperty
JS_BeginRequest
JS_BindCallable
JS_BufferIsCompilableUnit
JS_CStringsAreUTF8
JS_CallFunction
JS_CheckAccess
JS_CheckForInterrupt
JS_ClearContextThread
JS_ClearDateCaches
JS_ClearNewbornRoots
JS_ClearNonGlobalObject
JS_ClearPendingException
JS_ClearRegExpStatics
JS_ClearScope
JS_CloneFunctionObject
JS_CompareStrings
JS_CompileFileHandleForPrincipals
JS_CompileFileHandleForPrincipalsVersion
JS_CompileFunction
JS_CompileFunctionForPrincipals
JS_CompileScript
JS_CompileScriptForPrincipals
JS_CompileUCFunctionForPrincipalsVersion
JS_CompileUTF8File
JS_CompileUTF8FileHandle
JS_ConcatStrings
JS_ConstructObject
JS_ContextIterator
JS_ConvertArguments
JS_ConvertArgumentsVA
JS_ConvertValue
JS_DecompileFunction
JS_DecompileFunctionBody
JS_DecompileScript
JS_DecompileScriptObject
JS_DeepFreezeObject
JS_DefaultValue
JS_DefineConstDoubles
JS_DefineElement
JS_DefineFunction
JS_DefineFunctions
JS_DefineObject
JS_DefineOwnProperty
JS_DefineProperties
JS_DefineProperty
JS_DefinePropertyWithTinyId
JS_DeleteElement
JS_DeleteElement2
JS_DeleteProperty
JS_DeleteProperty2
JS_DestroyContext
JS_DestroyIdArray
JS_DestroyRuntime
JS_DestroyScript
JS_DoubleIsInt32
JS_DoubleToInt32
JS_DropExceptionState
JS_DumpHeap
JS_DumpNamedRoots
JS_EncodeCharacters
JS_EncodeString
JS_EncodeStringToBuffer
JS_EnterCompartment
JS_EnterCrossCompartmentCall
JS_EnterLocalRootScope
JS_Enumerate
JS_EnumerateDiagnosticMemoryRegions
JS_EnumerateResolvedStandardClasses
JS_EnumerateStandardClasses
JS_ErrorFromException
JS_EvaluateScript
JS_EvaluateScriptForPrincipals
JS_ExecuteRegExp
JS_ExecuteScript
JS_ExecuteScriptPart
JS_ExecuteScriptVersion
JS_FORGET_STRING_FLATNESS
JS_FS
JS_FileEscapedString
JS_Finish
JS_FlattenString
JS_FlushCaches
JS_ForgetLocalRoot
JS_ForwardGetPropertyTo
JS_FreezeObject
JS_GC
JS_GET_CLASS
JS_GetArrayLength
JS_GetArrayPrototype
JS_GetClass
JS_GetClassObject
JS_GetClassPrototype
JS_GetCompartmentPrivate
JS_GetConstructor
JS_GetContextPrivate
JS_GetContextThread
JS_GetDefaultFreeOp
JS_GetElement
JS_GetEmptyString
JS_GetEmptyStringValue
JS_GetErrorPrototype
JS_GetExternalStringClosure
JS_GetExternalStringFinalizer
JS_GetFlatStringChars
JS_GetFunctionArity
JS_GetFunctionCallback
JS_GetFunctionFlags
JS_GetFunctionId
JS_GetFunctionName
JS_GetFunctionObject
JS_GetFunctionPrototype
JS_GetFunctionScript
JS_GetGCParameter
JS_GetGlobalForCompartmentOrNull
JS_GetGlobalForObject
JS_GetGlobalForObject3
JS_GetGlobalForScopeChain
JS_GetGlobalObject
JS_GetImplementationVersion
JS_GetInstancePrivate
JS_GetInternedStringChars
JS_GetLatin1FlatStringChars
JS_GetLatin1InternedStringChars
JS_GetLatin1StringCharsAndLength
JS_GetLocaleCallbacks
JS_GetNaNValue
JS_GetObjectPrototype
JS_GetObjectRuntime
JS_GetOptions
JS_GetOwnPropertyDescriptor
JS_GetParent
JS_GetParentRuntime
JS_GetPendingException
JS_GetPositiveInfinityValue
JS_GetPrivate
JS_GetProperty
JS_GetPropertyAttributes
JS_GetPropertyAttrsGetterAndSetter
JS_GetPropertyDefault
JS_GetPropertyDescriptor
JS_GetPrototype
JS_GetRegExpFlags
JS_GetRegExpSource
JS_GetReservedSlot
JS_GetRuntime
JS_GetRuntimePrivate
JS_GetScopeChain
JS_GetSecurityCallbacks
JS_GetStringBytes
JS_GetStringCharAt
JS_GetStringChars
JS_GetStringCharsAndLength
JS_GetStringEncodingLength
JS_GetStringLength
JS_GetTwoByteExternalStringChars
JS_GetTypeName
JS_GetVersion
JS_HasArrayLength
JS_HasElement
JS_HasInstance
JS_HasOwnProperty
JS_HasProperty
JS_IdArrayGet
JS_IdArrayLength
JS_IdToProtoKey
JS_IdToValue
JS_Init
JS_InitCTypesClass
JS_InitClass
JS_InitStandardClasses
JS_InstanceOf
JS_InternJSString
JS_InternString
JS_IsArrayObject
JS_IsAssigning
JS_IsBuiltinEvalFunction
JS_IsBuiltinFunctionConstructor
JS_IsConstructing
JS_IsConstructing_PossiblyWithGivenThisObject
JS_IsConstructor
JS_IsExceptionPending
JS_IsExtensible
JS_IsExternalString
JS_IsGlobalObject
JS_IsIdentifier
JS_IsNative
JS_IsNativeFunction
JS_IsRunning
JS_IsStopIteration
JS_IterateCompartments
JS_LeaveCompartment
JS_LeaveCrossCompartmentCall
JS_LeaveLocalRootScope
JS_LeaveLocalRootScopeWithResult
JS_LinkConstructorAndPrototype
JS_Lock
JS_LockGCThing
JS_LookupElement
JS_LookupProperty
JS_LooselyEqual
JS_MakeStringImmutable
JS_MapGCRoots
JS_MaybeGC
JS_New
JS_NewArrayObject
JS_NewCompartmentAndGlobalObject
JS_NewContext
JS_NewDateObject
JS_NewDateObjectMsec
JS_NewDependentString
JS_NewDouble
JS_NewDoubleValue
JS_NewExternalString
JS_NewFunction
JS_NewGlobalObject
JS_NewNumberValue
JS_NewObject
JS_NewObjectForConstructor
JS_NewPlainObject
JS_NewPropertyIterator
JS_NewRegExpObject
JS_NewRuntime
JS_NewScriptObject
JS_NewStringCopyN
JS_NewStringCopyZ
JS_NewUCString
JS_NextProperty
JS_Now
JS_NumberValue
JS_ObjectIsDate
JS_ObjectIsFunction
JS_ObjectIsRegExp
JS_PSGS
JS_ParseJSON
JS_PopArguments
JS_PreventExtensions
JS_PropertyStub
JS_PushArguments
JS_PutEscapedString
JS_Remove*Root
JS_RemoveExternalStringFinalizer
JS_RemoveRootRT
JS_ReportError
JS_ReportErrorNumber
JS_ReportOutOfMemory
JS_ReportPendingException
JS_ResolveStandardClass
JS_RestoreExceptionState
JS_SET_TRACING_DETAILS
JS_SameValue
JS_SaveExceptionState
JS_SaveFrameChain
JS_ScheduleGC
JS_SealObject
JS_SetAllNonReservedSlotsToUndefined
JS_SetArrayLength
JS_SetBranchCallback
JS_SetCallReturnValue2
JS_SetCheckObjectAccessCallback
JS_SetCompartmentNameCallback
JS_SetContextCallback
JS_SetDefaultLocale
JS_SetDestroyCompartmentCallback
JS_SetElement
JS_SetErrorReporter
JS_SetExtraGCRoots
JS_SetFunctionCallback
JS_SetGCCallback
JS_SetGCParametersBasedOnAvailableMemory
JS_SetGCZeal
JS_SetGlobalObject
JS_SetICUMemoryFunctions
JS_SetInterruptCallback
JS_SetNativeStackQuota
JS_SetObjectPrincipalsFinder
JS_SetOperationCallback
JS_SetOptions
JS_SetParent
JS_SetPendingException
JS_SetPrincipalsTranscoder
JS_SetPrivate
JS_SetProperty
JS_SetPropertyAttributes
JS_SetPrototype
JS_SetRegExpInput
JS_SetScriptStackQuota
JS_SetThreadStackLimit
JS_SetVersion
JS_SetVersionForCompartment
JS_ShutDown
JS_StrictlyEqual
JS_StringEqualsAscii
JS_StringHasBeenInterned
JS_StringHasLatin1Chars
JS_StringIsFlat
JS_StringToVersion
JS_SuspendRequest
JS_THREADSAFE
JS_ThrowStopIteration
JS_ToggleOptions
JS_TracerInit
JS_TypeOfValue
JS_Unlock
JS_ValueToBoolean
JS_ValueToECMAInt32
JS_ValueToFunction
JS_ValueToId
JS_ValueToInt32
JS_ValueToNumber
JS_ValueToObject
JS_ValueToSource
JS_ValueToString
JS_VersionToString
JS_YieldRequest
JS_freeop
JS_malloc
JS_updateMallocCounter
OBJECT_TO_JSVAL
PRIVATE_TO_JSVAL
Property attributes
STRING_TO_JSVAL
Stored value
jschar
jsdouble
jsid
jsint
The JavaScript shell (js
) is a command-line program included in the SpiderMonkey source distribution. It is the JavaScript equivalent of Python's interactive prompt, the Lisp read-eval-print loop, or Ruby's irb
. This article explains how to use the shell to experiment with JavaScript code and run JavaScript programs.
To get the SpiderMonkey JavaScript shell, see the SpiderMonkey Build Documentation or download a compiled binary for your platform from the Nightly Builds.
For a list of other JavaScript shells, see JavaScript shells.
Note: Starting with SpiderMonkey 44 (Firefox 44 / Thunderbird 44 / SeaMonkey 2.41), the standard, Web-compatible JavaScript version is used by default (and not JS1.7+ anymore). The version()
shell builtin is still there for testing legacy features.
The shell offers two modes of operation. You can use it as an interactive shell, in which you type JavaScript code at a prompt and get instant gratification, which is handy for experimenting or testing new features. You can also pass in, on the command line, a JavaScript program file to run, in which case the program is run automatically.
After following the build documentation and installing the built shell using make install, you can run the shell in interactive mode using the command:
js
[ If you get " symbol lookup error: ./js: undefined symbol: PR_SetCurrentThreadName" e.g. from a Bash console when using a pre-compiled binary, try <path to your Firefox's run-mozilla.sh>/run-mozilla.sh ./js -- that worked for me]
If you'd like to run the JavaScript code in the file foo.js
, you can use this command:
js foo.js
To run foo.js
then drop into the interactive shell, do this:
js -f foo.js -i
There are a number of command line options you can specify to control the shell. These are summarized below. Be sure to use -h with your own jsshell to see if there is anything undocumented.
-c, --compileonly
-e script
-f filename
-i
--no-ion
--no-baseline
-P
-s
-w, --warnings
-W
, --nowarningsThere are some environment variables that can be set to alter js shell behavior.
JS_STDOUT=file
JS_STDERR=file
To make the JavaScript shell more useful, there are a number of built-in functions provided that you can use either from JavaScript programs or in interactive mode.
Note: This list is incomplete and overlaps with Shell global objects. See js/src/shell/js.cpp
(around shell_functions
) for more.
build()
Returns the date and time at which the JavaScript shell was built.
clear()
with no parameters really clears everything. This includes all these built-in functions.clone(function, [scope])
Clones the specified function object. If scope isn't specified, the new object's parent is the same as the original object's. Otherwise, the new object is placed in the scope of the object specified by scope.
countHeap([start[, kind]])
Added in SpiderMonkey 1.8 Count the number of live GC things in the heap, or things reachable from start when it is given and is not null. kind is either 'all'
(default) to count all things or one of 'object'
, 'double'
, 'string'
, 'function'
, 'qname'
, 'namespace'
, 'xml'
to count only things of that kind.
dumpHeap([fileName[, start[, toFind[, maxDepth[, toIgnore]]]]])
Added in SpiderMonkey 1.8 Dump the graph of all existing objects (or a specific interesting subgraph) to a file. For more information, see the C/C++ version of this function, JS_DumpHeap
.
evalcx(string[, object])
Evaluates the JavaScript code in string. If object is specified, the code is executed in that object, treating it as a sandbox.
If string is empty and object is not specified, evalcx()
returns a new object with eager standard classes.
If string is "lazy" and object is not specified, evalcx()
returns a new object with lazy standard classes.
evalcx()
is only useful for people doing deep internal work on the JavaScript engine, for testing evalInSandbox
-like environments in the shell.gc()
Runs the garbage collector to free up memory.
gcparam(name[, value])
Added in SpiderMonkey 1.8 Read or configure garbage collector parameters.
The name must be one of the parameter keys (such as 'maxBytes'
, 'maxMallocBytes'
or 'gcNumber
') defined by FOR_EACH_GC_PARAM
in https://searchfox.org/mozilla-central/source/js/src/builtin/TestingFunctions.cpp#464.
If value is not specified, gcparam()
returns the current value associated with GC parameter named name.
If value is specified, it must be convertable to a positive uint32; gcparam()
sets GC parameter name to value.
For more information, see the C/C++ functions JS_GetGCParameter
and JS_SetGCParameter
.
gczeal(level)
Added in SpiderMonkey 1.8 DEBUG
only. Set the level of GC zeal, a debugging feature. This can be 0 for normal periodic garbage collection, 1 for very frequent GC, or 2 for extremely frequent GC. Anything other than 0 will make JavaScript run extremely slow but may help reveal or reproduce GC-related bugs. For more information, see the C/C++ version of this function, JS_SetGCZeal
.
getpda(object)
Returns the property descriptors for the specified object.
getslx(object)
Returns the script line extent, which is the number of lines of code comprising the specified object.
help([command ...])
Displays brief help information about the specified commands, or about all available functions if none are specified.
intern(string)
Internalizes the specified string into the atom table. Every string has a unique identifier, called an atom. This system makes it easier to do comparisons between strings.
line2pc([function, ] line)
Returns the program counter value corresponding to the specified line of code. If function is specified, line is an offset into the specified function.
load(filename1 [filename])
Loads the JavaScript files with the specified names.
read()
.options([option ...])
Lets you set or get options. If you specified options on the command line, the results of calling options
will indicate which options you requested. You can also pass in new options to set.
The available options are:
Option Name | Description |
strict |
Strict mode is enabled. |
werror |
Warnings should be treated as errors. |
atline |
When atline is enabled, comments of the form //@line num set the number of the following line to num . |
pc2line(function, [pc])
Returns the line number of the JavaScript code that corresponds to the first line of the specified function. If you specify a program counter offset into the function, the line number of the line of code containing that offset is returned.
print([expression ...])
Evaluates the expression(s) and displays the result(s) on stdout
, separated by spaces (" ") and terminated by a newline ("\n").
putstr(expression)
Evaluates the expression and displays the result on stdout
.
quit([status])
Exits the shell. status defaults to 0 if omitted.
read(filename[, type])
Reads and returns the contents of file. If type is "binary" returns an Uint8Array
, otherwise returns an UTF-8 decoded string.
readline()
Reads a single line of input from stdin
, returning it to the caller. You can use this to create interactive shell programs in JavaScript.
See Parser API.
seal(object[, deep])
Seals the specified object, or an object graph if deep is true
. By sealing an object or object graph, you disable modification of those objects.
sleep(dt)
Added in SpiderMonkey 1.8 Only in JS_THREADSAFE
builds. Sleep for dt seconds. Fractions of a second are supported. Returns true
on success, false
if the sleep was interrupted.
stackQuota([number])
Get or set the script stack quota.
throwError()
Throws an error from the JS_ReportError()
function.
trap([function, [pc,]] expression)
Sets a trap at the specific point in the JavaScript code. When the bytecode at the offset specified by pc in the function function is about to be executed, the expression is evaluated.
This is a powerful debugging mechanism when used in concert with line2pc()
. For example, if you want to display a message when line 6 of a function, doSomething()
is executed, you can enter the following:
trap(doSomething, line2pc(doSomething, 6), "print('line 6!\n')");
trap
bytecode until you use untrap()
to remove the trap.untrap(function [, pc])
Removes a trap from the specified function at the offset pc. If pc isn't specified, the trap is removed from the function's entry point.
This function has no effect if there is no trap at the specified location.
version([number])
The version()
function lets you get or set the JavaScript version number. This may be useful for gaining access to syntax only available in certain versions of JavaScript (for example, see Using JavaScript 1.7).
These built-in functions are only available in DEBUG
builds.
dis([function])
Disassembles the JavaScript bytecode for the entire program, or for the specified function.
For example, if you enter the JavaScript function below:
function test() { var i = 3; print(i+2); }
Then run the command dis(test);
, you get this output:
main: 00000: uint16 3 00003: setvar 0 00006: pop 00007: name "print" 00010: pushobj 00011: getvar 0 00014: uint16 2 00017: add 00018: call 1 00021: pop 00022: stop Source notes: 0: 0 [ 0] newline 1: 3 [ 3] decl offset 0 2: 7 [ 4] newline 3: 18 [ 11] xdelta 4: 18 [ 0] pcbase offset 11
dissrc([function])
Disassembles the JavaScript bytecode for the entire program, or for the specified function, showing the source lines. This function only works with programs loaded from files, either using the -f
flag on launching the shell, or by using the load()
function.
If your program includes a function, doStuff()
, like this:
function doStuff(input) { print("Enter a number: "); var n1 = readline(); print("Enter another one: "); var n2 = readline(); print("You entered " + n1 + " and " + n2 + "\n"); }
Calling dissrc(doStuff)
function would give this output:
;------------------------- 10: print("Enter a number: "); 00000: 10 name "print" 00003: 10 pushobj 00004: 10 string "Enter a number: " 00007: 10 call 1 00010: 10 pop ;------------------------- 11: var n1 = readline(); 00011: 11 name "readline" 00014: 11 pushobj 00015: 11 call 0 00018: 11 setvar 0 00021: 11 pop ;------------------------- 12: print("Enter another one: "); 00022: 12 name "print" 00025: 12 pushobj 00026: 12 string "Enter another one: " 00029: 12 call 1 00032: 12 pop ;------------------------- 13: var n2 = readline(); 00033: 13 name "readline" 00036: 13 pushobj 00037: 13 call 0 00040: 13 setvar 1 00043: 13 pop ;------------------------- 14: ;------------------------- 15: print("You entered " + n1 + " and " + n2 + "\n"); 00044: 15 name "print" 00047: 15 pushobj 00048: 15 string "You entered " 00051: 15 getvar 0 00054: 15 add 00055: 15 string " and " 00058: 15 add 00059: 15 getvar 1 00062: 15 add 00063: 15 string "\\n" 00066: 15 add 00067: 15 call 1 00070: 15 pop 00071: 15 stop
dumpheap(([fileName[, start[, toFind[, maxDepth[, toIgnore]]]]])
Dump GC information. This is a thin wrapper for JS_DumpHeap
.
gczeal(zeal)
Enable extra-frequent GC, to help find GC hazards. zeal is an integer. The meaning is the same as for the parameter to JS_SetGCZeal
.
notes([function])
Shows the source notes for the specified function. Source notes contain information that map the bytecode to the source code, which is used when decompiling the code, such as when using the dissrc()
function.