简体   繁体   中英

Convert a statement to ES5

I need helps with convert the statement below to ES5 syntax. What will it be in ES5?

const { a, b, c = “foo” } = this.props;
 var
   a=this.props.a,
   b=this.props.b,
   c=this.props.c||"foo";

Object destructuring trys to find properties with the same name in the object, so

 {prop}=obj

equals:

 prop=obj.prop;

The default parameter can be easily achieved with an Or operator:

 prop=obj.prop || default;

or if you want to count falsys as a prop, itll be:

 prop=("prop" in obj)?obj["prop"]:default;

I suggest to use an explicit check if property c exists in the given object or not. If not given, then use the default value.

var a = this.props.a,
    b = this.props.b,
    c = this.props.c === undefined ? 'foo' : this.props.c;

The otherwise used pattern

c = this.props.c || 'foo';

does not work for given falsy value like zero.

Why do you need a check with undefined (kudos to loganfsmyth for mention this problem in comments)?

Because undefined is the value for the check for default parameters in a function in ES6.

 const f = (c = 'foo') => console.log(c); f(); // 'foo' f(undefined); // 'foo' f(0) // 0 

I believe it would be :

var a = this.props.a,
    b = this.props.b,
    c = this.props.c || "foo"

At least I hope, otherwise it'll be raining downvotes

The easiest way to achieve this would be:

var a = this.props.a,
b = this.props.b,
c = this.props.c===undefined?"foo":this.props.c

But the better way would be to just use the this.props object instead of storing it in local variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM