LocalStorage in JavaScript

LocalStorage is a part of Web Storage API which allows the developers to store data on the user’s web browser in stringified JSON format. The data stored in LocalStorage is persisted even after the web browser is closed and doesn’t have an expiration date. The data is stored in LocalStorage in key/value pairs.

LocalStorage API provides 5 methods to interact with Storage.

1. setItem

As the name suggests, it allows the users to add new values to the storage. This method accepts two parameters, the first parameter is the key which used to identify the data and second is the value needs to be stored.

localStorage.setItem('nameOfclient', 'Sam');

In the above example nameOfclient is the key and Sam is the value to be stored.

2. getItem

The getItem method is used to retrieve the values stored in localStorage. It accepts only one parameter the key and returns the value as a string.

const clientName = localStorage.getItem('nameOfclient');

In the above example, we’re using nameOfClient as key which points to value Sam.

3. removeItem

This method deletes the key / value pair from the localStorage. It accepts only one parameter the key of item that needs to be deleted.

localStorage.removeItem('nameOfclient');

4. clear

The clear method deletes all the records stored in the localStorage. It does not accept any parameters.

localStorage.clear();

5. key

This method will accept the index number of the item inside localStorage and will return key name of that item.

const firstKeyName = localStorage.key(0);

Storing objects and arrays inside LocalStorage

LocalStorage can only store strings. If you wish to store arrays or objects within the localStorage you first need to convert it to string. This can be easily done using JSON.stringify method. Consider the following example.

const person1 = {
  name: 'Sam',
  city: 'New York',
}
localStorage.setItem('person1', JSON.stringify(person1));

As you can see, we’re first converting the person1 object to string and then passing it to the setItem method.

To retrieve the stringified data we need to first parse it using JSON.parse method.

let person1 = JSON.parse(localStorage.getItem('person1'));

Checking for items in localStorage

In order to verify if there are any items in localStorage you can use the following code.

if (localStorage.length > 0) {
  // You've items in you're localStorage
} else {
  // You don't have anything in you're localStorage
}

Looping over items in LocalStorage

You can use localStorage.length property to loop over items stored in localStorage.

for ( var i = 0; i < localStorage.length; i++ ){
  console.log(localStorage.getItem(localStorage.key(i))) 
}

Must Read: How To Get Current Date In JavaScript

Thank you for reading. I hope you found the post helpful. In case you’ve any queries or feedback feel free to drop a comment in the comment section.

JavaScript Ternary Operator

If statement in JavaScript provides you a way to execute a block of code conditionally.

const age = 19
if (age >= 18) {
    console.log('you are old enough to drive');
} else {
    console.log('you are too young to drive');
}

However, there is a shorter way accomplish this:

const age = 19;
age >= 18 ? console.log('you are old enough to drive') : console.log('you are too young to drive');

Syntax

condition ? expression one : expression two;

As you can see in the syntax the ternary operator consists of the condition followed by two expressions. If the condition results to true, expression one is executed else expression two is executed.

Ternary operator is primarily used to conditionally assign values to the variables.

const age = 19;
const canDrive = age >= 18 ? true : false;
console.log(canDrive); // true

Recommended: How to get current date in JavaScript?

How To Get Current Date In JavaScript

In this short post, we’re going to understand how we can get current date in JavaScript.

The following code will log the current date in the console in mm/dd/yyyy format.

const now = new Date();
let day = now.getDate();
let month = now.getMonth() + 1;
let year = now.getFullYear();

if (day < 10) {
    day = '0' + day
} 

if (month < 10) {
    month = '0' + month
} 

const today = month + '/' + day + '/' + year;
console.log(today);

Now, let’s go line by line and understand what exactly is happening in this code.

const now = new Date();
let day = now.getDate()();
let month = now.getMonth() + 1;
let year = now.getFullYear();

At line one, we’re creating a new instance of the date object. And in the next three lines, we’re extracting the day, month and year.

  • getDate – returns the current date (1-31).
  • getMonth – returns the current month (0-11). Values start at zero that represents January and ends at eleven that represents December. Hence we’re adding one to month.
  • getFullYear – returns current year in four digit format e.g. 2019.
if(day < 10) {
    day = '0' + day
} 

if(month < 10) {
    month = '0' + month
} 

Next, we’re adding zero at the beginning of day and month if they are single digit numbers.

const today = month + '/' + day + '/' + year;
console.log(today);

And at the last two lines we’re simply concatenating the day, month and year in mm/dd/yyyy format and logging it to the console.

Must Read: JavaScript ES6 – What are Template Literals

Thank you for reading. I hope you found this post useful. In case you’ve any query or feedback feel free to drop a comment on this post.

For more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

JavaScript ES6 – What are Template Literals

Since the beginning of time JavaScript developers are using single quotes and double quotes to create strings. However, ES6 specification came with template literals which is more elegant way of creating strings. In this post, we’re going to understand what template literals are? And how to use them within your applications to improve code readability?

Basic Usage:

We usually use single or double quotes to create strings.

const name1 = 'sam';
const name2 = "harry";

When it comes to template literals we need to use the back tick key located on the upper let corner of your keyboard. A basic example of template literals is as follows.

const name3 = `john`;

Line Breaks:

Before ES6, we had to use \n to maintain line breaks between our strings. The following code will log the string in 2 lines.

const myText = 'I am on line one. \n I am on line two';
console.log(myText);

We can do the same using template literals in much a simpler way.

const myText = `I am on line one.
I am on line two.`;
console.log(myText);

Note that template literals are space sensitive.

const myText = `I am on line one.
                I am on line two.`;
console.log(myText);

The above code will produce the following output in the console.

I am on line one.
                I am on line two.

Interpolation:

In order to interpolate variables in variables or expression in traditional strings, you would use following syntax:

const num = 2;
console.log('Square of ' + num + ' is ' + (num * num));

You can do the same thing in much simpler way using template literals.

const num = 2;
console.log(`Square of ${num} is ${num * num}`);

As you can see in the above code, you can simply add your variables or expressions to dollar sign followed by curly braces in order to interpolate them.

Recommended: How To Inject Document Object In Angular Service

I hope you found this post useful. In case if you’ve any query or feedback feel free to drop a comment.

JavaScript ES6 – var, let and const

ES6 comes with two new keywords let and const useful for the variable declaration. At a first glance, these keywords look similar to the good old var which is being used by the JavaScript developers since the beginning of time. But, If we already had var why two new keywords to do the same thing? What makes let and const different? These are the questions we’re going to answer in the following post.

1. var

var is used by JavaScript developers since dawn of JavaScript. However, there are several downsides of using var for declaring variables.

Scope

Scope simply means in which portion of the application the variable will be available. a variable declared with var only supports two types of scopes, the function level scope, and the global level scope. This means that when a variable is declared inside a function, it will be available only inside that function and if the variable declared outside a function, it will be available globally throughout the application. Let’s understand this in detail with help of an example.

var name1 = 'Sam';

function samplefunction () {
  var name2 = 'Mark';
}
console.log(name1);
console.log(name2);

As you can see, name1 is declared outside the function and hence can be accessed globally. But, name2 is declared inside the samplefunction and hence won’t be available outside of that function and the second console.log statement will result in a reference error.

Apart from that, var doesn’t have a block level scope. In the following code, name1 will be available outside the if statement due to lack of the block level statement.

if (true) {
  var name1 = 'harry'
}
console.log(name1);

Hoisting

Hoisting is behavior in JavaScript which moves the variable declaration at the top of the current scope and initializes the variables with undefined as value. Consider the following code.

console.log(name1)
var name1 = 'harry';

The above code is interpreted as,

var name1;
console.log(name1)
name1 = 'harry';

Re-declaration

JavaScript allows the developers to re-declare the variable even if it is already been declared. This might lead conflicts if you are trying to declare a variable which is already been declared and which you are not aware of.

var name1 = 'sam';
if (1 === 1) {
  var name1 = 'harry';
}
console.log(name1); // output: harry

As you can see in the above code, name1 is already been declared, however when we try to re-declare this variable inside the if statement it doesn’t prevent us from doing it. This behavior might lead to buggy code.

Now that you’re familiar with var, lets take a look at let and const.

2. let

let is the new preferred way of declaring variables since the inception of es6. The let keyword is designed in a way that it overcomes the downsides of var.

Scope

One of the major issue with var was the lack of block-level scope, which is introduced in JavaScript with let keyword. To understand this in detail consider the following code.

let age = 19;
if (age > 18) {
  let name1 = 'sam';
  console.log(name1); // outputs 'sam'
}
console.log(name1); // throws ReferenceError

As you can see we are declaring a variable name1 inside the if block and logging it twice, once inside the if block and second time after the if statement has ended. Since the variables declared with let are block-level variables the scope of variable name1 is limited to the if statement and hence first log statement with successfully log the value of name1 i.e. ‘sam’ however, the second log statement will throw a reference error.

Hoisting

Similar to var, The declaration of variables created using let are moved i.e hoisted to the top however, the variables are not initialized until the definition is executed. That means, if you’re trying to access a variable before it is being declared, you’ll end up with a reference error.

console.log(name1);
let name1 = 'sam' // throws a ReferenceError 

Re-declaration

Although, you can update the values of variables declared with let keyword, let doesn’t allow you to re-declare a variable within the same scope. Let’s see this in action.

let name1 = 'sam';
name1 = 'harry';

The above code will run successfully as we are just assigning a value to a variable.

let name1 = 'sam';
let name1 = 'harry';

The above code will throw an error as we are trying to declare a variable which already been declared.

3. const

As the name suggests const keyword is used to create constants i.e. the value of the variables cannot be changed after being assigned. There are lots of similarities between let and const in terms of scope and hoisting.

Scope

Similar to let, const also has the block-level scope and cannot be accessed from outside the block. Consider the following code.

if (1 == 1) {
  const name1 = 'sam';
}
console.log(name1); // ReferenceError

console.log will throw a reference error as name1 is declared inside the if block.

Hoisting

Similar to let, const declarations are moved i.e. hoisted to the top of the scope but not initialised until the definition is executed.

console.log(name2); // ReferenceError
const name2 = 'sam';

The above code will throw a reference error as we are trying to access a variable before it is being initialized.

Re-declaration

The const declarations can neither be re-declared nor re-assigned.

const name1 = 'sam';
name1 = 'harry';

The above code will throw an error as we are trying to re-assign value to a constant.

const name1 = 'sam';
const name1 = 'harry';

The above code will also throw an error as the constant name1 is already declared.

Summary:

  • Variables declared using the var keyword has global or function level scope while the variables declared using let and const has block level scope.
  • Var declarations are hoisted at the top and are initialized with undefined as value. let and const declarations are hoisted at the top however their values are not initialized.
  • Variables declared using var can be re-declared or its value can be re-assigned. Value of variables declared using let can be updated however these variables cannot be re-declared. Variables declared using const can neither be re-declared nor be re-assigned.

That’s it! I hope this post was useful. In case you’ve any query or feedback, feel free to drop a comment.

Must Read: Things you probably didn’t know you could do with Developer Console!

JavaScript – Double Equals Vs Triple Equals

JavaScript provides two different operators to test the equality of two values or variables. These operators are the double equals (==) and the triple equals (===).  Both these operators are used to test if the two values under consideration are equal. However, there is a key difference between the two.

See Also: 10 JavaScript Console Tricks You Probably Didn’t Know

The double equal operator tests only if the two values or variables which are being compared are equal and will return true even when the type of these values are different. To understand this in detail consider the following example. As you can see, the types of two values are different one is a number and the other is a string.

if (8 == '8') {
  console.log("I'm in!")
}

In the above example, if statement will return true and the string will be logged in the console.

Unlike the double equals operator, the triple equals operator not only tests if the two values are equal but also check if the types of the values under consideration are also equal.

if (8 === '8') {
  console.log("I'm in!")
}

In the above code, we’re using triple equals for comparing the two values the if statement will return false and no output will be logged on screen. 

Whenever possible, it is recommended to use triple equals operator to compare to values as it compares both values as well as types.

Thank you for reading! I hope you found it useful. In case, you’ve any query of feedback, feel free to drop a comment.

10 JavaScript Console Tricks You Probably Didn’t Know

The Console object is one of the most underrated and under utilised features of JavaScript. Most of us don’t go beyond the simple console.log method of this object. However, knowing what you’ve in your arsenal makes a great difference when it comes to debugging you’re application.

For this post, I’ve compiled a list of 10 JavaScript console tricks which you might want to add to your arsenal.

1. console.log

Most of us are familiar with the plain and simple console.log method..

console.log('dead simple console output');

However, very few people know that we can do string interpolation with the console.log method.

const name = 'Harshal';
console.log('My name is %s', name);

The above code will produce following output in the console.

My name is Harshal

With the latest es6 features you can achieve the same result using template literals. The following code will produce exactly same result as the one with previous code.

const name = 'Harshal';
console.log(`My name is ${name}`);

You can also style your text within the console.log method.

console.log('%c My name is Harshal', 'color: #ff0000; font-size: 24px');

The output text produced by above code will have red color and font size of 24 pixels.

console.log usage

2. console.count

As the name suggests, this will count the number of times a particular call to count method has been made.

console.count('India');
console.count('Russia');
console.count('India');
console.count('India');
console.count('India');
console.count('Russia');
console.count('India');
console.count('Brazil');

The above code will produce the following output,

India: 1
Russia: 1
India: 2
India: 3
India: 4
Russia: 2
India: 5
Brazil: 1

3. console.time and console.timeEnd

console.time is used to start a timer and console.timeEnd is used to stop it. These methods can be quite useful when it comes to debugging performance issues.

console.time('myTimer');
setTimeout(() => console.timeEnd('myTimer'), 5000);

As the code suggests, console.time method will start a timer with name myTimer which will be stopped inside the setTimeout method after 5 seconds. The above code will produce an output which looks similar to one given below.

myTimer: 5000.453857421875ms

4. console.dir

console.dir outputs a hierarchical list of the properties of the JavaScript object under consideration.

const body = document.querySelector('body');
console.dir(body);

5. console.info, console.warn and console.error

console.info is used to display informational text to the browser console.

console.info("India is seventh largest country by landmass");

console.warn is used to display warning text to the browser console.

console.warn("you've been warned");

console.error is used to display errors to the browser console.

console.error("Random error just to frustrate you!");

6. console.assert

console.assert used to output an error when a specified condition returns false.

function isAdult (age) {
	console.assert(parseInt(age) >= 18, {"error": "not an adult!"});
}
isAdult(19);
isAdult(17);

In the above code isAdult(17) will throw an error as 17 is less then 18.

console.assert usage

7. console.group and console.groupEnd

group and groupEnd methods are used to organize the console output in different groups. console.group starts a group and console.groupEnd ends it. Both these methods accepts a string argument which serves as the group name.

console.group('India');
console.log('Mumbai');
console.log('Chennai');
console.log('Bangalore');
console.log('Hyderabad');
console.groupEnd('India');
console.group('Nepal');
console.log('Kathmandu');
console.log('Pokhara');
console.groupEnd('Nepal');

The above code will produce following output.

console.group and console.groupEnd usage

8. console.trace

trace can be used to track the whole function call stack.

function funcOne () {
	function funcTwo () {
		function funcThree() {
			console.trace();
		}
		funcThree();
	}
	funcTwo();
}
funcOne();
console.trace usage

9. console.clear

As the name suggests it simply clears the browser console.

console.clear();
console.clear usage

10. console.table

console.table method can be used to print table.

const people = [{name: 'John', age: 28}, {name: 'Brock', age: 19}, {name: 'Mike', age: 31}, {name: 'Ron', age: 59}]

console.table(people)

The above code will produce following output. 

console.table usage

That’s it! These are the console tricks which you can use to make the debugging process more efficient.

If you’ve any feedback or query about this post, feel free to let me know in the comments below.