0% found this document useful (0 votes)
4K views

Javascript Tips E-Book

This document provides JavaScript tips and best practices for various coding scenarios. It discusses topics like using proper variable names, comparing values carefully, checking object properties, conditionally adding properties, removing duplicates from arrays, copying arrays and objects, avoiding mutations, determining array types, filtering falsy values, checking array occurrences, formatting numbers, and more. The tips aim to write clean, readable and maintainable JavaScript code.

Uploaded by

Rijo varghese
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4K views

Javascript Tips E-Book

This document provides JavaScript tips and best practices for various coding scenarios. It discusses topics like using proper variable names, comparing values carefully, checking object properties, conditionally adding properties, removing duplicates from arrays, copying arrays and objects, avoiding mutations, determining array types, filtering falsy values, checking array occurrences, formatting numbers, and more. The tips aim to write clean, readable and maintainable JavaScript code.

Uploaded by

Rijo varghese
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

TELEGRAM: CODINIT(click here)

TELEGRAM: CODINIT(click here)

Index
Introduction .................................................................. 4
JavaScript Tips ............................................................... 5
Use proper variable names ......................................... 7
Be careful with comparison using the loose equality
operator ...................................................................... 8
Check property exists in an object .............................. 9
Conditionally add a property to an object ................ 10
Use includes to check for multiple criteria ............... 11
Remove duplicates from an array using Set ............. 12
Use spread operator to shallow copy arrays and
objects ...................................................................... 13
Avoid delete keyword ............................................... 14
Use Array.isArray to determine the array ................ 15
Use of falsy bouncer ................................................. 16
Use Array.some to check occurrence in array .......... 17
Readable numbers .................................................... 18
Pass function arguments as an object ...................... 19
Object destructuring on arrays ................................. 21
Skip values in array destructuring ............................ 22
Format the output of JSON.stringify ......................... 23
Filter with JSON.stringify .......................................... 24

1
TELEGRAM: CODINIT(click here)

Power of JSON.stringify replacer parameter ............ 25


Don’t extend built-ins ............................................... 26
Use of optional chaining on function call ................. 27
Convert to a flat array using Array.flat ..................... 28
Use console.time to debug performance ................. 29
Logging using console.group .................................... 30
Conditional log message using console.assert ......... 31
Display tabular data using console.table .................. 32
Default assignment for required arguments of the
function..................................................................... 33
Avoid default exports ............................................... 34
Use of object destructuring ...................................... 35
Lock an object using the Object.freeze..................... 36
Understanding of closures ........................................ 37
Smooth scroll to a specific element .......................... 38
Use Object.entries to access key and value .............. 39
Use of nullish coalescing operator with numbers .... 40
Use semicolons manually to avoid issues generated
by ASI ........................................................................ 41
Use of template literals with expressions and function
call............................................................................. 42
Use of template literals with variable substitutions
and multiline string ................................................... 43

2
TELEGRAM: CODINIT(click here)

Get an array of keys using Object.keys ..................... 44


Ways of a function declaration ................................. 45
Use of increment (++) and decrement (--) ................ 46
Property renaming in object destructuring .............. 47
Object nested destructuring ..................................... 48
Use id to find a single element ................................. 49
Use let instead of var for blocked statement ........... 50
Use of default parameters ........................................ 51
Add dynamic property to an object .......................... 52
Use curly brackets ({}) instead of new Object() ........ 53
Use square brackets ([]) instead of new Array() ....... 54
Declare common variables outside of the loop ........ 55
Create an object from key-value pairs using
Object.fromEntries ................................................... 56
Tests every element of the array using Array.every . 57
Read property using optional chaining (?.)............... 58
Easy way to swap two variables ............................... 59
Improve variable logging using console.log .............. 60
Mask numbers using slice and padStart ................... 61
String to a number using the plus (+) operator ........ 62

3
TELEGRAM: CODINIT(click here)

JavaScript Tips

JavaScript is one of the most popular scripting or


programming language.

In 1995, Brendan Eich from Netscape designed and


implemented a new language for the Netscape
Navigator browser. It was initially named Mocha, then
LiveScript, and finally JavaScript.

JavaScript is everywhere.
• More than 94% of websites use JavaScript.
• JavaScript completes its ninth year in a row as the
most commonly used programming language.
(2021 StackOverflow developer survey)

I have used the following two images in some code


snippets with different meanings in different examples.
Image Meaning
Code is okay
Can improve code
Incorrect way

5
TELEGRAM: CODINIT(click here)

Better code
Improved code
Correct way

6
TELEGRAM: CODINIT(click here)

Use proper variable names

• Use the specific naming convention. Mostly used


camel-case naming convention.
• The variable name should be concise and
descriptive.
• It should explain the purpose.
• It is easy to pronounce.

7
TELEGRAM: CODINIT(click here)

Be careful with comparison using the loose


equality operator

Loose Equality Operator (== OR !=) performs the


automatic type conversion before comparison if
needed.
Like in the above example, you can get unexpected
output with Loose Equality Operator.

8
TELEGRAM: CODINIT(click here)

Check property exists in an object

The in operator returns the boolean value true/false.


The in operator returns true if a property exists in the
object or its prototype chain.

9
TELEGRAM: CODINIT(click here)

Conditionally add a property to an object

Use spread operator (...) to spread an object into


another object conditionally.
Use condition with && operator to add a new property
to an object. It will add a property to an object if the
condition match.

10
TELEGRAM: CODINIT(click here)

Use includes to check for multiple criteria

The includes() method determines whether an array


includes a certain value among its entries. It returns
true if a value exists, otherwise, it returns false.
Instead of extending the statement with more || (OR)
conditions, rewrite the conditional by using the
includes method.
More readable and concise alternative.

11
TELEGRAM: CODINIT(click here)

Remove duplicates from an array using Set

Set is a new data object introduced in ES6. The Set only


lets you store unique values of any type. When you
pass an array to a new Set(array), it will remove
duplicate values.
The spread syntax (...) is used to include all the items
of the Set to a new array.

12
TELEGRAM: CODINIT(click here)

Use spread operator to shallow copy arrays


and objects

Use the spread operator (...) to create a shallow copy


of the object and array.
The spread operator (...) allows us to make copies of
the original data (whether it is an array or object) and
create a new copy of it.
It is an easy and clean way.

13
TELEGRAM: CODINIT(click here)

Avoid delete keyword

Avoid a delete keyword to remove a property from an


object. This way mutates the original object and hence
leads to unpredictable behavior and makes debugging
difficult.
A better way to delete a property without mutating the
original object is by using the rest operator (...). Use
the rest operator (...) to create a new copy without the
given property name.

14
TELEGRAM: CODINIT(click here)

Use Array.isArray to determine the array

The Array.isArray() method determines if the given argument is an


Array or not.
• Returns true if the value is Array.
• Returns false if the value is not Array.

15
TELEGRAM: CODINIT(click here)

Use of falsy bouncer

A falsy value is a value that is considered false when


examined as a Boolean.
Falsy Bouncer means removing all falsy values from an
array.
Falsy values in JavaScript are false, null, 0, undefined,
NaN, and "" (empty string).
Pass the Boolean to Array.filter as the first argument
and it will serve as a falsy bouncer.

16
TELEGRAM: CODINIT(click here)

Use Array.some to check occurrence in array

If we want to check only occurrence means value exist


or not then use Array.some instead of Array.find.
The some() method checks if any array items pass a
test implemented by the provided function. If the
function returns true, some() returns true and stops.
The some() method does not change the original array.

17
TELEGRAM: CODINIT(click here)

Readable numbers

When working with large numbers it can be hard to


read them out.
The Numeric Separators allow us to use underscore (_)
as a separator in numeric literals, for example, you can
write 50000 as 50_000.
This feature improves readability.

18
TELEGRAM: CODINIT(click here)

Pass function arguments as an object

Parameters are part of a function definition. A


JavaScript function can have any number of
parameters. When we invoke a function and pass some
values to that function, these values are called function
arguments.
If a function has more than 1 parameter, it is hard to
figure out what these arguments mean when the
function is called. When you pass the arguments, the
order is important.
A better way is to create a function with object (with
properties) parameters like in the example. When we
pass the argument contained in an object it is pretty

19
TELEGRAM: CODINIT(click here)

much clear from the names of the properties. Also, the


order of properties doesn’t matter anymore.

20
TELEGRAM: CODINIT(click here)

Object destructuring on arrays

The destructuring assignment provides a clean way to


extract values from arrays and objects. Array
destructuring is a way that allows us to extract an
array’s value into new variables.
Each item in the array has an index. The property name
corresponds to the index of the item that returns the
value like in the example.
It is an easy way to get a specific item from an array in
a single line of code.

21
TELEGRAM: CODINIT(click here)

Skip values in array destructuring

Destructuring means breaking down a complex


structure into simpler parts.
Array destructuring is a way that allows us to extract
an array’s value into new variables. Sometimes we
don't need some values from the array means we want
to skip those values. During the destructuring arrays, if
you want to skip some values, use an empty
placeholder comma.
This is a clean way to skip values.

22
TELEGRAM: CODINIT(click here)

Format the output of JSON.stringify

The JSON.stringify() method converts a JavaScript


object to a JSON string.
The 3rd parameter to JSON.stringify() is called spacer.
You can pass String or Number value to insert
whitespace in the returned string.
If the 3rd parameter is a Number, it indicates the
number of spaces for indenting purposes.
If the 3rd parameter is a String, the string is used as
whitespace.

23
TELEGRAM: CODINIT(click here)

Filter with JSON.stringify

The JSON.stringify() method converts a JavaScript


object to a JSON string.
The 2nd parameter to JSON.stringify() is a replacer or
filter that can be a function or an array.
When 2nd parameter is passed as an array, it works as
a filter and includes only those properties in the JSON
string which are defined in an array.

24
TELEGRAM: CODINIT(click here)

Power of JSON.stringify replacer parameter

The JSON.stringify() method converts a JavaScript


object to a JSON string.
The 2nd parameter to JSON.stringify() is a replacer or
filter that can be a function or array.
When 2nd parameter is passed as a replacer function,
it alters the behavior of the stringification process. As a
function, it takes two parameters, the key and the
value being stringified.

25
TELEGRAM: CODINIT(click here)

Don’t extend built-ins

Extending built-in Objects/types or Array is not a good


practice in JavaScript.
A better way is to create your own utility library and
use it.

26
TELEGRAM: CODINIT(click here)

Use of optional chaining on function call

The optional chaining operator (?.) is a safe and


concise way to access properties that are potentially
null or undefined.
The chaining operator (.) throws an error if a reference
is null or undefined.
The optional chaining operator (?.) will return
undefined if a reference is null or undefined.
Just like with properties, we can use the optional
chaining operator with methods also.
Less code and clean way.

27
TELEGRAM: CODINIT(click here)

Convert to a flat array using Array.flat

Flattening an array is the process of reducing the


number of dimensions of an array to a lower number.
The flat() method creates a new array with all items of
subarray concatenated into it recursively up to the
specified depth.

28
TELEGRAM: CODINIT(click here)

Use console.time to debug performance

The console object has time() and timeEnd() methods.


These two methods help us to analyze the
performance of our code.
The console.time() method starts a timer to track how
long an operation takes. You can give each timer a
unique name. When you call console.timeEnd() with
the same name, the browser will output the time in
milliseconds.

29
TELEGRAM: CODINIT(click here)

Logging using console.group

The console object has group() and groupEnd()


methods.
The console.group() method starts a new inline group
in the web console log. This method takes an optional
argument label.
The console.groupEnd() method ends the group.
It organizes your messages and improves visibility.

30
TELEGRAM: CODINIT(click here)

Conditional log message using console.assert

The console object has an assert() method which helps


to log an error message conditionally.
The console.assert() method writes an error message
to the console if the assertion is false. If the assertion is
true, nothing happens.

31
TELEGRAM: CODINIT(click here)

Display tabular data using console.table

The console object has a table() method which allows


you to display arrays and objects to the console in
tabular form.
The console.table() method provides better data
visualization.

32
TELEGRAM: CODINIT(click here)

Default assignment for required arguments of


the function

You can use default parameters to make the function


arguments required.
If you don't provide the parameter, it will default to the
function which throws an error.
Note that null is considered a value, so passing null will
not result in a default assignment.

33
TELEGRAM: CODINIT(click here)

Avoid default exports

Problems with default exports are:


• Discoverability is very poor for default exports.
• Difficult to analyze by automated tools or provide
code autocompletion.
• Horrible experience for CommonJS.
• TypeScript auto-import struggles.
• Default exports make large-scale refactoring
impossible.

34
TELEGRAM: CODINIT(click here)

Use of object destructuring

Object destructuring provides a unique way to neatly


extract an object’s value into new variables.
To assign values to variables, declare the variables in
curly brackets and assign the object like in code
snippet.
To destructure into existing variables must surround
the variables with parentheses.

35
TELEGRAM: CODINIT(click here)

Lock an object using the Object.freeze

The Object.freeze() method freezes an object. A frozen


object can no longer be changed.
This method prevents new properties from being
added and modification of existing properties.

36
TELEGRAM: CODINIT(click here)

Understanding of closures

A closure is a mechanism that allows the inner function


to remember the outer scope variables when it was
defined, even after the outer function has returned.
The closure has three scope chains:
• It can access its own scope means variables
defined between its curly brackets ({ }).
• It can access the outer function’s variables.
• It can access the global variables.

37
TELEGRAM: CODINIT(click here)

Smooth scroll to a specific element

The Element.scrollIntoView() method scrolls the


specified element into the viewing portion of the
window.
It provides the behavior option for smooth scrolling.

38
TELEGRAM: CODINIT(click here)

Use Object.entries to access key and value

The Object.entries() method is used to return an array


of a given object's own enumerable property [key,
value] pairs.
The order of the properties is the same as in an object.

39
TELEGRAM: CODINIT(click here)

Use of nullish coalescing operator with


numbers

A Nullish value is a value that is either null or undefined.


The Nullish Coalescing Operator (??) is a logical operator that
accepts two values and returns the second value if the first one is
null or undefined and otherwise returns the first value.

40
TELEGRAM: CODINIT(click here)

Use semicolons manually to avoid issues


generated by ASI

ASI stands for Automatic Semicolon Insertion.


In JavaScript, semicolons are optional. JavaScript
Engine automatically inserts a semicolon, where it is
required.
If the code is not formatted correctly like in the above
example, JavaScript Engine will add a semicolon to the
end of the return statement and consider that no value
is returned. So, it returns as undefined.
You should not depend on the ASI. If ASI fails and you
are missing semicolons, the code will fail.

41
TELEGRAM: CODINIT(click here)

Use of template literals with expressions and


function call

Template Literals use back-ticks (``) instead of single


('') or double ("") quotes.
Template literals provide an easy way to interpolate
variables and expressions into strings.
Template literals allow expressions and functions in
strings.
Using template literal means not only less code but
higher readability also.

42
TELEGRAM: CODINIT(click here)

Use of template literals with variable


substitutions and multiline string

Template Literals use back-ticks (``) instead of single


('') or double ("") quotes.
Template literals provide an easy way to interpolate
variables and expressions into strings. You can do it
using the ${...} syntax.
Template literals make multiline strings much simpler.

43
TELEGRAM: CODINIT(click here)

Get an array of keys using Object.keys

The Object.keys() returns an array of a given object's


own enumerable property names.
The ordering of the properties is the same as that
when looping over them manually.

44
TELEGRAM: CODINIT(click here)

Ways of a function declaration

Functions are one of the fundamental building blocks


in JavaScript.
Following are the different ways to write functions.
• Function declaration
• Function Expression
• Arrow (=>) function
• Arrow (=>) function without curly braces ({}) – (Use
only for a single statement of code)

45
TELEGRAM: CODINIT(click here)

Use of increment (++) and decrement (--)

The increment operator (++) adds one (+1) to its


operand and returns a value. The increment (++)
operator can be used before or after the operand.
Increment Syntax: i++ or ++i
The decrement operator (--) subtracts one (-1) to its
operand and returns a value. The decrement (--)
operator can be used before or after the operand.
Decrement Syntax: i-- or --i

46
TELEGRAM: CODINIT(click here)

Property renaming in object destructuring

Object destructuring provides a unique way to neatly


extract an object’s value into new variables.
Sometimes an object contains some properties, but
you want to access it and rename it.
When renaming a variable in object destructuring, the
left-hand side will be the original field in the object, and
the right-hand side will be the name you provide to
rename it to.
It is also possible to destructure the same property
multiple times into different variable names like in
code snippet.

47
TELEGRAM: CODINIT(click here)

Object nested destructuring

With destructuring, we can quickly extract properties


or data from objects into separate variables.
You need to give a complete path when you have to
destructure a nested property.
Destructuring an object does not modify the original
object.

48
TELEGRAM: CODINIT(click here)

Use id to find a single element

Never use the same id for multiple elements on the


same HTML page.
The getElementById() method returns an element
object.
The getElementById() method returns null if the
element does not exist.
When you want to access any element, please use
element-id if exists. Access element by id is faster than
class.

49
TELEGRAM: CODINIT(click here)

Use let instead of var for blocked statement

Scope means where these variables are available for use. The var
declarations are globally scoped or function/locally scoped.
Using var is the oldest method of variable declaration in JavaScript. A
variable declared using var is function scoped when it is declared
within a function.
A let variable is scoped to the immediate enclosing block denoted by
curly braces ({ }). You cannot access the let variable outside of its
scope. The above code snippet shows the behavior of var and let
variable.

50
TELEGRAM: CODINIT(click here)

Use of default parameters

Default function parameters allow named parameters


to be initialized with default values if no value or
undefined is passed.
ES6 provides an easier way to set the default values for
the function parameters. Use the assignment operator
(=) and the default value after the parameter name to
set a default value for that parameter.

51
TELEGRAM: CODINIT(click here)

Add dynamic property to an object

ES6 provides an easy way to create a dynamic property


in an object.
We can simply pass the property name in square
brackets ([]) which we want to make property in the
object.

52
TELEGRAM: CODINIT(click here)

Use curly brackets ({}) instead of new Object()

Objects can be initialized using new Object(),


Object.create(), or using the literal notation.
You can use curly brackets ({}) to declare objects in
JavaScript. Creating a new object this way is called
object literal notation.
The advantage of the literal notation is, that you are
able to quickly create objects with properties inside the
curly brackets ({}). You notate a list of key: value pairs
delimited by commas.
Better and clean way.

53
TELEGRAM: CODINIT(click here)

Use square brackets ([]) instead of new Array()

Arrays can be created using the new Array(), but in the


same way, they can be created using literal notation
also.
You can use square brackets ([]) to declare arrays in
JavaScript. Creating an array this way is called array
literal notation.
The advantage of the array literal notation is, that you
are able to quickly create arrays.
Better and clean way.

54
TELEGRAM: CODINIT(click here)

Declare common variables outside of the loop

Variables that are not going to reassign in the loop


must be declared outside of the loop, otherwise, they
will be created again and assigned the same value
every time.

55
TELEGRAM: CODINIT(click here)

Create an object from key-value pairs using


Object.fromEntries

The Object.fromEntries() method transforms a list of


key-value pairs into an object.
Object.fromEntries() performs the reverse of
Object.entries().

56
TELEGRAM: CODINIT(click here)

Tests every element of the array using


Array.every

The Array every() method checks whether all the array


elements pass the test implemented by the provided
function.
It returns true if the function returns true for all
elements.
It returns false if the function returns false for one
element. When every() finds a false result, it will stop
the loop and continue no more which improves the
performance.
The every() method does not change the original array.

57
TELEGRAM: CODINIT(click here)

Read property using optional chaining (?.)

The optional chaining operator (?.) is a secure way to


read nested object properties, even if an intermediate
property doesn’t exist.
The optional chaining operator (?.) stops the
evaluation if the value before ?. is nullish (undefined or
null) and returns undefined.
It prevents writing boilerplate code.
Less and clean code.

58
TELEGRAM: CODINIT(click here)

Easy way to swap two variables

Use destructuring assignment approach because it is


short and expressive. Swapping is performed in just
one line statement. It works with any data type like
numbers, strings, booleans, or objects.

59
TELEGRAM: CODINIT(click here)

Improve variable logging using console.log

In JavaScript, we use console.log() to log the variables


or messages. Sometimes it is difficult to understand
what variable corresponds to a log in the console when
too many variable logs.
To log the variable, wrap the variable into a pair of
curly brackets {variable-name}.
It will improve readability.

60
TELEGRAM: CODINIT(click here)

Mask numbers using slice and padStart

The slice() method returns selected elements in an


array, as a new array. Negative numbers select from
the end of the array.
The padStart() method pads the current string with
another string until the resulting string reaches the
given length. The padding is applied from the start of
the current string.
Masking is possible with less code.

61
TELEGRAM: CODINIT(click here)

String to a number using the plus (+) operator

The unary plus operator (+) is the fastest and preferred


way of converting something into a number.

62

You might also like