7 Tricks With Javascript
When I began learning JavaScript, I make a list trick I had found in other people’s code, on the website or anywhere. Those things helped me a lot in writing code and improving working performance.
And in this article, I will share with you 7-tips that strike me as particularly clever and useful. This post suitable for beginners with JavaScript, but I hope to bring new knowledge to experienced people too.
Let’s Start!
1. Not-Not Operator | !!
When function returns a falsy value (Could be null, undefined, NaN, empty string or 0, …), and then you want to transfer that falsy value to Boolean (true/false), you can use !!
.
There is no official name for it, but everyone often called “Non-inverted Boolean”.
const val1 = null;
console.log(!val1)
>> true
console.log(!!val1)
>> false
const val2 = [];
console.log(!val2)
>> false
console.log(!!val2)
>> true
const val3 = '';
console.log(!val3)
>> true
console.log(!!val3)
>> false
Copy
NaN is falsy, but it is not really False. typeof NaN = “number”
2. Convert to String
To quickly convert a number to a string, we can use the concatenation operator +
follow by an empty set of quotation marks ""
.
const value = 1 + "";
console.log(value);
>> "1"
console.log(typeof value);
>> "string"
Copy
Even though I typically do it like this for simple convenience, over 1,000s of iterations it appears for raw speed there is an advantage for .toString()
3. Convert to Number
To quickly convert a string to number, we can use addition operator:
let value = "10";
value = +value;
console.log(value);
>> 10
console.log(typeof value);
>> "number"
Copy
There may be context where +
will be understood as the concatenation operator rather than the addition operator. When that happens ( And in case you want to convert a float number to int number ), you can use ~~
(two tildes) operator:
console.log(~~"10")
>> 10
console.log(~~"10.5")
>> 10
Copy
How this work ?
A tilde, called as the “bitwise NOT operator”, is an operator equivalent to-n — 1
. So, for example, ~10
is equal to -11
When you using two tildes in a row effectively negates the operation, because
(~n = -n-1) => ~~n = -(-n-1)-1 <=> ~~n = n
4. Quick Float to Number
If you want to convert float to number, you can use Math.floor()
, Math.ceil()
or Math.round()
. But, there is a faster way truncate float to an integer use |
, the “bitwise OR operator”.
console.log(10.5 | 0)
>> 10
console.log(-10.5 | 0)
>> -10
Copy
5. Remove final digits (base on bitwise OR operator)
The “bitwise OR operator” can also be used to remove any amount of final digits from the end of an integer number. This means you don’t need write code like this to transfer and remove a final digit from a string number:
const value = "1234"
Number(value.substring(0, value.length - 1));
>> Result: 123
Copy
Instead, shorten code with the “bitwise OR operator”:
console.log(1234 / 1000 | 0)
>> 1
console.log(1234 / 100 | 0)
>> 12
console.log(1234 / 10 | 0)
>> 123
6. Get Unique Values of an Array
Since started learning JavaScript, I met a lot case have to retrieve unique values from an array with JavaScript, and we can easy way of unique value management using objects like this.
/Make sure an array called "foundKeywords" was defined above
if(shouldSave(keyword)) {
foundKeywords.push(keyword);
}
// The result of foundKeywords when done will be
["keywork1", "keywork2", "keywork3", ...]
Copy
And now, with ES6, we can use new JavaScript spread operator with Set:
var result1 = [...new Set([1, 2, 3, 3])]
>> [1, 2, 3]
var result2 = Array.from(new Set([1, 2, 3, 3]))
>> [1, 2, 3]
Copy
Awesome ! I love the mixture of rest expression and
Set
!
7. Get the Last Item(s) in an Array
The array method slice()
can take negative integers, and if provided it will take values from the end of the array rather than the beginning.
let array = [0, 1, 2, 3, 4, 5];
console.log(array.slice(-1));
>> [5]
console.log(array.slice(-2));
>> [4, 5]
console.log(array.slice(-3));
>> [3, 4, 5]
Copy
Hope you like this article!
TECH TOWN – TECHNOLOGY CONSULTING FOR YOUR BUSINESS
CONTACT US:
📞Phone: +84 81-716-0331
🌐Website: https://techtown.asia
📧Email: info@techtown.asia
📍Address: Floor 6, Vinhomes Central Park, No 208 Nguyen Huu Canh, Ward 22, Binh Thanh District , HCMC.
– Japan Representative : Floor 7, Honmachi Minami Garden City, 3-6-1 Kitakyuhoji Machi, Chuo-Ku, Osaka, 541-0057, Japan
– United States Representative office: 10802 Capital Ave, Garden Grove, CA 92843, United States
– Canada Representative office: 100 City Centre Dr. Unit 206 – Level 1, Mississauga, ON, L5B 2C9