- You can use + in front of a string to convert it into a number.
console.log(typeof +"5") //number
-
+ in front of date object will convert in into number of milliseconds.
console.log(+new Date()) //1634538267248
-
| 0 after a floating point number will convert in into a integer.
console.log(35.354 | 0) //35
- If an array only contains one number you can use + in front of array to convert it into a number.
console.log(typeof +[6]) //number
- Use es6 to remove duplicates from array.
console.log([...new Set([1,2,2,3,4,4,5])]) //[1, 2, 3, 4, 5]
- Converting Numbers array to Strings array
console.log([1,2,2,3,4,4,5].map(String)) //['1', '2', '2', '3', '4', '4', '5']
- Converting String array to Numbers array
console.log(['1', '2', '2', '3', '4', '4', '5'].map(Number)) //[1, 2, 2, 3, 4, 4, 5]
-
HTML comment is valid in JavaScript WTF đ€Ł
<!--Don't mind me I am just a comment--> console.log("Hello")
Compare three values without using &&.
console.log(3 > 2 < 5) //false
Deep copy object using JSON.stringify and JSON.parse
console.log(obj == JSON.parse(JSON.stringify(obj))) // false
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (2)
You should stop using "tricks" to convert types in javascript and start using explicit type conversion.
Implicit type conversion is bad for readability and leads to errors.
Your "trick" number 9 prove my point : it does not compare 3 values like you say but instead evaluate
3 > 2
which returnsfalse
, then implicitly convertfalse
to0
because a boolean cannot be compared to a number, then it returns the result of0 < 5
which istrue
.Try
2 > 0 < 1
and you will see it does not work.Try number 10 with a
Date
object or any other object that define thetoJSON
method...Be explicit about your type conversions. Using tricks like
+'5'
and+new Date()
will just confuse beginners (and it requires you to memorize these "tricks". What's wrong withparseInt('5')
ornew Date().getTime()
(or even,Date.now()
)?The last item is the worst here, though.
JSON.parse(JSON.stringify(obj))
won't work in many cases. There are many cases, not even edge cases, where this won't perform a correct clone.You lose any functions the source object has:
You lose any inherited properties from the prototype chain:
It messes with class instances too:
Use a proper deep clone function.
You are teaching beginners a lot of terrible practices with these posts tagged #beginners...