I am curious.
What is the meaning of [+
in this code:
ngOnInit() {
this.route.paramMap.subscribe(params => {
this.product = products[+params.get('productId')];
});
}
I am curious.
What is the meaning of [+
in this code:
ngOnInit() {
this.route.paramMap.subscribe(params => {
this.product = products[+params.get('productId')];
});
}
Changes the string to integer/ number.
For example:
If you have "60". This is a string but if you add +
front of it. This is a number now: 60
In your code, params.get('productId')
returns string, and you might need it as number. It's short hand but it only convert numbers wrapped with string to number - not "one" to 1.
Also, [+
. The first bracket is opening bracket for accessing element of the array based on index or element/ property of the object. For instance, products[5]
.
This is also called Unary plus (+)
,
+false // 0
+‘123’ // 123
+0xBABE // 47806 (Hexadecimal)
+null // 0
+function(val) {return val } // NaN
There is a detailed article if you are interested to read more on it:
https://medium.com/@nikjohn/cast-to-number-in-javascript-using-the-unary-operator-f4ca67c792ce
There is nothing related to Angular here.
This is the concept of Javascript, Basically It will change the value to number type (format).
While you pass your parameter in routing, by default it is in string format, in order to accept the same in integer format, generally follow this method.
For example -
new Date() // output Wed Sep 25 2019 00:35:05 GMT+0530 (India Standard Time)
+new Date() // output 1569351921895
[+
by itself doesn't mean anything, it's two separate things combined together.
The key piece is +params.get('productId')
, which means "take the value of productId and force it into a numeric value." For instance, +"1"
will become 1 as a number instead of a string, and +"foo"
will become NaN.
Then the [
is just the opening bracket for the subscript notation.
For instance, if productId is "1"
, then it will reduce to products[1]
.
ngOnInit() {
this.route.paramMap.subscribe(params => {
this.product = products[+params.get('productId')]; // here [+params.get(productIs) ] returns you number with use of + operator and [+ means starting a bracket to map the array.
});
}
I hope you now understood the meaning.
implicit conversion of values from one data type to another, in this case from string to number.
https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion