Skip to content

if statements return first condition on nil value #42

@jqr

Description

@jqr

When an if statement encounters a value that is nil, all condition evaluation stops and the condition is returned.

JSONLogic.apply({ "if" => [true, nil] }, {})            # => true   (expected nil)
JSONLogic.apply({ "if" => [false, nil] }, {})           # => false  (expected nil)
JSONLogic.apply({ "if" => [false, nil, true, 1] }, {})  # => false  (expected 1)

Background

if generally has the form [condition1, value1, condition2, value2, ...] and the first condition to be truthy returns the associated value, and if no conditions match null is returned.

{ "if": [false, 1] }            // => null
{ "if": [false, 1, true, 2] }   // => 2
{ "if": [false, 1, false, 2] }  // => null

There is a special case with an odd number of arguments [condition1, value1, condition2, value2, value_else] where the value_else is returned if none of the previous conditions match.

{ "if": [false, 1, 2] }            // => 2
{ "if": [false, 1, false, 2, 3] }  // => 3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions