20 Javascript Tips and Tricks

Following contains a list of javascript snippets which can be included in our projects. Ive been collecting this locally like a library which helped me through my projects. Now just thought of sharing it over here.

1) How to get query string values in JavaScript ?

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
    results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));

2) How to redirect page in JavaScript ?

// similar behavior as an HTTP redirect
// similar behavior as clicking on a link
window.location.href = "http://blog.roymj.co.in";

3) How to get a timestamp in JavaScript ?

var currentTimeStamp = new Date().getTime();

4) Check if one string contains another substring in JavaScript ?

indexOf returns the position of the string in the other string. If not found, it will return -1.

var s = "foo";
alert(s.indexOf("oo") != -1);

5) How to Capture the close Event of a Browser ?

JS :

function PageUnloadHandler() {
    alert("Do something to invalidate the sessions");


<body onbeforeunload="PageUnloadHandler()">
    <!-- Body content -->

6) How to use the Conditional Operator in JavaScript ?
Instead of using the following :

if (val) {
  return foo();
} else {
  return bar();

We can simply use :

return val ? foo() : bar();

7) How to remove a property from a JavaScript object ?

var myJSONObject = {
    "fn": "Roy",
    "ln": "MJ",
    "loc": "India"
//To remove propery loc
delete myJSONObject.loc;
// or,
delete myJSONObject['loc'];

8) How to detect an undefined object property in JavaScript ?

var something = myJSONObject.fakeObject;
if (typeof something === "undefined") {
    alert("something is undefined");

9) How to Validate Email address in JavaScript ?

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\
    return re.test(email);

10) How do I append to an array in JavaScript ?

// initialize array
var arr = [
    "Test 1",
    "Test 2",
    "Test 3"
// append new value to the array
arr.push("Test 4");

11) How to check for an empty string in JavaScript ?

if (strValue) {
    //do something
    //do something

12) How to convert a JavaScript string value to all lower case letters ?

var str = "Your Name";
str.toLowerCase();//returns "your name"

13) How to clear an array in JavaScript ?

A = [1,2,3,4];

If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:

A.length = 0;

14) How to remove specific element from an array in JavaScript ?

First, find the index of the element you want to remove :

var array = [2, 5, 9];
var index = array.indexOf(5);

Then remove it with splice :

if (index > -1) {
    array.splice(index, 1);

15) How to get the selected value of dropdownlist using JavaScript?

If you have a select element that looks like this :

<select id="test">
    <option value="1">Test 1</option>
    <option value="2" selected="selected">Test 2</option>
    <option value="3">Test 3</option>

Then the following code will fetch corresponding values of selected item from the select box

var selected      = document.getElementById("test");
var selectedValue = selected.options[selected.selectedIndex].value;
var selectedText  = selected.options[selected.selectedIndex].text;

16) How to shuffle an array in JavaScript?

var list = [1,2,3,4,5,6,7,8,9];
list = list.sort(function() Math.random() - 0.5);
print(list); // prints something like: 4,3,1,2,9,5,6,7,8

17) How to add break-point programmatically in JavaScript?

// ...
// ...

If a debugger is present or active, it will cause it to break immediately, right on that line.

Otherwise, if the debugger is not present or active this statement has no observable effect.

18) How to insert an array into another array in JavaScript?

var a = [1,2,3,7,8,9];
var b = [4,5,6];
var insertIndex = 3;
a.splice.apply(a, Array.concat(insertIndex, 0, b));
print(a); // prints: 1,2,3,4,5,6,7,8,9

19) How can you check for a #hash in a URL using JavaScript?

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist

20) How can you get the height and width of a rendered image using JavaScript?

var image  = document.getElementById('image');
var width  = image.clientWidth;
var height = image.clientHeight;

clientWidth and clientHeight are DOM properties that show the current in-browser size of the inner dimensions of a DOM element (excluding margin and border). So in the case of an IMG element, this will get the actual dimensions of the visible image.

1 Comment on "20 Javascript Tips and Tricks"

  1. Woah this website will be spectacular i like looking through your content regularly. Continue the nice works of art! You recognize, a lot of people are seeking all over for this details, you are able to enable them to greatly.


Leave a Reply

Your email address will not be published. Required fields are marked *