1578919943
These practices are what makes our code cleaner, readable, more comprehensible and simpler.
Sometimes, the code you write is perfectly valid, usable and somewhat readable, but you might be going the long way around addressing problem. Maybe that’s because you haven’t made an effort to start using newer syntax, or that you’re stuck in how you work and your thought processes.
It might be time to change your habits by creating new ones; replacing them with shorthand alternatives for solving the same problem. It will involve asking yourself questions constantly until you are used to the new approach.
The shorthand expressions that will be discussed have their limitations. They are not always the right option, as with any tool. However, they are valid language features & syntax.
You may have strong feelings towards some of the code used. If so I would like to hear them!
Let’s start with a simple one…
Use ‘truthy’ to its full potential
Instead of using a complex if
condition to check whether a value is truthy, you can just simply use the variable itself as the condition. You need to know the logic behind a truthy value however.
false
, 0
, 0n
, ""
, null
, undefined
, and NaN
.Before
if (condition !== undefined && condition !== null) {
// handle truthy condition
}
After
if (condition) {
// handle truthy condition
}
Stop using so many if-else statements
Ternary Operators are frequently used as a shortcut to an if statement. It is simply asking a question (the condition), with which you execute some code if the answer is yes (truthy) or no (falsy).
Therefore, there are three parts to the statement: the condition to evaluate, the truthy expression, and the falsy expression.
condition ? exprIfTrue : exprIfFalse
Before
if (num > 5) {
return 'number is above 5';
} else {
return 'number is not above 5';
}
After
return num > 5 ? 'number is above 5' : 'number is not above 5';
When ternary operators get messy
Ternary operators are recommended for a single expression. You can use them to execute code based on the condition: condition ? executeThis() : executeOther()
or assign to variables const num = condition ? 3 : 5;
.
It gets messy when you introduce multiple ternary operators together into a single expression. For example…
((typeof val === 'string' ? runStringFunction() : false) ? runFunctionWhenStringFuncTrue() ? 'ok' : 'might be ok') : 'exited early so not ok'
The logic might not be clear at first glance, but you want it to be! For your future self and your peers.
When intent starts to become unclear, you should break them up into single statements or use an if-else statement.
if (typeof val === 'string') {
if (runStringFunction()) {
if (runFunctionWhenStringFuncTrue()) {
return 'ok';
}
return 'might be ok';
}
}
return 'exited early so not ok';
Bonus (omit the ‘else’)
As you can see from above if-else, you can omit the else if you return
within the if
statement. The return
would cause the function to return early, making the else
redundant (therefore you don’t need it for the logic to work as intended).
(Do you really need an if-else for variable assignment)
Short-Circuit Evaluation is a condition where the logical operator used, in addition to the precedence, dictates whether the statement should take the return value early (short circuit). It allows you to prevent unnecessary execution of code.
(some falsy expression) && _expr_
is short-circuit evaluated to the falsy expression;(some truthy expression) || _expr_
is short-circuit evaluated to the truthy expression.Before
let value; // we want to assign 'other' to 'value' if it is not null or undefined
if (other !== undefined && other !== null) {
value = other;
return value;
}
value = 'other was falsy';
return value;
After
const other = '';
value = other || 'other was falsy'; // will return 'other was falsy'
Bonus: Non-Boolean values
Short circuit evaluation, when used with non-boolean values, can return non boolean values.
const other = '';
const value = other || 'other falsy'; // returns 'other falsy'
other = 'Im truthy now';
value = other && ''; // returns 'Im falsy now'
However be careful with introducing complexity. You begin to sacrifice the benefits of short circuit evaluation when you introduce multiple logical operators. It’s a breeding ground for irritatingly simple (but easy to miss) bugs.
This is due to operator precedence. It is important to note that the &&
will be evaluated first due to precedence, unless you wrap the separate logical operator conditions in parenthesis.
true || false && false // returns true, because '&&' is executed first
(true || false) && false // returns false, due to no precedence
An arrow function expression is a syntactically compact alternative to a regular function. It does not have it’s own bindings to this
, arguments
, super
or new.target
.
Using an arrow function makes our code more concise, simplifies scoping and this
.
Before
const func = function() {
// do something
}
After
const func = () => { return 'something'; }
func();
// OR
const func = () => 'something';
// OR WITH PARAM (SINGLE)
func();
const func = arg => {
console.log(arg);
}
func('hello');
// OR WITH MULTI PARAMS
const func = (arg, arg1) => {
console.log('arg: ', arg);
console.log('arg1: ', arg1);
};
func('hello', 'there');
Use the forEach
Array Prototype method
It allows you to iterate over elements an operate on them one at a time. The operation on each element is provided through the callback parameter. It looks cleaner and is easier to infer intent.
Before
const array = ['1', '2', '3'];
for (const val of array) {
}
// or
for (let i = 0; i < array.length; i++) {
}
After
const array = ['1', '2', '3'];
array.forEach(val => {
// do something
})
However, one drawback is that you cannot terminate a **forEach**
execution early, as you can with regular for..of
statements. If you require the possibility for early termination, then this isn’t the correct tool.
There may be a difference in performance of the
forEach()
compared to other for loops. Tests have shown that[forEach](https://github.com/dg92/Performance-Analysis-JS)
is significantly slower, however for simple tasks there should be no real performance concern.
The spread operator allows an iterable to be expanded where there are zero or more arguments, such as elements in an array or key-value pairs for objects.
Before
const array1 = [0, 1, 2, 3, 4];
const array2 = [5, 6, 7, 8, 9];
function(array1, array2) {
for (const value of array2) {
array1.push(value);
}
}
After
const array = [0, 1, 2, 3, 4];
const other = [5, 6, 7, 8, 9];
function(array1, array2) {
return [ ...array1, ...array2 ];
}
The rest operator allows an indefinite number of arguments, represented as an array.
Before
function add(x, y, z?) {
return x + y + (z || 0);
}
add(1, 2, 3)
After
function add(...nums) {
return sum(...nums);
}
add(1, 2, 3, 4, 5);
add(1, 3);
add(4, 5, 3, 4);
When assigning values to objects, sometimes you want to check whether they are truthy (have been defined and are not null etc).
If they are falsy you might want to fallback to default values. You can achieve this with the spread operator. The second spread has the ability to overwrite object values that have already been defined, otherwise the defaultValues
are kept.
Therefore, the default values are used as the first spread so that the second spread overwrites the first.
Before
function handleParams(params?: any) {
const finalParams = {
one: params && params.one ? params.one,
two: params && params.two? params.two,
three: params && params.three ? params.three
};
// do something with the params
}
After
const defaultValues = {
one: 'oneDefault',
two: 'twoDefault'
three: 'threeDefault'
};
function handleParams(params?: any) {
const finalParams = { ...defaultValues, ...params };
// do something with the params
return finalParams;
}
handleParams({one: 'oneNew', three: 'threeNew'});
// will return {one: 'oneNew', two: 'twoDefault', three: 'threeNew'}
This is just a simple replacement for a for loop iterating over each index of an iterable. Using a while
loop with a decrementing value val--
will count down to zero (which itself is falsy) to end the loop.
It looks cleaner (to me) and easy to understand what you are iterating over at first glance.
Before
for (let i; i < array.length; i++) {
// do something
}
After
const length = array.length;
while(length--) {
// do something
}
Checking if a value is in an Array
The bitwise NOT operator can be used with an indexOf
statement to check whether a value exists in an Array
or String
.
Where we would normally check whether the return value from the indexOf
operation was more than -1
, the tilde ~
will return true if indexOf
returns 0 or higher.
The logic behind the bitwise NOT is
~n == -(n+1)
.
Before
const array = [0, 1, 2, 3, 4];
if (array.indexOf(5) > -1) {
return 'exists';
} else {
return 'does not exist';
}
After
const array = [0, 1, 2, 3, 4];
if (~array.indexOf(4)) // true
This simpler syntax can also be achieved with Array.prototype.find
and Array.prototype.includes
.
if (array.includes(3)) // true
if (array.find(val => val === 2)) // true
We would use an IIFE
(Immediately-Invoked Function Expression) when there is code which we want to be executed immediately on parsing by the browser, and/or if we do not want to pollute the namespace with conflicting variables. It essentially introduces another scope.
It is useful if you need to execute a function immediately after declaring it. It combines the declaration + execution in one concise expression.
Before
function random() {
// do something
}
random()
After
!function() {
}()
(function() {})()
You can use any unary operator in place of !
to self-execute a function.
~function(){}()
+function(){}()
You may also like: Keeping your JavaScript code clean forever and scalable.
These shorthand expressions are intended to make code simpler and cleaner.
Therefore, it is counter-productive and defeats the original purpose to use multiple shorthand expressions together.
Thank you for reading!
#javascript #cleanercode #JavaScript code #tutorial
1603857900
According to an analysis, a developer creates 70 bugs per 1000 lines of code on average. As a result, he spends 75% of his time on debugging. So sad!
Bugs are born in many ways. Creating side effects is one of them.
Some people say side effects are evil, some say they’re not.
I’m in the first group. Side effects should be considered evil. And we should aim for side effects free code.
Here are 4ways you can use to achieve the goal.
Just add use strict; to the beginning of your files. This special string will turn your code validation on and prevent you from using variables without declaring them first.
#functional-programming #javascript-tips #clean-code #coding #javascript-development #javascript
1622207074
Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.
JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.
JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.
Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.
In JavaScript, ‘document.write‘ is used to represent a string on a browser.
<script type="text/javascript">
document.write("Hello World!");
</script>
<script type="text/javascript">
//single line comment
/* document.write("Hello"); */
</script>
#javascript #javascript code #javascript hello world #what is javascript #who invented javascript
1578919943
These practices are what makes our code cleaner, readable, more comprehensible and simpler.
Sometimes, the code you write is perfectly valid, usable and somewhat readable, but you might be going the long way around addressing problem. Maybe that’s because you haven’t made an effort to start using newer syntax, or that you’re stuck in how you work and your thought processes.
It might be time to change your habits by creating new ones; replacing them with shorthand alternatives for solving the same problem. It will involve asking yourself questions constantly until you are used to the new approach.
The shorthand expressions that will be discussed have their limitations. They are not always the right option, as with any tool. However, they are valid language features & syntax.
You may have strong feelings towards some of the code used. If so I would like to hear them!
Let’s start with a simple one…
Use ‘truthy’ to its full potential
Instead of using a complex if
condition to check whether a value is truthy, you can just simply use the variable itself as the condition. You need to know the logic behind a truthy value however.
false
, 0
, 0n
, ""
, null
, undefined
, and NaN
.Before
if (condition !== undefined && condition !== null) {
// handle truthy condition
}
After
if (condition) {
// handle truthy condition
}
Stop using so many if-else statements
Ternary Operators are frequently used as a shortcut to an if statement. It is simply asking a question (the condition), with which you execute some code if the answer is yes (truthy) or no (falsy).
Therefore, there are three parts to the statement: the condition to evaluate, the truthy expression, and the falsy expression.
condition ? exprIfTrue : exprIfFalse
Before
if (num > 5) {
return 'number is above 5';
} else {
return 'number is not above 5';
}
After
return num > 5 ? 'number is above 5' : 'number is not above 5';
When ternary operators get messy
Ternary operators are recommended for a single expression. You can use them to execute code based on the condition: condition ? executeThis() : executeOther()
or assign to variables const num = condition ? 3 : 5;
.
It gets messy when you introduce multiple ternary operators together into a single expression. For example…
((typeof val === 'string' ? runStringFunction() : false) ? runFunctionWhenStringFuncTrue() ? 'ok' : 'might be ok') : 'exited early so not ok'
The logic might not be clear at first glance, but you want it to be! For your future self and your peers.
When intent starts to become unclear, you should break them up into single statements or use an if-else statement.
if (typeof val === 'string') {
if (runStringFunction()) {
if (runFunctionWhenStringFuncTrue()) {
return 'ok';
}
return 'might be ok';
}
}
return 'exited early so not ok';
Bonus (omit the ‘else’)
As you can see from above if-else, you can omit the else if you return
within the if
statement. The return
would cause the function to return early, making the else
redundant (therefore you don’t need it for the logic to work as intended).
(Do you really need an if-else for variable assignment)
Short-Circuit Evaluation is a condition where the logical operator used, in addition to the precedence, dictates whether the statement should take the return value early (short circuit). It allows you to prevent unnecessary execution of code.
(some falsy expression) && _expr_
is short-circuit evaluated to the falsy expression;(some truthy expression) || _expr_
is short-circuit evaluated to the truthy expression.Before
let value; // we want to assign 'other' to 'value' if it is not null or undefined
if (other !== undefined && other !== null) {
value = other;
return value;
}
value = 'other was falsy';
return value;
After
const other = '';
value = other || 'other was falsy'; // will return 'other was falsy'
Bonus: Non-Boolean values
Short circuit evaluation, when used with non-boolean values, can return non boolean values.
const other = '';
const value = other || 'other falsy'; // returns 'other falsy'
other = 'Im truthy now';
value = other && ''; // returns 'Im falsy now'
However be careful with introducing complexity. You begin to sacrifice the benefits of short circuit evaluation when you introduce multiple logical operators. It’s a breeding ground for irritatingly simple (but easy to miss) bugs.
This is due to operator precedence. It is important to note that the &&
will be evaluated first due to precedence, unless you wrap the separate logical operator conditions in parenthesis.
true || false && false // returns true, because '&&' is executed first
(true || false) && false // returns false, due to no precedence
An arrow function expression is a syntactically compact alternative to a regular function. It does not have it’s own bindings to this
, arguments
, super
or new.target
.
Using an arrow function makes our code more concise, simplifies scoping and this
.
Before
const func = function() {
// do something
}
After
const func = () => { return 'something'; }
func();
// OR
const func = () => 'something';
// OR WITH PARAM (SINGLE)
func();
const func = arg => {
console.log(arg);
}
func('hello');
// OR WITH MULTI PARAMS
const func = (arg, arg1) => {
console.log('arg: ', arg);
console.log('arg1: ', arg1);
};
func('hello', 'there');
Use the forEach
Array Prototype method
It allows you to iterate over elements an operate on them one at a time. The operation on each element is provided through the callback parameter. It looks cleaner and is easier to infer intent.
Before
const array = ['1', '2', '3'];
for (const val of array) {
}
// or
for (let i = 0; i < array.length; i++) {
}
After
const array = ['1', '2', '3'];
array.forEach(val => {
// do something
})
However, one drawback is that you cannot terminate a **forEach**
execution early, as you can with regular for..of
statements. If you require the possibility for early termination, then this isn’t the correct tool.
There may be a difference in performance of the
forEach()
compared to other for loops. Tests have shown that[forEach](https://github.com/dg92/Performance-Analysis-JS)
is significantly slower, however for simple tasks there should be no real performance concern.
The spread operator allows an iterable to be expanded where there are zero or more arguments, such as elements in an array or key-value pairs for objects.
Before
const array1 = [0, 1, 2, 3, 4];
const array2 = [5, 6, 7, 8, 9];
function(array1, array2) {
for (const value of array2) {
array1.push(value);
}
}
After
const array = [0, 1, 2, 3, 4];
const other = [5, 6, 7, 8, 9];
function(array1, array2) {
return [ ...array1, ...array2 ];
}
The rest operator allows an indefinite number of arguments, represented as an array.
Before
function add(x, y, z?) {
return x + y + (z || 0);
}
add(1, 2, 3)
After
function add(...nums) {
return sum(...nums);
}
add(1, 2, 3, 4, 5);
add(1, 3);
add(4, 5, 3, 4);
When assigning values to objects, sometimes you want to check whether they are truthy (have been defined and are not null etc).
If they are falsy you might want to fallback to default values. You can achieve this with the spread operator. The second spread has the ability to overwrite object values that have already been defined, otherwise the defaultValues
are kept.
Therefore, the default values are used as the first spread so that the second spread overwrites the first.
Before
function handleParams(params?: any) {
const finalParams = {
one: params && params.one ? params.one,
two: params && params.two? params.two,
three: params && params.three ? params.three
};
// do something with the params
}
After
const defaultValues = {
one: 'oneDefault',
two: 'twoDefault'
three: 'threeDefault'
};
function handleParams(params?: any) {
const finalParams = { ...defaultValues, ...params };
// do something with the params
return finalParams;
}
handleParams({one: 'oneNew', three: 'threeNew'});
// will return {one: 'oneNew', two: 'twoDefault', three: 'threeNew'}
This is just a simple replacement for a for loop iterating over each index of an iterable. Using a while
loop with a decrementing value val--
will count down to zero (which itself is falsy) to end the loop.
It looks cleaner (to me) and easy to understand what you are iterating over at first glance.
Before
for (let i; i < array.length; i++) {
// do something
}
After
const length = array.length;
while(length--) {
// do something
}
Checking if a value is in an Array
The bitwise NOT operator can be used with an indexOf
statement to check whether a value exists in an Array
or String
.
Where we would normally check whether the return value from the indexOf
operation was more than -1
, the tilde ~
will return true if indexOf
returns 0 or higher.
The logic behind the bitwise NOT is
~n == -(n+1)
.
Before
const array = [0, 1, 2, 3, 4];
if (array.indexOf(5) > -1) {
return 'exists';
} else {
return 'does not exist';
}
After
const array = [0, 1, 2, 3, 4];
if (~array.indexOf(4)) // true
This simpler syntax can also be achieved with Array.prototype.find
and Array.prototype.includes
.
if (array.includes(3)) // true
if (array.find(val => val === 2)) // true
We would use an IIFE
(Immediately-Invoked Function Expression) when there is code which we want to be executed immediately on parsing by the browser, and/or if we do not want to pollute the namespace with conflicting variables. It essentially introduces another scope.
It is useful if you need to execute a function immediately after declaring it. It combines the declaration + execution in one concise expression.
Before
function random() {
// do something
}
random()
After
!function() {
}()
(function() {})()
You can use any unary operator in place of !
to self-execute a function.
~function(){}()
+function(){}()
You may also like: Keeping your JavaScript code clean forever and scalable.
These shorthand expressions are intended to make code simpler and cleaner.
Therefore, it is counter-productive and defeats the original purpose to use multiple shorthand expressions together.
Thank you for reading!
#javascript #cleanercode #JavaScript code #tutorial
1604008800
Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.
Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.
“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”
We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.
We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.
Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast
module, and wide adoption of the language itself.
Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:
As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:
The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.
A token might consist of either a single character, like (
, or literals (like integers, strings, e.g., 7
, Bob
, etc.), or reserved keywords of that language (e.g, def
in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.
Python provides the tokenize
module in its standard library to let you play around with tokens:
Python
1
import io
2
import tokenize
3
4
code = b"color = input('Enter your favourite color: ')"
5
6
for token in tokenize.tokenize(io.BytesIO(code).readline):
7
print(token)
Python
1
TokenInfo(type=62 (ENCODING), string='utf-8')
2
TokenInfo(type=1 (NAME), string='color')
3
TokenInfo(type=54 (OP), string='=')
4
TokenInfo(type=1 (NAME), string='input')
5
TokenInfo(type=54 (OP), string='(')
6
TokenInfo(type=3 (STRING), string="'Enter your favourite color: '")
7
TokenInfo(type=54 (OP), string=')')
8
TokenInfo(type=4 (NEWLINE), string='')
9
TokenInfo(type=0 (ENDMARKER), string='')
(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)
#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer
1602819699
Who else loves to write side-effects-free functions?
I think we, as programmers, all do.
Today, in this story, I will walk you through the basic principles of functional programming that will make your coding life easier.
Let’s get into it.
When it comes to pure functions, you need to remember only two things:
Let’s look at the simple example below:
const DISCOUNT = 0.5;
const calculatePrice = price => price * DISCOUNT;
let actualPrice = calculatePrice(15); // 7.5
Is the function **calculatePrice **pure? No, it’s not.
Why? Because the global variable DISCOUNT is not passed to the function as an argument. If you change the DISCOUNT’s value, the returning result will also change, although the argument price stays the same.
To make it pure function, you have to add one more parameter to the function like this:
const DISCOUNT = 0.5;
const calculatePrice = (price, discount) => price * discount;
let actualPrice = calculatePrice(15, DISCOUNT); // 7.5
#javascript-tips #javascript-development #coding #javascript #functional-programming