.png?type=webp)
10 crazy oneliners in javascript
11 December, 2022
3
3
0
Contributors
1.
[1, 2, 3].reduce((a, b) => a + b)
- This line uses the reduce
method to sum the values in an array. It returns the result 6
.
2.
'Hello, world!'.split('').reverse().join('')
- This line uses the split
, reverse
, and join
methods to reverse the characters in a string. It returns the result "!dlrow ,olleH"
.
3.
(() => 'Hello, world!')()
- This line defines and immediately invokes an anonymous arrow function that returns the string "Hello, world!"
. It returns the result "Hello, world!"
.
4.
Array.from(Array(10), (_, i) => i + 1)
- This line uses the Array.from
method to create an array of 10 numbers, starting from 1. It returns the result [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.
5.
[1, 2, 3].map(x => x * x)
- This line uses the map
method to square the values in an array. It returns the result [1, 4, 9]
.
6.
[1, 2, 3].filter(x => x % 2 === 0)
- This line uses the filter
method to return only the even numbers from an array. It returns the result [2]
.
7.
['a', 'b', 'c'].forEach((x, i) => console.log(x, i))
- This line uses the forEach
method to log each character in a string along with its index to the console. It outputs the results "a 0"
, "b 1"
, and "c 2"
to the console.
8.
'Hello, world!'.replace(/[aeiou]/g, '*')
- This line uses the replace
method to replace all vowels in a string with the character "*"
. It returns the result "H*ll*, w*rld!"
.
9.
'Hello, world!'.split(' ').join('_')
- This line uses the split
and join
methods to replace all spaces in a string with the character "_"
. It returns the result "Hello,_world!"
.
10.
(x => x * x)(10)
- This line defines and immediately invokes an anonymous arrow function that squares its argument. It returns the result 100
.
develevate
toolstipstricks