JavaScript -something we need to know
Data Types, Error handling, Coding Style, Caching, Cross Browser, Hoisting, Block level, Default parameter, Spread operator, Arrow function

Data Types in Javascript
What are data types? Data types specify what kind of data can be stored or manipulated within a program.
The latest ECMAScript standard defines nine types.
In a short, there are mainly six basic data types in Javascript, which we can divide into three main categories: 1. primitive(or primary) 2. composite(or reference), and 3. special data types.
Primitive data types:
String, Number, and Boolean are primitive data types.
Composite data types:
Object, Array, and Function are composite data types.
Special data types:
Undefined and Null are special data types.
Expressions
An expression is a combination of values, variables, and operators, which computes a value.
The computation is called an evaluation. Expressions always result in a single value.
For example,
5 * 2 //this is an expression
x * 2 //this is an expression
"Apple" + " " + "Mango" //this is an expression
Hoisting
Moving declarations to the top is Javascript’s default behavior, and we called it hoisting.
Declarations are hoisted but initializations are not hoisted.
A simple code:
var x; // Declare x
x = 5; // Assign 5 to x
console.log(x);Output:
5
In javascript, a variable can be used before it has been declared.
x = 5; // Assign 5 to x
console.log(x);
var x; // Declare xOuput:
5
In the last code, the variable declaration has been hoisted to the top of the script automatically.
Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).
In Javascript, Initializations are Not Hoisted:
JavaScript only hoists declarations, not initializations.
var x; //Declare x
console.log(x);
x = 5; //assign 5 to xOutput:
undefined
In the upper example, we can see that in javascript only declarations are hoisted but the initializations are not hoisted.
So we cannot use variables before the initialization.
To avoid bugs, always declare all variables at the beginning of every scope.
But if we use let or const keyword instead of var the declaration hoisting will not work and through a ReferenceError.
x = 5; //assign 5 to x
var x; //Declare x
console.log(x);Output:
VM1099:2 Uncaught ReferenceError: Cannot access 'x' before initialization
Error Handling:
When executing JavaScript code, different errors can occur.
Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things.
try
,catch
,throw
,finally
keywords are used for error handling.
The try
statement lets you test a block of code for errors.
The catch
statement lets you handle the error.
The throw
statement lets you create custom errors.
The finally
statement lets you execute code, after try and catch, regardless of the result.
Syntax:
try {
try_statements
}
catch (exception_var) {
catch_statements
}
finally {
finally_statements
}
Example:
try {
nonExistentFunction();
} catch (error) {
console.error(error);
// expected output: ReferenceError: nonExistentFunction is not defined
// Note - error messages will vary depending on browser
}
Throw:
When a catch
-block is used, the catch
-block is executed when any exception is thrown from within the try
-block. For example, when the exception occurs in the following code, control transfers to the catch
-block.
try {
throw 'myException'; // generates an exception
} catch (e) {
// statements to handle any exceptions
logMyErrors(e); // pass exception object to error handler
}
Scopes:
Before ES2015, Javascript had only two types of scope. They are Global Scope and Function scope.
ES6 introduced let
and const
keywords that provide Block Scope.
Global Scope:
Variables declared globally (outside any function) have global scope.
Global variables can be accessed from anywhere within the program.
Function Scope:
Variables declared locally (inside a function) have function scope.
Local variables can only be accessed from inside the function where they are declared. They cannot be accessed from outside of the function.
Block Scope:
Variables declared with the let
or const
keyword inside a block have Block Scope.
Variables declared inside a block {} cannot be accessed from outside the block.
Functions:
In Javascript, functions are defined with the function keyword.
We can use a function declaration or a function expression.
// function declarationfunction myFunction(a, b) {
return a * b;
}
A JavaScript function can also be defined using an expression.
var x = function (a, b) {return a * b};
The variable can be used as a function. This type of function is called an anonymous function(a function without a name).
var x = function (a, b) {return a * b};
var z = x(4, 3);
Arrow Functions:
ES6 introduced a new way to define a function. Actually, it is a short syntax for writing function expressions.
// ES5
var x = function(x, y) {return x * y};
// ES6
const x = (x, y) => { return x * y };
No need to use function
keyword, the return
keyword, and the curly brackets if the function is a single statement.
const x = (x, y) => x * y;
Spread Syntax(…):
Spread Syntax or Spread Operator or Three Dots.
Spread syntax (...
) allows an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
Array:
function sum(x, y, z) {
return x + y + z;
}const numbers = [1, 2, 3];console.log(sum(...numbers));// expected output: 6
It is commonly used when we want to add a new item to a local data store .A very simple version of this kind of action could look like:
let numberStore = [0, 1, 2];
let newNumber = 12;
numberStore = [...numberStore, newNumber];
Concatenate Arrays - a better way using spread syntax.
Normal array concatenation:
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
// Append all items from arr2 onto arr1
arr1 = arr1.concat(arr2);
With spread syntax this becomes:
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];
// arr1 is now [0, 1, 2, 3, 4, 5]
// Note: Not to use const otherwise, it will give TypeError (invalid assignment)
Object:
Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax.
let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };
let clonedObj = { ...obj1 };
// Object { foo: "bar", x: 42 }
let mergedObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 42, y: 13 }