Javascript Tips : 1 → Using Closure functionality to create a function that sets the style to



The styleSetter function will return a function that has a local reference to the element that we have passed to styleSetter function so this is stored in the scope of the function which is returned by the function styleSetter .

Follow Javascript Jeep🚙 đŸ„¶.

Learn TypeScript:Part 2 → Type declaration.

Learn basic features of typescript

Create a new file with extenstion .ts ,say add.ts

In that file we will create a variable a , then assign different types of values then see what typescript says


When we compile the code using tsc add.ts . It generates a.js file in the same folder . And it doesn’t reports any error.

So now let’s try to add a type to a then test if TypeScript allows us to assign different types of values to variable a


number is the datatype . So when we assign a string to a variable which is declared as type Number it will throw error.

If you’re using VSCode IDE then this error will be warned when you’re writing (which means you don’t need to compile it ).

So as a first step let’s write the add function in Typescript.


: number in function() : number is the return type of the function.

If we call the method like 
--------------------------------------------------------------------
1.addNumber(1)

//error
2 function addNumber(num1 : Number , num2 : Number): Number {
~~~~~~~~~~~~~
An argument for 'num2' was not provided.
--------------------------------------------------------------------
2. addNumber("hi","hi");
// error
Argument of type '"hi"' is not assignable to parameter of type 
'Number'.
--------------------------------------------------------------------
3. addNumber(5,5)
// return 10

That is do this all you have read .

Now let’s create a function which takes two argument as type string then concat two string and return the length of the string in Typescript.


Let’s play with what you have learned , meet you at part 3.

Learn TypeScript . Part 1.

First part in learning TypeScript.


What is TypeScript ?

  • TypeScript is modern JavaScript + types .
  • TypeScript is an open-source programming language developed and maintained by Microsoft.
  • Typically Typescript is Javascript with types. So that the type error and some of data type related bugs can be resolved .
  • It is highly useful in large projects.

Why TypeScript?

In order to understand why typescript is needed, we need to understand what is the problem in Javascript.

What are the problems in Javascript?

In javascript we don’t have strict type in other words javascript is a dynamically typed language which means we can assign any type of value to a variable. The type are automatically assigned during runtime.


Let’s look a practical example why we need to go for TypeScript.


Now what if we for got to pass a number or if we pass string instead of number. What javascript do is , it doesn’t throw any error it result in NaN


This is one of the reasons of many.

So now let’s understand how typescript can be used instead of javascript ,

  • We write code in TypeScript(Javascript with types) ,with file extension .ts
  • Then we compile the .ts file using the command tsc filename.ts .
  • The file will be transpiled from Typescript to Javascript.
  • The we can include the javascript to our webpage.


We write code in Typescript it is converted into javascript by typescript compiler , the typescript compiler will check if there is any type error present , if so it will result in compilation error or else it will produce a javascript file.

Typescript → Javascript + types. 

How to install TypeScript.?

You can install typescript by two ways

1 . Via npm (the Node.js package manager)

You need node to be installed on your system . you can download it from here .

Once node installed it installs npm(node package manager).

After installing node type the below command to install typescript

npm install -g typescript

It will install typescript in your machine globally.

By installing TypeScript’s Visual Studio plugins

Visual Studio 2017 and Visual Studio 2015 Update 3 include TypeScript by default. If you didn’t install TypeScript with Visual Studio, you can still download it.

Getting a random item from an array

Let’s write a function to return a random element from an array.

We can use Math.random() to generate a number between 0–1(inclusive of 0, but not 1) randomly.


Then multiply the random number with the length of the array.

floor to result to make it whole number .

That’s it we find the random Index.

Let’s explore more 
..

Get the random number between specific range


Here we have + min at the end so that it ensures if rand is 0 then we add min so that it results in minimum value provided.

Let’s try to shuffle an array using Math.random()


Implement copy-on-click using JavaScript

We have seen many websites have the option to copy a block of text by clicking a button. Let’s learn how to build this using vanilla JavaScript.

Steps to copy text in javascript
1. Create a textarea element
2. Get the text from the div using div.innerText
3. Set the value of textarea with the text we retrived
4. Then select the text using select() method
5. Then use the method document.execCommand('copy') to copy text.
NOTES: Don't forgot to set text area width and height, and also DO NOT set  "display : none" property to the textarea.



https://gitconnected.com/learn/javascript

Find the number of days between two dates in Javascript

Learn to find the difference between two dates in javascript.

Let’s take an example of what we are going to do. We have a function that takes two dates as the input, and it returns the number of days.

If we pass May 22, 2019 and May 28, 2019, then it returns 7.

The solution to the problems

1. Convert the date object in to millisecond
2. Subtract the second date from first date.
3. Divide that by number of milliseconds per day (86400000) calculated by (1000 * 60 * 60 * 24)
1000 --> 1 second
60   --> 60 minutes
60  -->  60 seconds
24  --> 24 hours

Program

const MILLISECONDS_PER_DAY = 1000 * 60 * 60 * 24;
function dayDifference(date1, date2) {  
   var timeDiff = Math.abs(date2.getTime() - date1.getTime());
   var diffDays = Math.ceil(timeDiff / MILLISECONDS_PER_DAY);
   return diffDays;
}
var date1 = new Date(); //May 28 2019 
var date2 = new Date(); 
date2.setDate(22);
dayDifference(date, date1); // 7

Note: dateObj.getTime() → convert date to milliseconds.

Follow Javascript Jeep🚙 for more interesting posts.


https://gitconnected.com/learn/javascript

Different ways to create Date in JavaScript.

Learn about Date object in JavaScript

To get the current time and date create a Date object without any arguments.

var now = new Date(); 
log(now) // Tue Mar 12 2019 21:14:43 GMT+0530 (India Standard Time)

There are many ways of creating a Date object

Passing milliseconds as arguments

If there is single argument and it is of type number then the number is considered as millisecond value.

The milliseconds is counted from the Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time) to check this you can create a Date object passing 0 as argument

// passing milliseconds
var sunDec17 = new Date(819138600000);
sunDec17 //Sun Dec 17 1995 00:00:00 GMT+0530 (India Standard Time)
___________________________________________________________________
passing 0 
var date = new Date(0);
date // Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)
___________________________________________________________________
passing negative value will go back from Jan-1-1970
var date = new Date(-86,400,000); // -1 day from Jan-1-1970
date // Wed Dec 31 1969 05:30:00 GMT+0530 (India Standard Time)

NOTE :To get millisecond of a Date object use DateObj.getTime() method.

Passing Date String

If you pass a string value then it is considered as DateString.

Example “2019–01–22”

To learn more about dateString format visit this link

let date = new Date("2019-01-22");
date  //Tue Jan 22 2019 05:30:00 GMT+0530 (India Standard Time)

Passing all the year, month, date, hours, minutes, seconds, ms

  • year should have 4 digit
  • if we pass less then 4 digits and that value is less then 100 then it is added to 1900.
  • month counts from 0–11
  • date counts from 1–31(max)
  • If date value is not passed or invalid then it takes date value as 1
  • If hours/minutes/seconds/ms is not passed , then it takes 0 as default value.
var date = new Date(1997, 0, 22);
date; // Wed Jan 22 1997 00:00:00 GMT+0530 (India Standard Time)
var date = new Date(1997, 0);
date; // Wed Jan 01 1997 00:00:00 GMT+0530 (India Standard Time)
var date = new Date(97, 0);
date; //Wed Jan 01 1997 00:00:00 GMT+0530 (India Standard Time)
var date = new Date(107, 2);
date; //Tue Mar 01 0107 00:00:00 GMT+0553 (India Standard Time)

if we pass invalid string then it returns invalid date

new Date(undefined) // Invalid Date
new Date(null)  
//Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)
new Date("hi") // Invalid Date
new Date("")  // Invalid Date

Follow Jagathish Saravanan for more interesting posts

Javascript Equivalent method for jQuery addClass method.

The jQuery addClass method will add the class provided to the element or elements.

Consider that we have an “div” element stored in the variable “divElement” .

<div id = "divElement"> </div>
<script> 
let divElement = document.getElementById('divElement')
</script>

now we can add class to the “divElement” in JavaScript by

function addClass(element, className) { 
  divElement.classList += " className";
}

// Method 2:

function addClass(element, className) {
  divElement.classList.add(className)->className may string or array
}

remove class name of the object

function removeClass(element, className) {
   divElement.classList.remove(className);
}

check if an element has class

function hasClass(element, className) {
    divElement.classList.contains(className);
}

Toggle the class

function toggle(element, className) {
  element.classList.toggle(className);
}
NOTE :: 
When only one argument(className) is passed: 
if
className already in classList then remove & return false
else
add className and return true.
___________________________________________________________________
When a second argument(forceAddOrRemoveClassName) is present : 
   if (second argument evaluates to  true)
          add the specified class name. 
   else
          remove the specified class name.

replace a className with new className

function replaceClass(element, oldClassName, newClassName) {
    element.classList.replace( oldClassName, newClassName)
}

Follow Javascript Jeep🚙 đŸ„¶.

If you found helpful , surprise 🎁 me here.

Understand filter in javascript.

Javascript filter method.

filter() is used to filter the array and creates a new array with the elements which satisfy the condition provided as predicate function .

filter method takes a predicate( predicate is commonly understood to be a Boolean-valued function P: X→ {true, false}) as argument , to test each element of the array satisfy condition provided. Each element of the array is passed to that function and checked against the condition provided in that function . If the function returns true then the current element will be added to resulting array.

Example 1 : given an array find odd numbers.

let array = [1,2,3,4,5,6,7,8,9,10];
let oddArray = array.filter( (number) => return number%2 );

NOTE::-- the predicate can be simplified as,
let oddArray = array.filter( number => number%2 );

In the above Example 1 we have an array with numbers from 1 to 10. When we use filter function on that array , it will loop every element and pass each element to the predicate function and check if number%2 , number%2 evaluates to 0 for even numbers and 1 for odd numbers. So for odd numbers it returns 1, so that the odd numbers are added to the resulting array.

EXERCISE SUMS :

  1. [1,2,3,4,5,6,7] find the numbers which are greater than 6.
  2. [“abC”, “bac”, “cad”, ”dad”] find the string which is palindrome.

EXAMPLE 2 :

The predicate function can take three arguments.

element[, index[, array]
  1. element → current element of the array on each looping operation
  2. index → current Index
  3. array → source array

Now , [1,2,3,4,5,6,7,8,9,10] we are going to change all the odd numbers into even numbers in this array , (we can change an odd number to even number by adding +1 to it). Here we are changing in its original array itself. This example is used here because to show how to use all three arguments of the predictive function.

var array = [1,2,3,4,5];
array.filter((element, index, sourceArray) => {

if(element %2 === 1) {

sourceArray[index] += 1;
     }
})
log(array); // [2, 2, 4, 4, 6]

Exercise :

  1. [“one”, “two”, ”three”] reverse all the elements of the array

Follow Jagathish Saravanan for more interesting posts

Get keys of the object in javascript

Object.keys() method can be used to get the keys of the object.

We get the keys in same order as we get in the normal for..in loop

It returns an array filled with the keys of the object.

// array
var num = [1 , 2, 3];
console.log(Object.keys(num)); // ['0', '1', '2']

// object
var obj = { 0: 'zero' , 1: 'one' , 2: 'two' };
console.log(Object.keys(obj)); //['0', '1', '2']

//object
var user = {name : "John", age : 20}
console.log(Object.keys(obj)); // ['name', 'age']

var functionObj = {
value_function () { return 10; }
}
console.log(Object.keys(functionObj)); // ['value_function']
Object.keys([]) // []
Object.keys({}) // []

Follow Jagathish Saravanan for more posts

Design a site like this with WordPress.com
Get started