3

There's problem when I test my code on Google Chrome and I don't have any problem when test it on Firefox. I've a function and I call it in onblur event. It's working fine on Firefox but Google Chrome gave me this error on the console

Uncaught ReferenceError: fill is not defined

HTML code:

<input type="text" name="title" id="title" placeholder="mytitle" onblur='fill(this);'>

JavaScript code:

function fill(element,value = false){
    if(element.value == ""){
        $("#"+element.id).css('border-color','red');
    }else{
        $("#"+element.id).css('border-color','#56de56');
    }
    if(value == true){
        if(element.value > 75 || element.value < 5)
            $("#"+element.id).css('border-color','red');
    }
}

and I declared fill function before that line and after that line so I'm facing the same problem.

1 Answer 1

3

EcmaScript, the standard JS is based on as of version 5.1 does not support optional parameters.

function fill(element,value = false){

Does not do what you expect it to. Instead, you have to do this manually:

function fill(element,value){
     if(typeof value === 'undefined') {
          value = false;
     }

Or in a shorter notion if you're only expecting boolean values

function fill(element,value){
    value = value || false;

Note - These both have cases they miss - as Fabrício Matté suggested in the comments you can also check arguments.length if you want to differenciate not getting an argument passed, and getting undefined explicitly although that's rarely the case.

although optional parameters are in the EcmaScript 6 proposal

(Firefox however, does independently support them even today)

Sign up to request clarification or add additional context in comments.

6 Comments

You meant the ECMAScript 5.1 spec I believe.
@FabrícioMatté right you are, mixed up what I thought about and what I wrote - started writing "You can't do optional parameters in JavaScript yet" and changed my mind. Thanks for the catch!
@BenjaminGruenbaum really !! .. ok i will test it without optional parameter
@YahiaSweid-BillGates It's one of those cases where Firefox developers at mozilla eagerly implemented a language feature that made it through to the ECMAScript 6 draft :)
You can also use if (arguments.length < 2), in the rare case when passing undefined as the value argument must be treated differently from omitting the argument.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.