Home > Net >  JavaScript Advanced Syntax - I don't understand
JavaScript Advanced Syntax - I don't understand

Time:07-17

So I recently copied this code from the internet to format strings inline:

module.exports=function(){
    String.prototype.FormatPlus = String.prototype.FormatPlus || function(){
        "use strict";
        let str = this.toString();
        if (arguments.length) {
            let t = typeof arguments[0];
            let key;
            let args = ("string" === t || "number" === t) ? Array.prototype.slice.call(arguments) : arguments[0];
            
            for (key in args) {
                str = str.replace(new RegExp("\\{"   key   "\\}", "gi"), args[key]);
            }
            
            return str;
        }
    }
}

I understand most of it, except this part:

let args = ("string" === t || "number" === t) ? Array.prototype.slice.call(arguments) : arguments[0];

Is there any professional JavaScript Node.js programmers that can break-down every bit of this line please? Thank you.

CodePudding user response:

t is the type of the first argument. So the ternary conditional expression tests whether the first argument is a string or number.

If it is, arguments is converted to an array by calling Array.prototype.slice(), and this is assigned to args.

If not, the first argument is assigned to args.

This can be written more clearly, using modern EcmaScript 6 features:

let args;
if (t === 'string' || t == 'number') {
    args = [...arguments];
} else {
    args = arguments[0];
}

The purpose of this is to allow the caller to provide the values to be formatted as a single array or object, or spread as separate arguments.

CodePudding user response:

arguments is an array type. if first element of argument array is of type string or number then you are just returning entire argument array itself by calling slice method of Array & assigning it to args.

If first element of argument is not of type string or number then you are returning just first element of argument & assigning it to args.

? is ternary operator in javascript which is similar to if.else block.

CodePudding user response:

Array.prototype.slice() returns a shallow copy of a portion of an array into a new array object.

In the function you provided, t is an alias for typeof arguments[0].

So in your code, when the first element of arguments is a string or a number, you call the Array.prototype.slice() function on every element.

For example, if arguments[0] is the string "hello world", Array.prototype.slice.call("hello world") would return ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'].

  • Related