Search code examples
javascriptjqueryternary

Assign 0 if the value is null or empty in Jquery


I want to use a ternary operator for the below jQuery statement like if employee_salary is empty or null, I want to assign as 0 (zero). Otherwise, just assign the actual value.

jQuery('#employee_form #employee_salary').val(parseInt(selected_table_data['employee_salary']))

Solution

  • var employee_salary = selected_table_data['employee_salary'];
    var salary_form_value = employeeSalary ? parseInt(employee_salary) : '0';
    jQuery('#employee_form #employee_salary').val(salary_form_value);
    
    // If you want to inline it, you could do the following:
    
    jQuery('#employee_form #employee_salary').val(
      selected_table_data['employee_salary']
        ? parseInt(selected_table_data['employee_salary']
        : 0
    );

    Here is an example

    const s1 = null;
    console.log(s1 ? s1 : 'There was a null value');
    
    const s2 = ''
    console.log(s2 ? s2 : 'There was an empty string');
    
    const s3 = 'value';
    console.log(s3 ? s3 : 'There was no value');