Effective Programming

Git – How to undo ‘git add’ before commit

To undo git add before git commit, do this git reset <file> In addition to afore-mentioned example, we can undo staging all files, without any file name. This is useful when there are too many files to be listed one by one in a reasonable amount of time. git reset

JavaScript – How to remove a particular element from an array

To remove an element from an array. First, we need to find the index of the element you wish to remove. var array = [100, 200, 300]; var index = array.indexOf(300); if (index > -1) { array.splice(index, 1); } console.log(array); Then remove it with splice() Output (2) [100, 200]

JavaScript – How to get current Date

To get current date. Use new Date() to generate a new Date object containing the current date and time. var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd < 10) { dd = '0'+dd } if(mm < 10) { mm = '0'+mm }... » read more

JavaScript – How do I loop through an object

Given an object as following: var o = { "k1": "value1", "k2": "value2", "k3": "value3" }; To loop through it, then do following: for (var key in o) { if (o.hasOwnProperty(key)) { console.log(key + " - " + JSON.stringify(o[key])); } } Output k1 - "value1" k2 - "value2" k3 - "value3" References: MDN Web Docs... » read more

JavaScript – How to check whether a string contains a sub-string

1. String indexOf() String.prototype.indexOf returns the position of the string in the other string. If not found, it will return -1. var haystack = "foo", needle = "oo"; haystack.indexOf(needle) !== -1; //Output: true 2. String includes() Starting from ES6, includes() determines whether one string may be found within another string, returning true or false as... » read more

JavaScript – How to Redirect to another Webpage

window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user will not have a chance in never-ending back-button fiasco. In a nutshell: To simulate someone clicking on a link, use window.location.href. // similar behavior as clicking on a link window.location.href = ""; To simulate... » read more

JavaScript – Closure Explained

1. A function inside another function, a closure is used. 2. A closure in JavaScript is like keeping a copy of all the local variables, just as they were when a function exited. 3. It is probably best to think that a closure is always created just an entry to a function, and the local... » read more