12 JavaScript Tricks For Novice Programmers

JavaScript Tricks For Novice Programmers from Coding Compiler. A small selection of JavaScript tricks and utilities for creating short and effective code that you will not find in the textbooks. Most textbooks and tutorials explain basic concepts and constructions to novice programmers. From these, you get the academic JavaScript basics of the language, but the practical tricks will have to be recruited independently.

JavaScript Tricks for Novice Programmers

Many of the JavaScript tricks described in this article have become possible only in the latest JS standards, so you won’t find them in the old manuals. Others sacrifice readability for brevity, so they are not mentioned, so as not to embarrass the mind of newcomers. A couple of tricks can still be found in the textbooks, but you could well have missed them.

JavaScript Array Tricks

Filtering Unique Values

In the ES6 standard, a new type of object has appeared Set. Combining it with the spread operator ( …), you can easily get a new one from the old array, which will have only unique values.

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 5]

Before ES6, you would have to write much more code to solve this problem!

[Related Article: Introduction to JavaScript]

Loop length caching

When we learn programming in JavaScript, then in all tutorials we meet the following standard loop construction for:

for (let i = 0; i < array.length; i++){
console.log(i);
}

Need to follow the recommended pattern, right? But it is not quite optimal. At each iteration of the loop, the length of the array array will be calculated anew. Sometimes this is useful, but in most cases it will be more efficient to cache it after the first calculation. To do this, create a variable length. This can be done in the first part of the condition, along with the definition of a loop counter:

for (let i = 0, length = array.length; i < length; i++){
console.log(i);
}

The conciseness of the code almost does not suffer, but when working with large arrays, it will work a little more efficiently.

[Related Article: Javascript Reference and Specifications]

Shortening

This is one of the most famous JavaScript tricks, but it will not hurt to repeat it.

To remove multiple values from the end of the array, not necessarily to use the methods slice(), splice()or pop(). Just override the property length:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;
console.log(array); // [0, 1, 2, 3]

This works only with arrays, but with Set, for example, the trick will not work.

[Related Article:Javascript Code editors ]

Getting items from the end

You slice()can pass a negative parameter to the method , then the counting of elements starts from the end of the array.

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(array.slice(-1)); // [9]
console.log(array.slice(-2)); // [8, 9]
console.log(array.slice(-3)); // [7, 8, 9]

Javascript type conversion tricks

Conversion to string

You can quickly convert a number to a string using the operator +, simply concatenating it with an empty string.

const val = 1 + "";
console.log(val); // "1"
console.log(typeof val); // "string"

Conversion to number

For the reverse transformation, the ubiquitous is again useful +.

let int = "15";
int = +int;
console.log(int); // 15
console.log(typeof int); "number"

Boolean values ​​can also be turned into numbers:

console.log(+true);  // 1
console.log(+false); // 0

In some contexts, it + acts as a concatenation operator, so an alternative is needed.

If you work with integers (without the fractional part), pay attention to the operator ~ (tilde), also known as “bitwise NOT”. Each bit of the operand it replaces with the opposite. The expression ~n is equivalent -n-1, for example ~15 = -16.

If this operator is a string, then converts it to a number: ~”15″ = -16.

[Related Article: Javascript Developer Console ]

Applying bitwise negation to the result of another bitwise negative operation successfully cancels the effect, that is, returns the original number. Really -(-n-1)-1 = n. In other words, ~-16 = 15.

const int = ~~"15"
console.log(int); // 15
console.log(typeof int); // "number"

If desired, you can use bitwise negation and with boolean values, although you can hardly find many uses for this:

~true = -2
~false = -1

Using these JavaScript tricks is justified only if you are well aware of what their action is based on.

[Related Article: JavaScript Hello World.!]

Conversion to boolean type

The programming language JavaScript can consider any value from a logical point of view. Everything converted to false is called “falsy” (false). This number is 0, the empty string “”, null, undefined, NaN and, of course, false. All other values ​​are true (“truthy”). This concept is supported by many JavaScript tricks.

The logical negation operator ! can work with values ​​of any type. It converts any falsy value to true, and any truthy to false. Thus, the output is always a boolean value.

Here are javascript examples:

const true  = !0;
const false = !1;
const alsoFalse = !!0;

console.log(true); // true
console.log(typeof true); // "boolean"

Such a conversion can be convenient in conditional statements.

[Related Article: External JavaScript Files ]

A couple of math javascript tricks

Check out our article on working with numbers and mathematical methods in JS.

Rapid exponentiation

The ES7 standard offered us a new operator ** for raising a number to a power

2 ** 3; // 8

This is clearly shorter than Math.pow(2, 3).

You probably expected to see a more familiar symbol here ^. But in JavaScript, it’s already taken — it’s bitwise exclusive OR (XOR).

Before ES7, we had a short exponentiation method only for the number 2 using the bitwise left shift operator <<:

// These expressions are equivalent.

Math.pow(2, n);
2 << (n - 1);
2**n;

For example,, 2 << 3 = 16 and 2 ** 4 = 16.

[Related Article: JavaScript Code Structure]

Fast rounding

If you need to make a fractional number an integer, you use Math.floor(), Math.ceil()or Math.round()- depending on the desired effect. But there is a faster way – bitwise OR.

console.log(23.9 | 0);  // 23
console.log(-23.9 | 0); // -23

The behavior of an operator with positive and negative operands is different. Positive rounded down, negative – up. All digits after the decimal point are deleted.

The same effect can be achieved with the help of other JavaScript tricks, for example, the familiar double bit negation operator ( ~~).

[Related Article: Use Strict in JavaScript]

Deletion of discharges

Using bitwise OR, you can remove digits from a number without confusing with the fractional part:

console.log(1553 / 10   | 0)  // 155
console.log(1553 / 100  | 0) // 15
console.log(1553 / 1000 | 0)  // 1

Three JavaScript Bonus Tricks

Short calculations in one chain

The ternary operator provides a simple and fast way to perform simple – and sometimes not very simple – conditional calculations.

x > 100 ? 'More 100' : 'Less 100';
x > 100 ? (x > 200 ? 'More 200' : 'Less 100 и 200') : 'Less 100';

But sometimes even the ternary operator is too complicated. If your programming spirit craves for brevity, pay attention to logical operators && and ||.

[Related Article: JavaScript Variables ]

How it works?

Suppose you only need to choose one of several options.

The operator && returns the first “falsy” value in the chain. If a miracle happens, and each operand is true, the last executed expression will be returned.

let one = 1, two = 2, three = 3;

console.log(one && two && three); // 3
console.log(0 && null); // 0

The operator ||, on the contrary, returns the first “truthy” value. And if all the links in the chain are false, the calculated value of the last expression will be returned.

let one = 1, two = 2, three = 3;

console.log(one || two || three); // 1
console.log(0 || null); // null

JavaScript example – 1

It is required to receive value of property of length some array. However, instead of an array you can get undefined, and in this case there will be an error.

You can use a construct if/else to check if a variable is defined foo. This entry is quite acceptable, but long. Here are shorter javascript code examples:

// так
(foo || []).length;
// или так
return ([] && foo).length;

If a variable foo in a logical context is false (for example, this null or undefined), then an empty array will be substituted for it as the default value.

[Related Article: JavaScript Design Patterns Tutorial ]

Javascript example 2

Familiar with the problems of accessing deep nesting properties? At any level, the desired object may not be available, and an error will occur.

Suppose there is an object John, and you would like to know the name of John’s wife ( John.wife.name). However, it may very well be, John is not married, it is necessary to clarify this point.

 if (John.wife && John.wife.name) {
 return John.wife.name;
} else {
 return “John, it's time you get married";
}

5 lines of code is a lot for lazy programmers. Let’s shorten:

 John.wife && John.wife.name || "John, it's time you get married"; 

Here we combined two logical operators. The && priority is higher, therefore it is always executed first. If John does not have a wife – or his wife suddenly doesn’t have a name for some reason – we return the default value.

[Related Article: JavaScript Data Visualization Libraries]

New language features

Problems with the structure of objects are very common, so a suggestion was made to add “optional chaining” to the JavaScript language. They allow you to query deeply embedded properties without fear of errors. The movement along the chain will be continued only if the current property is not equal null.

John.wife?.brother?.dog?.name; 

If the brother of John’s wife has a dog, this expression will return her nickname.

[Related Article: JavaScript Animation Libraries ]

The proposal is now in the first stage of consideration (experimental opportunity). You can read about it or try it in action with Babel. To do this, add the @ babel / plugin-proposal-optional-chaining plugin to the .babelrc file .

Automatic Binding in classrooms

If you use pointer functions when creating methods, such methods are implicitly attached to class instances! This allows you to save a few lines of code and get rid of boring constructions like this.myMethod = this.myMethod.bind(this).

import React, { Component } from React;
export default class App extends Component {
constructor(props) {
super(props);
this.state = {};
}
myMethod = () => {
  //This method is implicitly related to this.
}
render() {
  return (
<>
   <div>
     {this.myMethod()}
   </div>
</>
  )
}
};

[Related Article: JavaScript Guide]

JSON formatting

Most likely, you have repeatedly used the method JSON.stringify(). Did you know that it can independently format your JSON code?

stringify() It can take two optional parameters (except for the first – the object itself for serialization):

  • replacer – a function for converting values ​​and properties or an array of those properties that should be included in a serialized object.
  • space – specifying the number of spaces in front of each level of nesting or string to be inserted before each level, for example “\t”.
console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));
// '{
// "alpha": A,
// "beta": B
// }'

You may have found some interesting ones among these tips.

Remember that not all of these JavaScript tricks are usable in production. Some are more likely to explore the possibilities of language and code golf.

Related JavaScript Tutorials

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
Use Strict in JavaScript


Leave a Comment