Greetings. I present to your attention the translation of the article "My Favorite JavaScript Tips and Tricks" published on July 28, 2020 by Tapas Adhikary
Most programming languages ββare open enough to provide developers with the ability to do the same thing in different ways. JavaScript is no exception. Often, we have different ways to achieve the same result, which can sometimes even be confusing.
At the same time, some techniques have advantages over analogues. In this article, I provide a list of my favorites. I'm sure you will also be familiar with some of them.
1. Forget about concatenation, use template strings (literals)
Concatenating strings using the " +
" operator is old school. Moreover, concatenating strings involving many variables (or expressions) increases the risk of confusion and errors.
let name = 'Charlse';
let place = 'India';
let isPrime = bit => {
return (bit === 'P' ? 'Prime' : 'Nom-Prime');
}
// "+"
let messageConcat = 'Mr. ' + name + ' is from ' + place + '. He is a' + ' ' + isPrime('P') + ' member.'
Template strings (or literals) allow you to embed expressions directly into text. They have a unique syntax in which the string is enclosed in backticks (``). The template string can contain places for dynamic value substitution. Such places are marked with a dollar sign and curly braces. Eg ${}
.
Demonstration of their application:
let name = 'Charlse';
let place = 'India';
let isPrime = bit => {
return (bit === 'P' ? 'Prime' : 'Nom-Prime');
}
//
let messageTemplateStr = `Mr. ${name} is from ${place}. He is a ${isPrime('P')} member.`
console.log(messageTemplateStr);
2.isInteger
, . JavaScript API "Number
" "isInteger()
". , .
let mynum = 123;
let mynumStr = "123";
console.log(`${mynum} is a number?`, Number.isInteger(mynum));
console.log(`${mynumStr} is a number?`, Number.isInteger(mynumStr));
:
3.
- , "event.target.value
" , "input
" "number
"?
. , , , , .
<input type='number' onkeyup="trackChange(event)" />
"event.target.value
". . - . , ( 16.56)? "parseFloat()
"? - !
function trackChange(event) {
let value = event.target.value;
console.log(`is ${value} a number?`, Number.isInteger(value));
}
, "event.target.valueAsNumber
".
let valueAsNumber = event.target.valueAsNumber;
console.log(`is ${value} a number?`, Number.isInteger(valueAsNumber));
4. AND
, .
let isPrime = true;
const startWatching = () => {
console.log('Started Watching!');
}
.
if (isPrime) {
startWatching();
}
AND (&&)? , "if
" . , ?
isPrime && startWatching();
5. OR
, OR.
let person = {name: 'Jack'};
// "age" "undefined", 35
let age = person.age || 35;
console.log(`Age of ${person.name} is ${age}`);
6.
β , . .
let planets = ['Mercury ', 'Mars', 'Venus', 'Earth', 'Neptune', 'Uranus', 'Saturn', 'Jupiter'];
let randomPlanet = planets[Math.floor(Math.random() * planets.length)];
console.log('Random Planet', randomPlanet);
let getRandom = (min, max) => {
return Math.round(Math.random() * (max - min) + min);
}
console.log('Get random', getRandom(0, 10));
learn.javascript.ru, , 2 , . .
7.
JavaScript . . "undefined
", .
. "message
" "greetings
" "Hello
".
let greetings = (name, message='Hello,') => {
return `${message} ${name}`;
}
console.log(greetings('Jack'));
console.log(greetings('Jack', 'Hola!'));
8.
, .
,
let isRequired = () => {
throw new Error('This is a mandatory parameter.');
}
, . , "undefined
", , .
let greetings = (name=isRequired(), message='Hello,') => {
return `${message} ${name}`;
}
console.log(greetings());
"name
" "undefined
", - , "isRequired()
". :
9. ""
, , .
JavaScript .
let count = 1;
let ret = (count++, count);
console.log(ret);
"ret
" 2. , 32.
let val = (12, 32);
console.log(val);
? ? "for
".
"j"
"i"
.
for (var i = 0, j = 50; i <= 50; i++, j--)
10.
, , . "...
" (, ).
:
let emp = {
'id': 'E_01',
'name': 'Jack',
'age': 32,
'addr': 'India'
};
let job = {
'title': 'Software Dev',
'location': 'Paris'
};
spread- ( ):
// spread-
let merged = {...emp, ...job};
console.log('Spread merged', merged);
. "Object.assign()
":
console.log('Object assign', Object.assign({}, emp, job));
:
, spread- "Object.assign
" (shallow) . , , .
, , , lodash
11.
β , .
, :\
let [fire, clock, , watermelon] = emojis;
, "let fire = emojis[0];
", . , "", ? , ?
console.log(fire, clock, watermelon);
:
, "rest
". , , , "...rest
", .
let [fruit, ...rest] = emojis;
console.log(rest);
:
,
let shape = {
name: 'rect',
sides: 4,
height: 300,
width: 500
};
, , .
let {name, sides, ...restObj} = shape;
console.log(name, sides);
console.log(restObj);
12.
, ,
let fire = '';
let fruit = '';
[fruit, fire] = [fire, fruit];
console.log(fire, fruit);
13. isArray
, ,
let emojis = ['', 'οΈ', '', ''];
console.log(Array.isArray(emojis));
let obj = {};
console.log(Array.isArray(obj));
14."'undefined" "null"
"undefined
" β , ,
"null
" β ,
"undefined
" "null
"
undefined === null // false
15. url-
"window.location
" . , , , url- .
,
window.location.search
The " search
" property returns the portion of the url string after the question mark: " ?project=js
".
To get query parameters, in addition to " location.search
", you can use another useful API called "URLSearchParams".
let project = new URLSearchParams(location.search).get('project');
As a result, we get " js
"
Read more about this topic here
This is not the end
There are many other useful techniques. I decided to add them to the repository along with small examples as I come across them.
What are your favorite JavaScript tricks? How about sharing them in the comments below?