ES6 js keywords as param exact behavior

Viewed 63

I have a code which is expected to return 'undefined' or any error but it gives output as mentioned.

let i = (x, c) => {
    c(x);
};

i(20, (undefined) => {
    let j = undefined;
    console.log(j);
});


function y(undefined) {
    let a = undefined;
    console.log(a);
}
y(90);

How reserved words works and change behavior if used in function arguments?

2 Answers

undefined is not a reserved word.

It is a global, readonly variable.

Nothing stops you defining another variable with the same name in a narrower scope.

undefined is not a reserved word, as you can see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords.

In your scenario, undefined actually holds the callback value, which is 20 in the first case and 90 in the second one.

For instance, if you want to assign the value undefined to the scoped j or a, you can use void 0. Further informations about how void works can be found here (also, void is actually a reserved word in javascript): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void

let i = (x, c) => {
    c(x);
};

i(20, (undefined) => {
    let j = void 0;
    console.log(j);
});


function y(undefined) {
    let a = void 0;
    console.log(a);
}
y(90);

Related