Javascript function default parameter incorrect

Viewed 36

Why does the code at this JS fiddle not work? I want it to log a blank string, but it's logging a Pointer Event. https://jsfiddle.net/wvom7k2f/

let c = document.getElementById('c');
c.onclick = test;

function test(a='', b=''){
console.log(a);
}
2 Answers

An onclick event handler will put the event as the first parameter. If you want to call test with no parameters you should change c.onclick = test; to the following:

c.onclick = () => test();

You're doing c.onclick = test. The onclick event calls its function with the event as the 1st parameter.

Try to do:

function test(e, a='', b='') {
    console.log(a);
}

c.onclick = test;

Or, if you don't want to change test(), then you can do:

function test(a='', b='') {
    console.log(a);
}

c.onclick = function(e) {
    test();
};
Related