You Should Know These JavaScript Data Types, Error Handling, Coding Style & Summary Of ES6

Let’s learn some JS Data Types you’ve never heard of
  1. Data Type

A value in JavaScript is always of a certain type. For example, a string or a number. Data types basically specify what kind of data can be stored and manipulated within a program.

String Data Type
Number Data Type
Boolean Data Type

2. Primitive Values, Objects and Functions, Expressions

All types except objects define immutable values (that is, values which can’t be changed). For example (and unlike in C), Strings are immutable. We refer to the values of these types as “primitive values”.

Open your
browser’s console and print these primitive values using console.log()

When you assign a variable that stores a primitive value to another, the value stored in the variable is created and copied into the new variable.

Let’s take a look at the following example.

First, declare a variable and initialize its value to 10.

Objects and Functions​ are also values, but they are not primitive. This makes them very special. Go ahead and log a few of them to the browser console:

Notice how the browser console displays them differently from primitive
values. Some browsers might display an arrow before them, or do something
special when you click them. If you have a few different browsers installed (e.g.
Chrome and Firefox), compare how they visualize objects and functions.

Objects and functions are special because ​I can manipulate them from my
code​. For example, I can connect them to other values. This is rather vague —
so we’ll refine this idea in a later module. For now, I can say that if primitive
values are like distant stars, then objects and functions are more like rocks
floating nearby my code. They’re close enough that I can manipulate them.

And that’s the second kind of value.

You might have questions. Good. If you ask a question, the JavaScript universe
might answer it! Provided, of course, that you know how to ask.

The Function Data Type

A function is a callable object that executes a block of code. Since functions are objects, so it is possible to assign them to variables, as shown in the example below:

Expressions
There are many questions JavaScript can’t answer. If you want to know
whether it’s better to confess you're true feelings to your best friend or to keep
waiting until you both turn into skeletons, JavaScript won’t be of much help.

But there are some questions that JavaScript would be ​delighted​ to answer.
These questions have a special name — they are called ​expressions​.

If we “ask” the expression 2 + 2, JavaScript will “answer” with the value 4.

3.Types Of Values

As an aspiring astronomer, you might want to know about ​every​ type of value
that can be observed in the JavaScript sky. After almost twenty-five years of
studying JavaScript, scientists have only discovered nine such types:

Primitive Values

Undefined​ (undefined), used for unintentionally missing values.
Null​ (null), used for intentionally missing values.
Booleans​ (true and false), used for logical operations.
Numbers​ (-100, 3.14, and others), used for math calculations.
Strings​ (“hello”, “abracadabra”, and others), used for text.
Symbols​ (uncommon), used to hide implementation details.
BigInts​ (uncommon and new), used for math on big numbers.

Objects and Functions

Objects​ ({} and others), used to group related data and code.
Functions​ (x => x * 2 and others), used to refer to code.

4. Error Handling

Sometimes your JavaScript code does not run as smoothly as expected, resulting in an error. Several reasons may cause errors, for instance:

  • A problem with network connection
  • A user might have entered an invalid value in a form field
  • Referencing objects or functions that do not exist
  • Incorrect data is sent to or received from the webserver
  • A service that the application needs to access might be temporarily unavailable

The try…catch Statement

JavaScript provides the try-catch statement to trap the runtime errors, and handle them gracefully.

Any code that might throw an error should be placed in the try block of the statement and the code to handle the error is placed in the catch block, as shown here:

Throwing Errors

So far we’ve seen the errors that are automatically thrown by the JavaScript parser when an error occurs. However, it is also possible to throw an error manually by using the throw statement.

try…catch…finally Statement

You can also use the try...catch...finally statement to handle exceptions. The finally block executes both when the code runs successfully or if an error occurs. The syntax of try...catch...finally the block is:

try…catch in setTimeout

The try...catch won't catch the exception if it happened in "timed" code, like in setTimeout(). For example,

try {
setTimeout(function() {
// error in the code
}, 3000);
} catch (e) {
console.log( "won't work" );
}

5. Comments

As we know from the chapter Code structure, comments can be single-line: starting with // and multiline: /* ... */. We normally use them to describe how and why the code works. At first, sight, commenting might be obvious, but novices in programming often use them wrongly.

6. Coding Style

Our code must be as clean and easy to read as possible. That is actually the art of programming — to take a complex task and code it in a way that is both correct and human-readable. A good code style greatly assists in that.

coding conventions are style guidelines for programming. They typically cover:

  • Naming and declaration rules for variables and functions.
  • Rules for the use of white space, indentation, and comments.
  • Programming practices and principles

Coding conventions secure quality:

  • Improves code readability
  • Make code maintenance easier

7. ES6

ECMAScript 2015 or ES2015 is a significant update to JavaScript programming language. It is the first major update to the language since ES5 which was standardized in 2009. Therefore, ES2015 is often called ES6.

ES6 syntax

ES6 Var Declarations & Hoisting

Before ES6, the var keyword was used to declare a variable in JavaScript. Variables declared using var do not support block-level scope. This means if a variable is declared in a loop or if the block it can be accessed outside the loop or the if block. This is because the variables declared using the var keyword support hoisting.

var and hoisting

Variable hoisting allows the use of a variable in a JavaScript program, even before it is declared. Such variables will be initialized to undefined by default. JavaScript runtime will scan for variable declarations and put them to the top of the function or script. Variables declared with var keyword get hoisted to the top. Consider the following example −

8. Block-Level Declarations, Block Binding in Loops & Global Block Bindings

Block-level declarations are the ones that declare variables that are far outside of the given block scope. Block scopes, also known as lexical scopes, are created either inside of a function or inside of a block (indicated by the { and } characters). Block scoping is how many C-based languages work, and the introduction of block-level declarations in ECMAScript 6 is intended to bring that same flexibility (and uniformity) to JavaScript.

Here below is the screenshot that shows the difference between var and let (Check the comments within the code block).

Let Declaration

The let declaration syntax is the same as var. You can replace var with let to declare a variable, this will limit the variable’s scope to only that current code block. Since let declarations are not hoisted to the top of the enclosing block, you may want always to place let declarations first in the block, so that they are available to the entire block.

Many developers never realized that for-loop declarations were one of the areas that required block-level variable declarations the most. Take the following for example:

Functions in Loops

The characteristics of var have long made creating functions inside of loops problematic, because the loop variables are accessible from outside the scope of the loop. Consider the following code:

var funcs = [];for (var i=0; i < 10; i++) {
funcs.push(function() { console.log(i); });
}
funcs.forEach(function(func) {
func(); // outputs the number "10" ten times
});

Let Declarations in Loops

A let declaration simplifies loops by effectively mimicking what the IIFE does in the previous example. On each iteration, the loop creates a new variable and initializes it to the value of the variable with the same name from the previous iteration. That means you can omit the IIFE altogether and get the results you expect, like this:

var funcs = [];for (let i=0; i < 10; i++) {
funcs.push(function() {
console.log(i);
});
}
funcs.forEach(function(func) {
func(); // outputs 0, then 1, then 2, up to 9
})

Global Block Bindings

Another way in which let and const are different from var is in their global scope behavior. When var is used in the global scope, it creates a new global variable, which is a property on the global object (window in browsers). That means you can accidentally overwrite an existing global using, such as:

// in a browser
var RegExp = "Hello!";
console.log(window.RegExp); // "Hello!"
var ncz = "Hi!";
console.log(window.ncz); // "Hi!"

9. Functions with Default Parameter Values, Working with Unnamed Parameters

Let’s freshen up our knowledge quickly and take a look at the syntax again. Default parameters allow us to initialize functions with default values. Default is used when an argument is either omitted or undefined — meaning null is a valid value. A default parameter can be anything from a number to another function.

Arguments and parameters are often referred to interchangeably. Nevertheless, for this tutorial, we will make a distinction. In most standards, parameters (or formal parameters) are what’s given in the function declaration, and arguments (or actual parameters) are what’s passed to the function. Consider this function:

function foo(param1, param2) {
// do something
}
foo(10, 20);

10. The Spread Operator, Block-Level Functions, Arrow Functions

In ECMAScript 5, the apply() a method is a convenient tool for passing an array as arguments to a function. For example, it’s commonly used with the Math.max() method to find the highest value in an array. Consider this code fragment:

var myArray = [5, 10, 50];
Math.max(myArray); // Error: NaN
Math.max.apply(Math, myArray); // 50

The Math.max() the method doesn’t support arrays; it accepts only numbers. When an array is passed to the Math.max() function, it throws an error. But when the apply() method is used, the array is sent as individual numbers, so the Math.max() method can handle it.

Spreading elements on function calls

let fruits = [‘Apple’,’Orange’,’Banana’];

var getFruits = (f1, f2, f3) => {
console.log(Fruits: ${f1}, ${f2} and ${f3}); };

getFruits(…fruits); // Fruits: Apple, Orange and Banana

Spread syntax for object literals

var obj1 = { id: 101, name: ‘Jhon Doe’ }

var obj2 = { age: 25, country: ‘USA’}

const employee = { …obj1, …obj2 }

console.log(employee); //{ “id”: 101, “name”: “Jhon Doe”, “age”: 25, “country”: “USA” }

Block-Level Functions

I was preparing code samples for my ECMAScript 6 (ES6) workshop. ES6 has tons of new language features and programming in the next version of JavaScript is a lot of fun. In particular, ES6 supports block-level functions, so the following code should produce the error “doSomething is not defined”.

Arrow Functions

There are a variety of syntaxes available in arrow functions. We’ll cover the common ones here to get you started. Let’s compare how ES5 code with function expressions can now be written in ES6 using arrow functions.

Conclusion

We have now learned the JavaScript Data Types, Error Handling, Coding Style & Summary Of ES6 of what we can accomplish. If you feel inspired to build on these examples. Cheers!

I’m A Professional React Js Web Developer & Cyber Security Specialist that will assist me in developing, improving, and obtaining the necessary skills.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store