Sample code for 30+ languages & platforms
Rust Requires Chilkat v11.4.0+

Call a JavaScript Function Returning a Boolean

See more JavaScript Examples

Demonstrates how to call a JavaScript function that returns a boolean.

Chilkat Rust Downloads

Rust

// This is the JavaScript function we'll call:

// function isEven(number) {
//     return number % 2 === 0;
// }

let sb_script = chilkat::StringBuilder::new();
let _ = sb_script.append("function isEven(number) { return number % 2 === 0; }");

let js = chilkat::Js::new();

let result = chilkat::JsonObject::new();
result.set_emit_compact(false);

// Call Eval to add the function to the context's global object
if js.eval(&sb_script, &result).is_err() {
    // Examine the result for an exception.
    println!("{}", result.emit().unwrap_or_default());

    // Also examine the LastErrorText.
    println!("{}", js.last_error_text());
    return;
}

// ------------------------------------------------------------------------------
// Call the function isEven(8)

let func_call = chilkat::JsonObject::new();

// Create JSON specifying the function name and arguments

// {
//   "name": "isEven",
//   "args": [ 8 ]
// }

let _ = func_call.update_string("name", "isEven");
let _ = func_call.update_int("args[0]", 8);

if js.call_function(&func_call, &result).is_err() {
    // Examine the result for an exception.
    println!("{}", result.emit().unwrap_or_default());

    // Also examine the LastErrorText.
    println!("{}", js.last_error_text());
    return;
}

println!("{}", result.emit().unwrap_or_default());

// Output:
// {
//   "type": "bool",
//   "value": true
// }

let retval = result.bool_of("value");
println!("{}", retval);

// Output:
// true