Javascript slice() method:

Slice() method extracts a part of string and returns a new string without modifying the original string. It requires the index as start and end parameters for returning part of the string. Here negative index are allowed.

Syntax:

slice(indexStart)

slice(indexStart, indexEnd)

Here the parameter indexEnd is optional.

indexStart – index of first character to include in the returned string. If negative, this argument specifies a position from the end of the string. For example -1 indicates the last character and -2 indicates the second character from last.

indexEnd – index of first character to exclude from the returned string. As this is optional if not specified it includes all character from indexStart to end of string. Same as above, if negative argument, it specifies  a position measured from the end of the string.

Return value – A new string containing the extracted section of the string.

Example:
const s = 'Abaython';
console.log(s.slice(0,4))  
console.log(s.slice(2,4))  
console.log(s.slice(4))      
console.log(s.slice(3,-1)) 
console.log(s.slice(3,-2))  
console.log(s.slice(-3,-1))
Output:

Abay

ay

thon

ytho

yth

ho

indexStart>=index.length?

It returns an empty string.

indexStart omitted?

If indexStart is omitted, undefined or cannot be converted to a number. It consider indexStart as 0 and returns from  the start of the string.

const s = 'Abaython';
s.slice()
Output:

‘Abaython’

String methods slice(), substring() and the deprecated substr() all return specified portions of a string. Slice() is more flexible than substring() because it allows negative index values. Slice() differs from substr() in that it specifies a substring with two character positions, while substr() uses one position and a length. String.slice() is an analog of Array.slice()

How to add CSS to HTML?

Basic Insight into Inline, Internal and External CSS

Before getting into the topic of how to add CSS to HTML, first we will try to understand what CSS means, how to write it, difference between HTML and CSS, advantages of CSS.

What is CSS?

CSS stands for Cascading Style Sheet. In simple terms, CSS is used to style an HTML document. It describes how an HTML document is displayed. CSS defines the design and layout of a webpage. It can control how a web page look when loaded in browser. The term “Style Sheet” refers to the CSS document itself whereas “Cascading” refers to how style rules are applied to elements present in a web page.

What is the difference between HTML and CSS?

          While building a website, we will usually start with HTML. HTML is a Markup language, we can add headings, paragraphs, images, tables, forms, lists etc., But HTML is more of static in that we cannot change how the above-mentioned elements are presented and displayed in a webpage. It is often used for wide variety of styling purposes including changing text and background color on a page, removing underline from links, animating images, text and other HTML elements. At this point we will need CSS.CSS describes how HTML elements are displayed on a webpage. Thus, usually HTML and CSS go hand-in-hand with website development. Since the creation of CSS several updates have been made to add additional functionality to CSS, now the current standard is CSS3.

Advantages of CSS:

  • Less Coding: Developer can use CSS to apply the same styling to multiple pages and page elements across a website.
  • More Styling Options: CSS allows us to add lot more styling options to customize our website.
  • Standardization: Standardization gives us uniformity which means a developer can understand the style of a website just by looking at the CSS file.
  • Better Performance: As above mentioned, less code means smaller files, and smaller files automatically leads to less loading time which results in better performance.

How to write CSS?

A CSS syntax looks like this:

The Selector points to the HTML element we want to style.

The declaration block contains one or more declarations separated by semicolon.

Each declaration includes a CSS property and a value separated by colon.

Multiple declarations are separated by semicolon and a declaration block is enclosed by curly braces.

How to add CSS to HTML?

Now we will get into the topic of adding CSS to HTML, we can add CSS to HTML by three ways:

  • Inline CSS
  • Internal CSS
  • External CSS

Inline CSS:

          An inline CSS may be used to apply a unique style to single element. Inline styles are defined within the ‘style’ attribute of the relevant element. It is placed inside the HTML tag to change the style of an element. Since we cannot separate style and content in this type and it has violated many of the advantages of CSS, its generally not recommended to use in practice.

Output:

Internal CSS:

          CSS code is embedded in an HTML document. It is written inside the <style> element, inside the head section. It can be used when single HTML page has a unique style. Suitable for small web projects and individual web pages with their own styling.

Output:

External CSS:

          External CSS exists in its own file. The file is linked with HTML with <link> tag. It is the most common method, since one CSS can be used for multiple HTML documents. To create an external css we can write the code in any text editor or code editor and save the file with .css extension. To link the HTML and CSS file place both the files in same folder.

Linking CSS to HTML:
<link rel="stylesheet" href="external.css">
HTML:
CSS:
OUTPUT:

In this article we have learned basic understanding of CSS, its advantages and three ways of adding CSS to HTML.

What is client-side scripting?

Before jumping into client-side scripting, first we will see a short intro about script.

What is a script?

Script is a small embedded program. Popular scripting languages are Javascript, VBscript etc.,

HTML is not a scripting language because it does not have <script> tag. We need to use <script> tag to generate a script. </script> is used to end the script.

The type attribute in script specifies the type of language we are using. We can also use language attribute.

//type attribute
<script type = “text/javascript”>
     document.write(“TutorialRide”);
</script>
//language attribute
<script language= “javascript”>
     document.write(“Abaython”);
</script>

Client-side scripting:

Client side script is a small program embedded into your web page. Client-side scripting means ‘happening inside your browser’. Here scripts are executed on the browser without connecting to server. When the server sends the script along with HTML webpage to the client, the script runs on client’s browser either while page is loading or after page is loaded.

It is a technique for enhancing the interactivity of online web pages.

It is widely useful in creating dynamic user interface components like pull-down menus, navigation tools, animation etc.,

Its helpful in making the webpage user-friendly.

So, HTML, CSS and JavaScript all are client-side. They are stored on the server like files, but it’s the responsibility of the browser to do anything with them.

JavaScript is used to create dynamic and responsive webpages.

Benefits:

  • Client side scripting is quite easy to learn with minimum programming knowledge.
  • It is light weight and easy to implement. Editing and executing code is fast.
  • Data processing is done on client side from server so it is easy to scale applocations  for large set of users . Reduces workload on server.
  • Execution of client side script is quick as it done on client browser.

Limitations:

Main problem is security as the code is sent as it is. It is usually visible. Not suitable for sensitive data transmission. The web application based on the heavy JavaScript can be complicated to debug and maintain. Running of script depends on browsers configuration and security level. More limited functionalities.

4 methods to search through arrays in JavaScript

Before ECMA6, we have to search through arrays using for loops. Now we have specific methods to search through arrays.

Methods to search through arrays:
  • Array.includes()
  • Array.indexOf()
  • Array.find()
  • Array.filter()

Array.includes():

               It returns a true if a value exists in an array otherwise false

Syntax:
includes(searchElement)

includes(searchElement, fromIndex)

fromIndex is optional. Default is 0. It determines from which index to begin comparison

const arr=[2,4,6,8]

console.log(arr.includes(6))

console.log(arr.includes(10))
Output:

  True

False

In the above example when we search for the element 6 from index 3 it will return false. As the element 6 is in index 2

const arr=[2,4,6,8]

console.log(arr.includes(6,3))
Output:

False

Array.indexOf():

               This method returns the first index at which a given element can be found and -1 if it is not there. It starts at a specified index and search from left to right. By default, start from first element and ends at last element.

Syntax is similar to includes()

const indexOfElement = array.indexOf(element, fromIndex)

element – element you are searching

fromIndex – position or index from where you want to start the search

Example:

const emp=["Anna","Tom","Sam","Henry","Jack"]
let index = emp.indexOf("Henry", 2);
console.log(index)
Output:

3

Array.find():

This method is used to find the first element that meets the certain conditions. If elements do not satisfy the condition, it returns undefined. It is like filter method takes callback as an argument and returns the first element that satisfies the callback condition.

Syntax:
let element = array.find(callback);

callback is the function which is called on each element of the array. This has following parameters.

element- current element being processed.

index- index of current element

array- the array find() is called on.

find() is an iterative method.

Example:
const arr = [10, 20, 45, 120, 99];
const found = arr.find(element => element > 100);
console.log(found);
Output:

120

Array.filter()

This method will return a shallow copy of elements in an array that satisfies the given condition.

Syntax:
let newArray = array.filter(callback);

newArray is the array created with elements that satisfy the conditions.

array- array on which filter method is used.

Callback- function that is applied to each element of the array.

If no element matches the condition then an empty array is returned.

When we want to return only one element that matches the condition then we use find() method.

Example:
const arr = [10, 20, 108, 120, 99];
const found = arr.filter(element => element > 100);
console.log(found);
Output:

[108,120]

Points to remember:
  • includes() method is used to check whether a particular element present in an array. It returns a Boolean value TRUE or FALSE indicating the element is present or not.
  • indexOf() method is used to search for a particular element in an array and return the index of that element. It returns -1 if element is not there.
  • find() method is used to search for the first element that satisfies the given condition. It searches if atleast one element satisfies the condition and returns undefined if not satisfied.
  • filter() method is used to search for multiple elements and returns all the elements that satisfies the condition in a new array. It returns a empty array if no element satisfies.

Think beyond console.log()

While working with javascript we often use this popular method console.log(). During debugging when we need some insight about the happenings we use console.log(). There are a lot more methods to debug your code alternative to console.log(). These alternative console.log() methods are useful in data visualization, debugging etc.,

Alternative to console.log():

1.console.table()

This console.table() method is useful when we want to get a visual form of a group of objects that can be represented in a tabular form. It takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns. For example let us take 2 employee details and see in console.log() and console.table() methods

Using console.log():
const employee = [{id:101, name:'Anna'},
                    {id:102,name:'Tom'}];
console.log(employee);
Using console.table();
const employee = [{id:101, name:'Anna'},
                    {id:102,name:'Tom'}];
console.table(employee);

2.console.assert()

This console.assert() is great for debugging process. It takes an assertion and writes an error message when the assertion is false. If it is true nothing happens. Mainly used while debugging code. For example lets check whether a number is even and throw an error message if it is not.

const isEven = n => n % 2 === 0;
for (let i = 0; i < 3; i++) 
{
    console.assert(isEven(i), '%s is not even!', i);
}

3.console.count()

console.count() is used to count the number of times the line has been called.

for (let i = 0; i < 3; i++){
    console.count();
}

4.console.trace()

console.trace() helps you output the current stack trace at the location where you call it from. This helps in displaying a trace that show how the code ended up at a certain point.

function a() {
  b();
}

function b() {
  c();
}

function c() {
  console.trace();
}
a();

5.console.error()

console.error() is the second most popular method. It displays the error message.

console.error('This is an error message');

6.console.dir()

This method console.dir() will display the interactive view of the objects we want to log.

const employee ={
    name: 'Anna',
    age:'22',
    id:'101'
}
console.dir(employee);

7.console.warn()

console.warn() displays the warn message in yellow color.

console.warn('This is a warning message');

8.console.time()

console.time() is used to measure how long a particular operation in a program takes. This starts a timer you can use to track the time of a particular operation

console.time();

for (let i = 0; i < 100; i++) {
  // some code
}
console.timeEnd();

9.console.group()

console.group adds a level of indentation to any methods that comes after it. console.groupEnd() resets the indentation to the level it was before.

console.group('group 1');
for (let i = 0; i < 3; i++) {
    console.log(i);
}
console.groupEnd('group 1');

console.group('group 2');
for (let i = 0; i < 3; i++) {
    console.log(i);
}
console.groupEnd('group 2');

Array Data Structure – What you should know?

Already in previous post we have seen about the Data Strucutres in JavaScript. Now we will jump into the creation and implementation of arrays.

As you already know, array represents collection of similar data items. It is an object that stores multiple data items.

 Array Declaration:

By array literal

Simplest way to create an array is by using array literal [ ].

Syntax:

               let arrayname = [value1, value2, value3,….]

By new keyword
Syntax:

               let arrayname = new Array();

//creates an array with 6 elements using array literal
var arr1 = [2,3,1,4,5,7];
//create array using new keyword
var arr2 = new Array(1,3,5,7,9,0);
//create an array with undefined elements
var arr3 = new Array();
//provide elements in arr3
arr3[0] = "Apple";
arr3[1] = "Orange";
arr3[2] = "Banana";
//create an array with 2 elements
var arr4 = new Array("Tom","Paul");
console.log(arr1);
console.log(arr2);
console.log(arr3);
console.log(arr4);
Output:
Accessing arrays:

Elements of an array are accessed using indexes.

var arr1 = [2,3,1,4,5,7];
//first element
console.log(arr1[0]);
//fourth element
console.log(arr1[3]);
Output:

2

4

Adding elements to an array:

We use push() and unshift( ) methods to add elements to an array.

push() method adds elements to the end of an array.

unshift() method adds elements to the start of an array.

let fruits = ["apple","orange"];
//using push() method
fruits.push("banana");
//using unshift() method
fruits.unshift("grapes");
console.log(fruits);
Output:

Now what will happen to the above array fruits if we try to add an element at index 5 rather than index 4?

Let’s see,

let fruits = ["grapes","apple","orange","banana"];
//add element at index 5
fruits[5]="strawberry";
console.log(fruits);
Output:

So index 4 will be undefined.

Remove an element from an array:

Here also we can remove from start or end using pop() and shift() methods.

pop() removes the last element

shift() removes the first element

let fruits = ["grapes","apple","orange","banana"];
//pop() method
frutis.pop();
console.log(fruits);
//shift() method
console.log(fruits);
Output:
How to find the length of an array?

It is done by length property. Returns the number of elements in an array.

let fruits = ["grapes","apple","orange","banana"];
console.log(fruits.length);
Output:

4

Methods in an array data structure:

In JavaScript arrays there are various methods available.

MethodsDescription
concat()joins two or more arrays and returns a result
indexOf()searches an element of an array and returns its position
find()returns the first value of an array element that passes a test
findIndex()returns the first index of an array element that passes a test
forEach()calls a function for each element
includes()checks if an array contains a specified element
push()adds a new element to the end of an array and returns the new length of an array
unshift()adds a new element to the beginning of an array and returns the new length of an array
pop()removes the last element of an array and returns the removed element
shift()removes the first element of an array and returns the removed element
sort()sorts the elements alphabetically in strings and in ascending order
slice()selects the part of an array and returns the new array
splice()removes or replaces existing elements and/or adds new elements
let fruits = ["grapes","apple","orange","banana"];
//sort in alphabetical order
fruits.sort();
console.log(fruits);
//find the index position
const pos = fruits.indexOf("apple");
console.log(pos);
//slicing array
const frutis1 = fruits.slice(2)
console.log(fruits1);
//concat two arrays
const frutis2 = frutis.concat(fruits1);
Output:

7 Data Structures in JavaScript you need to know.

In this article, let’s try to understand the important data structures in javascript.

What is a Data Structure?

Data Structure is a storage that is used to store and organize data. It is a way of storing and organizing the data in such a way that it can be accessed more efficiently. It refers to group of data values, the relationship between them and the operations that can be performed on it. JavaScript has dynamic arrays i.e their size and type are not determined.

Now let us jump into the data structures in javascript.

1.Array Data Structure

Most popular linear data structure. All the elements are of same data type and stored in contiguous memory location. An array is represented by set of elements with index.

2.Stack Data Structure

Stack works on Last in First out(LIFO) principle. It is a linear data structure. It contains only one pointer and that points to the top element or last added element of the stack. Whenever we add or delete an element it is added or deleted from the top. Like a pile of books.

3.Queue Data Structure

Queue works on the principle of First in First out(FIFO). It is a linear data structure. It contains two-pointers front pointer and rear pointer. The front pointer contains address of the starting element and rear pointer contains address of the last element. The two main methods used for implementation. Enqueue is process of adding an element in the queue and dequeue is process of removing an element from the queue.

4.Linked List

Linked list is a linear data structure and here unlike arrays elements are stored in non-contiguous memory locations. It is made of group of nodes. Each node has its own data and address to the next node.

Here in linked list you have to start from head and work through the way to desired element. First element is head and last element is tail.

  • List don’t have indexes, so we cannot access elements randomly.
  • Insertion and deletion is more efficient we have to just redirect the pointers.

5.Trees

Tree is a non-linear data structure which consists of nodes connected by edges. This data structure link nodes via parent/child relationship. The top node is called root node and all the other nodes come off that node are called children. The nodes at the bottom of the tree are called leaf nodes. The height of the tree is determined by number of parent/child relationships it has.

Points to note:
  • A connection is valid between nodes when it is from parent to child.
  • Connection between siblings or child to parent are not valid.
  • Tree must have only one root node.
Examples:
  • File folders in our operating system
  • DOM model
Popular Tree based data structure
  • Binary Tree
  • Binary Search Tree
  • AVL Tree
  • Red-Black Tree
  • N-ary Tree
  • 2-3 Tree

6.Graph Data Structure

Graphs are relation based data structure helpful in storing web-like or network relationships. It is made up of a finite collection of nodes called vertices, and the connections between them are known as edges. Graphs can be of two types: Directed graph and undirected graph.

Often used in Social networks, geolocalization(Google maps) and Web analytics.

7.Hash table

Hash table is also known as hash map or hash. Generally used in Object data structures, map or dictionary as it queries through a key and hash function. Hashing is a technique of mapping keys, values into the hash table using a hash function. Key is a searched string and value is the data paired with the key. Insertion and search function are very fast irrespective of the size of the table. Hash tables are built using arrays. In real life example of hash table is in schools each student is assigned a unique id number.

How to jump in to the code in JavaScript sources from console

Let us see how to jump into the code in JavaScript sources from console by following the steps below

  1. Get the control instance in the console window ==> var control_instance = $($0)
  2. call the method name of the instance without the paranthesis. ==> control_instance.method
  3. It will print out the lines of code from the method ‘method’ of control_instance class.
  4. now double click on those lines of code. It will take us to the corresponding javascript file/code in the Sources tab of chrome developer ( Please see below picture )