1. Error handling, “try..catch”

Rakibabdur
10 min readNov 3, 2020

“Try..catch” is a most important keyword in JavaScript to prevent break-down of your site. In JavaScript ,basically in react If you write a wrong code site the whole site will have an error and the site will break-down. It doesn’t matter how experienced you are in the programming sector. Any time you can make a mistake.Ever there is no programmer who can confidently say that he won’t make any mistake during the coding time. So the try..catch most important to “catch” errors so the script can, instead of dying, do something more reasonable.

The try..catch construct has two blocks. Such as: 1. Try 2. Catch.

try {

// code…

} catch (err) {

// error handling

}

Now let’s discuss how try..catch works..

First code is executed in the try{…} area. If there are no errors found in the try{…} area , then the catch(err) is ignored.The execution reaches the end of try and goes on and it skips the catch(err).

On the other hand if any error is found in the try{…} ,then the try{…} is stopped it’s execution and whole control flow to the catch(err). Let’s explain it with example…

Example:

try {

alert(‘Start of try runs’); // (1) ←

// …no errors here

alert(‘End of try runs’); // (2) ←

} catch(err) {

alert(‘Catch is ignored, because there are no errors’); // (3)

}

Note that, try..catch only works for run time error .It won’t work if the code is syntactically wrong.

2. JSON.stringify

JSON(JavaScript Object Notation) is a format to represent value and objects. Initially it was made for JavaScript, but many other languages have libraries to handle it as well. So it is easy to use JSON for data exchange when clients use JavaScript and other servers.

JSON.stringify to convert objects into JSON

JSON.parse to convert back JSON into objects.

Let’s explain with a example bellow :

let student = {

name: ‘Karim’,

age: 30,

isAdmin: false,

courses: [‘html’, ‘css’, ‘js’],

wife: null

};

let json = JSON.stringify(student);

alert(typeof json); // we’ve got a string!

alert(json);

/* JSON-encoded object:

{

“name”: “John”,

“age”: 30,

“isAdmin”: false,

“courses”: [“html”, “css”, “js”],

“wife”: null

}

*/

According to the following example, JSON.stringify(student) takes the object and converts it into a string.

JSON.stringify() can be applied for primitives as well.

Here are some JSON supported data type :

  • JSON.stringify(student)
  • Arrays [ … ]
  • Primitives:
  • strings,
  • numbers,
  • boolean values true/false,
  • null

3. Coding Style

Our code must be as clean and easy to read as possible. It’s not mean that if our code is not clean and easy to read then it will make an error. But still if you want to prove yourself as a professional web developer and if you want a good job then you must concentrate your code to make it clean and easy to read. Coding style is actually an art in programming. A good code style greatly assists in that.

Now I will explain the cheat sheet with some suggested rules and examples.

Example:

  1. You can’t use any space between a function name and parentheses between the parentheses and the parameters. Such as: function number(x, y) In the following example , you can’t use a space after the number.
  2. You have to space between parameters. Look at example 1 . after x, you should space to separate parameters.
  3. Curly brace { on the same line, after a spac and have end after the end of the code. Such as: function number(x, y) {
  4. You should space around the operators. Such as: for (let i = 0, i < n , i++ )
  5. A semicolon is must.
  6. You should space around a nested call. Such as: alert( number(X, Y) )

In most JavaScript projects curly braces are written in “Egyptian” style with the opening brace on the same line as the corresponding keyword — not on a new line. There should also be a space before the opening bracket, like this:

if (condition) {

// do this

// …and that

// …and that

}

Note that , No one likes to read a long horizontal line of code. It’s best practice to split them. If your line is to much long , it will the reason of disturbedness for oher.

4. Comments

JavaScript comment can be used to explain the conde. It’s more important to make the code more readable. JavaScript comments can also be used to prevent execution, when testing alternative code. Normally we use comments to describe the code. If you build a website for your clients but sometimes they need to update or add something to their site, Then may

higher other developers.But the problem is , when you don’t use comments in the proper place then it will be difficult for them to understand your code.

Type of comments:

There are two kinds of comments used in javaScript.

Single line comment : Single line comments start with //.

Any text between // and the end of the line will be ignored by JavaScript (will not be executed).

Example:

// Change paragraph:

document.getElementById(“myP”).innerHTML = “My first paragraph.”;

Multi-line Comments : Multi-line comments start with /* and end with */. Any text between /* and */ will be ignored by JavaScript.

Example :

/*

The code below will change

the heading with id = “myH”

and the paragraph with id = “myP”

in my web page:

*/

document.getElementById(“myH”).innerHTML = “My First Page”;

document.getElementById(“myP”).innerHTML = “My first paragraph.”;

Guys I forgot to tell you the most important things. Though comments are very useful in the code but if you don’t use it in the proper way then it will make readable problems.

Now let’s see some bad comments …

Bad comments

// This code will do this thing (…) and that thing (…)

// …and who knows what else…

very;

complex;

Code;

Follow the following example. If your comments line is too big and you want to describe many things in just a comment then the comment line will be longer and it will lose it’s readability. But in good code, the amount of such “explanatory” comments should be minimal. Seriously, the code should be easy to understand without them.

Good comments:

Good comments make your code net and clean and more readable . Provide a high-level overview of components, how they interact, what’s the control flow in various situations… In short — the bird’s eye view of the code.

Example:

/**

* Returns x raised to the n-th power.

*

* @param {number} x The number to raise.

* @param {number} n The power, must be a natural number.

* @return {number} x raised to the n-th power.

*/

function pow(x, n) {

}

5. Block Bindings | ES6

declaring variables using the standard var keyword was commonplace in JavaScript. While super easy to use, it was not without its limitations. For one, it created an issue with ‘hoisting’. Any variable declared within a function, or within the global score, was ‘hoisted’ up to the top of the function (or global scope). Which meant that variables within smaller code-blocks, such as if-else statements or for loops, were not actually local to those blocks.

Var declaration and hoisting

Hoisting: Variable declarations using var are treated as if they are at the top of the function (or global scope, if declared outside of a function) regardless of where the actual declaration occurs.

Block-level Declarartion

Block-level declarations are those that declare variables that are inaccessible outside of a given block scope. Block scopes, also called lexical scopes, are created:

  1. Inside of a function
  2. Inside of a block (indicated by the { and } characters)

Let

let declarations are not hoisted to the top of the enclosing block.

Const

const, like let declarations, are block-level declarations.

Var Declarations and Hoisting

Variable declarations using var are treated as if they are at the top of the function (or global scope, if declared outside of a function) regardless of where the actual declaration occurs; this is called hoisting. For a demonstration of what hoisting does, consider the following function definition:

function getValue(condition) {

if (condition) {

var value = “blue”;

// other code

return value;

} else {

// value exists here with a value of undefined

return null;

}

// value exists here with a value of undefined

}

6 .SPREAD Operator

JavaScript ES6 (ECMAScript 6) introduced the spread operator. The syntax is three dots(…) followed by the array (or iterable*). It expands the array into individual elements. So, it can be used to expand the array in places where zero or more elements are expected.

1. Copying an array

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

let newFruitArray = […fruits];

console.log(copiedList); // [‘Apple’,’Orange’,’Banana’]

2. Concatenating arrays

let arr1 = [‘A’, ‘B’, ‘C’];

let arr2 = [‘X’, ‘Y’, ‘Z’];

let result = […arr1, …arr2];

console.log(result); // [‘A’, ‘B’, ‘C’, ‘X’, ‘Y’, ‘Z’]

3. Spreading elements together with an individual element

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

let newFruits = [‘Cherry’, …names];

console.log(newFruits); // [‘Cherry’, ‘Apple’,’Orange’,’Banana’]

4. 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

7. Arrow function

Arrow function is an easiest way to declare function shortly .There’s another very simple and concise syntax for creating functions, that’s often better than Function Expressions. It’s called an arrow function because it looks like an arrow( => ).

Example:

const multiplyByTwo = num => {

return num * 2;

}

Single parameter

x => 42 || (x) => 42

Multiple parameters

(x, y) => 42

Statements (as opposed to expressions)

In its most basic form, a function expression produces a value, while a function statement performs an action.

With the arrow function, it is important to remember that statements need to have curly braces. Once the curly braces are present, you always need to write return as well.

Here is an example of the arrow function used with an if statement :

var feedTheCat = (cat) => {

if (cat === ‘hungry’) {

return ‘Feed the cat’;

} else {

return ‘Do not feed the cat’;

}

}

8. Primitive Values

Primitives values in javaScript are data that is not an object and has no data. Primitive values are number strings and among the other things. All primitives are immutable, i.e., they cannot be altered. It is important not to confuse a primitive itself with a variable assigned a primitive value. The variable may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered.

This example will help you understand that primitive values are immutable.

// Using a string method doesn’t mutate the string var bar = “baz”; console.log(bar); // baz bar.toUpperCase(); console.log(bar); // baz // Using an array method mutates the array var foo = []; console.log(foo); // [] foo.push(“plugh”); console.log(foo); // [“plugh”] // Assignment gives the primitive a new (not a mutated) value bar = bar.toUpperCase(); // BAZ

9. Block Binding in ES6

Var Declarations and Hoisting:

Variable declarations using var are treated as if they are at the top of the function (or global scope, if declared outside of a function) regardless of where the actual declaration occurs; this is called hoisting. Consider the examples below:

function getValue(condition) {

if (condition) {

var value = “blue”;

// other code

return value;

} else {

// value exists here with a value of undefined

return null;

}

// value exists here with a value of undefined

}

Behind the scenes, the JavaScript engine changes the getValue function to look like this:

function getValue(condition) {

var value;

if (condition) {

value = “blue”;

// other code

return value;

} else {

return null;

}

}

The declaration of value is hoisted to the top. The variable value is actually still accessible from within the else clause. If accessed from within the else clause, the variable value will be undefined because it hasn’t been initialized, its initialized only in If clause.

Block-Level Declarations:

1.Inside of a function

2.Inside of a block { \\code block }

Let Declarations

The let declaration syntax is the same as the syntax for var. You can basically replace var with let to declare a variable, but the limit is only the current code block. Here’s an example:

function getValue(condition) {

if (condition) {

let value = “blue”;

// other code

return value;

} else {

// value doesn’t exist here

return null;

}

// value doesn’t exist here

}

10. Cross Browser

Cross Browser testing is a type of non-functional testing that lets you check whether your website works as intended when accessed through:

  • Different Browser-OS combinations i.e., on popular browsers like Firefox, Chrome, Edge, Safari — on any of the popular operating systems like Windows, macOS, iOS and Android.
  • Different devices i.e., users can view and interact with your website on popular devices — smartphones, tablets, desktops and laptops etc.

Why is Cross Browser Testing Important

Imagine that you’re trying to access a site that archives every bongo cat meme in existence. Let’s say you’re doing it for the first time from your first ever MacBook Air.

You open Safari, type the URL, press Enter, and wait for it to load. When it does, none of the GIFs are loading. Buttons and text are all over the page. You check your connectivity and reload, just to see the same screen.

In the end, you’ll likely do one of two things–assume that the site has an issue and leave to return later, or assume that the site is broken and leave to find an alternative.

Browser vendors follow Open Web Standards, but they have their own interpretations of it. Since they each render HTML, CSS, and JavaScript in unique ways, thoroughly debugging your website’s source code is not enough to ensure that your website will look and behave as intended on different browsers (or different versions of a single browser).

So it falls to web developers to abstract browser differences. Cross browser testing helps with that by pinpointing browser-specific compatibility errors so you can debug them quickly. It helps ensure that you’re not alienating a significant part of your target audience–simply because your website does not work on their browser-OS

--

--