Functions in JavaScript are objects

Functions in JavaScript are objects.

How to know in the browser?

Navigate to the console of the browser near you and type this simple function Person shown below and hit enter. Next, type Person followed by dot (.) see the methods on Person function. Pretty simple.

Thus the function is an object and has the methods as other objects in JavaScript.

We can call functions on function. Let’s invoke call function and see the output.

Invoking call method on function Person.

Prototype object:

Objects are keyed collection/associative array that has a hidden link to the prototype object. Try the following code in any browser console and understand it.

Object and prototype object has a linking.

We can access the prototype object using Object.prototype.

We can get an original object back from the prototype object using constructor (Object.prototype.constructor) property.

Pictorial representation of Object and it’s prototype object.

Oh, wait! We were talking about Function.

Like Object, Function is linked to Function.prototype.

Let me show you using Person function, it’s prototype object and their linking in the browser console.

Pictorial representation of Person function and it’s prototype object.

Computer program

computer program is a collection of instructions that performs a specific task when executed by a computer


From the program in its human-readable form of source code, a compiler or assembler can derive machine code—a form consisting of instructions that the computer can directly execute.

Alternatively, a computer program may be executed with the aid of an interpreter.

A collection of computer programs, libraries, and related data are referred to as software. Computer programs may be categorized along functional lines, such as application software and system software. The underlying method used for some calculation or manipulation is known as an algorithm.


Computer programming is the process of writing or editing source code. Editing source code involves testing, analyzing, refining, and sometimes coordinating with other programmers on a jointly developed program. A person who practices this skill is referred to as a computer programmer, software developer, and sometimes coder.

The sometimes lengthy process of computer programming is usually referred to as software development. The term software engineering is becoming popular as the process is seen as an engineering discipline.

A computer program in the form of a human-readable, computer programming language is called source code. Source code may be converted into an executable image by a compiler or assembler, or executed immediately with the aid of an interpreter.

Compilers are used to translate source code from a programming language into either object code or machine code.[22] Object code needs further processing to become machine code, and machine code consists of the central processing unit’s native instructions, ready for execution. Compiled computer programs are commonly referred to as executables, binary images, or simply as binaries – a reference to the binaryfile format used to store the executable code.

Some compiled and assembled object programs need to be combined as modules with a linker utility in order to produce an executable program.

Interpreters are used to execute source code from a programming language line-by-line. The interpreter decodes each statement and performs its behavior. One advantage of interpreters is that they can easily be extended to an interactive session. The programmer is presented with a prompt, and individual lines of code are typed in and performed immediately.

The main disadvantage of interpreters is computer programs run slower than when compiled. Interpreting code is slower because the interpreter must decode each statement and then perform it. However, software development may be faster using an interpreter because testing is immediate when the compiling step is omitted. Another disadvantage of interpreters is an interpreter must be present on the executing computer. By contrast, compiled computer programs need no compiler present during execution.

Just in time compilers pre-compile computer programs just before execution. For example, the Java virtual machine Hotspot contains a Just In Time Compiler which selectively compiles Java bytecode into machine code – but only code which Hotspot predicts is likely to be used many times.

Avoid complex conditionals using the ternary operator

?: is a ternary operator introduced to write elegant if-else clause.

It is a concise way of writing simple conditionals. However, those should be easily understandable by any human. It should not be used to write deeply nested complex conditionals that hamper the readability.


When to use?

When you have very simple if-else that could be covered in one line and returns value.


Example:

Display text as “Weekend” if it’s a Sunday otherwise “Working day”

Another one:

Determine the restaurant to visit depending upon cash in your wallet.

When NOT to use?

As said earlier, they are used to simplify the conditional so that they add value and make code simple and elegant.

However, that does not mean you should blindly rewrite ALL if-else clause with the ternary operator. Please avoid them when expression becomes complex and difficult to understand.


Bad Example

The implementation of the fizz buzz generator.



const output = number % 3 === 0 && number % 5 === 0 ? "FizzBuzz"
 : number % 3 === 0 ? "Fizz" 
 : number % 5  === 0 ? "Buzz" 
 : number;

In my career, I have seen people writing deeply nested clauses using the ternary operator. I kept the above example to convey my thoughts.

The above snippet adds unnecessary mental mapping to remember and process each conditional and symbols ?: ?: ?: more like a machine.

Please don’t be a human code compressor.

Better alternative

Conventional if-else over ternary when a condition becomes complex.

Day by day, high-level languages are introducing more features so that developers could write more human-readable expressive code. We should keep this point in our mind and avoid a few things like writing deeply nested complex ternary conditionals. Instead, go for conventional control flow statements like if-else or if-return-early.

Thoughts mentioned in this post are based on my personal experience. It is just a guideline. IMO, we should be compassionate about our co-worker while writing the code and should avoid clever-complex clauses using ternary operators and rather should focus on elegance.

Primitive Obsession – The code smell

https://www.collinsdictionary.com/dictionary/english/primitive

Programming languages divide their types mainly into two categories.

  • Primitive types (A built-in types like string, boolean, int, decimal…)
  • Objects (class/function): User-defined types using class-based/prototype-based objects.

A primitive data type is a data type for which the programming language provides built-in support. Example: number, string, boolean, date and so on.

There are situations when developers should represent their idea/concept using user-defined types (Abstraction or encapsulation).

Whereas they choose to use primitive types (inbuilt int, string…) to represents the concept.

“Talk is cheap. Show me the code.” ― Linus Torvalds

Consider the above API for scheduling meetup.

If you observe carefully, all the parameters: topic, description, date, location id, and max participants when they stand together represent the concept/idea called meetup.

Almost all the data types are primitive types (Built-in types: string, int, DateTime and so on).

Problem?

Overutilization of these primitive types to solve a problem makes the code more verbose/procedural and logic to deal with them is scattered.

Solution:

Since all method parameter stands together to represent the concept called Meetup.

Here, we could group all these parameters together to represent the idea/concept called meetup. So, introduce an object to gather these data values.

Upon replacing data values with an object API would look like:

This is how the API should have been. However, the developer chooses to go with all built-in types (segregated). IMO, this overutilization of primitive types in almost all cases can be treated as an obsession about primitives which can be called a primitive obsession.

I have explained only one scenario and there are other scenarios too.

Test case structure

A commonly applied structure for test cases has

  • Setup: Arrange the state of the unit under test in order to run the test.
  • Execution: Act on the unit under test so that it performs the expected behavior and receive output if needed.
  • Validation: Assert/Verify the outcome of execution.
  • Cleanup: Restore unit under test to a pre-test state.

Test-driven development benefits

  • Design first: You understand requirement first via analysis, create use cases for it. Thus, the focus is on the requirement before writing the code.
  • Good enough code for now: You write sufficient code against use cases that fulfills the user requirements. You don’t write extra lines of unnecessary code.
  • Avoid rework: Due to design first approach, most of the doubts are cleared before writing code hence rework is avoided.
  • Developer confidence: Continous delivery of requirement in small cycles gives developer a confidence.
  • Regression catching.
  • Safe Refactoring: Once the code is covered by multiple tests, a developer can safely improve code structure with confidence and can focus on simple and elegant design.
  • A shared understanding of the business: Tests are the live documentation that is the communication channel between you and your future version or other developers that talks about business rules.
  • Clean code reminder: IMO, TDD always reminds you to make your code better than you found it. Of course, after covering your code with test, make it better.

Rest parameter under the hood…

You know the rest parameter (usually prefixed with ...) allows functions or methods to accept indefinite numbers of parameters.

This parameter is actually gathering the values from arguments and creates an array of values from it.

How? Let’s see with code using ES6 rest parameter and it’s corresponding transpiled version.


Simple snippet with rest parameter

First snippet: The function with Rest parameter ‘…days’

Obviously, line 2 will print an array:

[ 'Monday', 'Tuesday', 'Wednesday' ].

You wonder, How it’s an array? Let’s inspect it via transpiled version.

Below code is transpiled using BABEL.


Transpiled version:

Transpiled version of first code snippet. The days variable is initialised as an array and copies element from argument object.

Under the hood, the rest parameters are actually derived from arguments object of called function, `print`. Please notice carefully variable days on line# 5.

It’s value is set to an array whose length is equal to number of arguments passed.

Later, elements from arguments are copied to variable days (element by element from line# 8 to 10).


Another Example

Second snippet

In the second code snippet, please note there is a parameter multiplier apart from rest parameter ...numbers. Hence, copying will not begin from first element instead it started from second element till last one.

See transpiled version for more details.


Transpiled version

Transpiled version of second snippet. Please note argument objects first element is skipped.

const does not mean value it holds is immutable

I see many JavaScript developers have started replacing var with const just because some linter forces them to do so.

const in JavaScript is not only blocked scope but also const variable cannot be reassigned with new content.

It creates readonly reference. It means you cannot reassign value to the const variable. It does not guarantees immutability of the content that it holds.


const person = { name: 'John Doe', age: 33};
person = { name: 'John'} 
// Above line will throw Uncaught TypeError: 
// Assignment to constant variable.

// However, you can change the content of object
// that is referenced by person variable.
person.age = 40;  

So, If you really want to mark your object as immutable then use some other API’s like `Object.freeze`.

There are specific use cases about const variable. Make sure you are intentionally marking some variable as const and not because some linter has that rule.