Saturday, September 29, 2018

JavaScript - writing Modular code

Instead of multiple script tags in the body. We can combine them all using Webpack. This helps us in ordering of the scripts and managing dependencies.

For webpack:
https://webpack.js.org/
https://webpack.github.io/
https://github.com/systemjs/systemjs
https://jspm.io/

JavaScript - Frameworks - Angular - React

Sometimes, we want to build a single page application. In a SPA (Single Page Application) the user experience is handled through JavaScript. This is the modern way of building applications. The popular frameworks are React and Angular. These frameworks are written in JavaScript. This is much more powerful than Jquery. Jquery only adds certain parts on the webpage.


Refer:



JavaScript - Libraries - Jquery


Jquery uses JavaScript. But, it added many convenience functions. For example AJAX or accessing the DOM, traversing through the DOM or manipulating the DOM. This where Jquery can be really helpful.

We can download it from:
https://jquery.com/download/


Thursday, September 20, 2018

JavaScript - Events - Changing Propagation Order

Let us consider the following HTML code for our examples:

<body>
  <div style="width: 100px
              ; height: 100px
              ; background-color:green"
       id = "greenDiv">
    <div style="width: 40px
                ; height:40px
                ;background-color:yellow"
         id = "yellowDiv">  </div></div>
</body>

What if we want to change the propagation order of the triggering events.

var yellow = document.querySelector("#yellowDiv");
yellow.addEventListener("click", yellowListener);


function yellowListener(event){
  console.log("clicked Yellow Square!");
}

var green = document.querySelector("#greenDiv");
green.addEventListener("click", greenListener,true);

function greenListener(event){
  console.log("clicked Green Square!");
}

Now, if we want to change the order of propagation of events. then we can add the argument true to the green eventListener. 

JavaScript - Events - Event Object Properties

The event object has some useful properties.

Let us consider the following HTML code for our examples:

<body>
  <div style="width: 100px
              ; height: 100px
              ; background-color:green"
       id = "greenDiv">
    <div style="width: 40px
                ; height:40px
                ;background-color:yellow"
         id = "yellowDiv">  </div></div>
</body>



Example:
We can log in the event target:

var yellow = document.querySelector("#yellowDiv");

yellow.addEventListener("click", yellowListener);

function yellowListener(event){
  console.log("clicked Yellow Square!");
}

var green = document.querySelector("#greenDiv");

green.addEventListener("click", greenListener);

function greenListener(event){
  console.log(event.target);
  console.log("clicked Green Square!");
}

We get a complex object. This object actually represents the div element. So, event.target gives the object on which the event happened. This is very useful because there are times when you need this object. During runtime, we may want to know, which element precisely triggered this event.

To know the problematic element, we can set the background color of the target element to "blue".

var yellow = document.querySelector("#yellowDiv");
yellow.addEventListener("click", yellowListener);


function yellowListener(event){
  console.log("clicked Yellow Square!");
}


var green = document.querySelector("#greenDiv");
green.addEventListener("click", greenListener);

function greenListener(event){
  console.log(event.target);
  event.target.style.backgroundColor = "blue";
  console.log("clicked Green Square!");

}

Now, we can click on one of the squares and change its color to blue. So, event.target is very useful for debugging purposes.

We can also extract the position of where the click happened. For example:

var yellow = document.querySelector("#yellowDiv");
yellow.addEventListener("click", yellowListener);


function yellowListener(event){
  console.log("clicked Yellow Square!");
}


var green = document.querySelector("#greenDiv");
green.addEventListener("click", greenListener);


function greenListener(event){
  //console.log(event.target);
  console.log(event.clientX, event.clientY);
  console.log("clicked Green Square!");
}


This will print the X and Y position of the point of click on the document. So, now, if I click on one of the squares. We can see that the coordinates change depending on where my cursor is.

This is extremely useful. As we can use these coordinates to move something on the page or some other action. To check all the properties that are available by default on each event - can be found on this page:
https://developer.mozilla.org/en-US/docs/Web/API/Event#Properties

But, for specific event like say.. mouse click event we can just google for it. We can then arrive at a MDN page:
https://developer.mozilla.org/en-US/docs/Web/Events/click

... which will give us an overview of the properties which we can access at the time of developing.
https://developer.mozilla.org/en-US/docs/Web/Events/click#Properties

 If we want to get a list of all the available events on a certain object. We can either:
- log the element to the console
- google for it.




Refer:
https://developer.mozilla.org/en-US/docs/Web/API/Event

Practice at:
http://jsbin.com


Ubuntu - Install CodeBlocks

To be able to install CodeBlocks in Ubuntu 18.04

Step 1: Download codeblocks software from the website: http://www.codeblocks.org/

Step 2: Downloding it from sourceforge website:

$ wget -c https://excellmedia.dl.sourceforge.net/project/codeblocks/Binaries/17.12/Linux/Debian%20stable/codeblocks_17.12-1_amd64_stable.tar.xz
--2018-09-20 11:48:57--  https://excellmedia.dl.sourceforge.net/project/codeblocks/Binaries/17.12/Linux/Debian%20stable/codeblocks_17.12-1_amd64_stable.tar.xz
Resolving excellmedia.dl.sourceforge.net (excellmedia.dl.sourceforge.net)... 202.153.32.19
Connecting to excellmedia.dl.sourceforge.net (excellmedia.dl.sourceforge.net)|202.153.32.19|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 13759596 (13M) [application/octet-stream]
Saving to: ‘codeblocks_17.12-1_amd64_stable.tar.xz’

codeblocks_17.12-1_amd64_stable.tar. 100%[===================================================================>]  13.12M   155KB/s    in 96s     

2018-09-20 11:50:41 (140 KB/s) - ‘codeblocks_17.12-1_amd64_stable.tar.xz’ saved [13759596/13759596]

$

Step 3: Uncompress the tar archive:

$ tar xvf codeblocks_17.12-1_amd64_stable.tar.xz 
codeblocks_17.12-1_amd64.buildinfo
codeblocks_17.12-1_amd64.changes
codeblocks_17.12-1_amd64.deb
codeblocks-common_17.12-1_all.deb
codeblocks-contrib_17.12-1_amd64.deb
codeblocks-contrib-common_17.12-1_all.deb
codeblocks-dev_17.12-1_amd64.deb
codeblocks-headers_17.12-1_all.deb
codeblocks-libwxcontrib0_17.12-1_amd64.deb
codeblocks-wxcontrib-dev_17.12-1_amd64.deb
codeblocks-wxcontrib-headers_17.12-1_all.deb
libcodeblocks0_17.12-1_amd64.deb
libwxsmithlib0_17.12-1_amd64.deb
libwxsmithlib0-dev_17.12-1_amd64.deb
wxsmith-dev_17.12-1_amd64.deb
wxsmith-headers_17.12-1_all.deb

Step 4: There are numerous files here. Let us install them in the following order:

  1. sudo dpkg -i codeblocks-common_17.12-1_all.deb
  2. sudo dpkg -i wxsmith-headers_17.12-1_all.deb
  3. sudo apt-get install -f
  4. sudo dpkg -i libcodeblocks0_17.12-1_amd64.deb
  5. sudo dpkg -i libwxsmithlib0_17.12-1_amd64.deb
  6. sudo dpkg -i libwxsmithlib0-dev_17.12-1_amd64.deb
  7. sudo dpkg -i wxsmith-dev_17.12-1_amd64.deb
  8. sudo apt-get install -f
  9. sudo dpkg -i codeblocks-libwxcontrib0_17.12-1_amd64.deb
  10. sudo dpkg -i codeblocks-wxcontrib-dev_17.12-1_amd64.deb
  11. sudo dpkg -i codeblocks-wxcontrib-headers_17.12-1_all.deb
  12. sudo dpkg -i codeblocks-headers_17.12-1_all.deb
  13. sudo dpkg -i codeblocks-dev_17.12-1_amd64.deb
  14. sudo dpkg -i codeblocks-contrib-common_17.12-1_all.deb
  15. sudo dpkg -i codeblocks_17.12-1_amd64.deb
  16. sudo apt-get install libcanberra-gtk-module:i386

To check the installation codeblocks:

$ which codeblocks
/usr/bin/codeblocks


To run codeblocks:
$ codeblocks



Tuesday, September 18, 2018

JavaScript - Events - Event Behaviors

In JavaScript there are certain events we need to know. Consider the following body code:

<body>
  <div style="width: 100px
              ; height: 100px
              ; background-color:green"
       id = "greenDiv">
    <div style="width: 40px
                ; height:40px
                ;background-color:yellow"
         id = "yellowDiv">  </div></div>
</body>




This is a nested HTML code - where the yellow div square is inside the green div square. Now, let us add a click listener to the yellow div here.

var yellow = document.querySelector("#yellowDiv");

yellow.addEventListener("click", yellowListener);

function yellowListener(event){
  console.log("clicked Yellow Square!");
}

var green = document.querySelector("#greenDiv");

green.addEventListener("click", greenListener);

function greenListener(event){
  console.log("clicked Green Square!");
}


Now, the question is - where does this event argument come from?
JavaScript passes this event object automatically to the listeners and this object will depend on the type of event. Example:
  • mouse Click Events
  • mouse Enter Events

different types of events to which you can listen and all those types will have their own properties and methods which we can access on the event object which we are passing as the argument here. To use the object is optional. 

Now, to find out more about which properties and methods are available for each event object. We can do the following:
- log it to the console and have a look there. 
- google for JavaScript click event and we can get access to articles with information.

Now what happens when I click on the yellow button. We get two messages. This is because events in JavaScript by default - propagate. This means that:
If I am clicking on the yellow div here. It means that I am also clicking on the green div. Since, the green one holds the yellow square. 

Now, if i don't want the propagation to occur then, I need to modify the yellowListener function to include the event.stopPropagation():

function yellowListener(event){
  event.stopPropagation();
  console.log("clicked Yellow Square!");
}

Hence stopPropagation is a very important method here. We can check if the event has the tendency to bubble up. 

function yellowListener(event){
  console.log(event.bubbles);
  event.stopPropagation();
  console.log("clicked Yellow Square!");
}

We can see that true is output to the console.


JavaScript - Events - Event Listeners

As an alternative to Event handlers, JavaScript has event listeners. This alternative mainly addresses the problem that you cannot have multiple event handlers for the same event on the same element.

Consider the following code snippet

var btn = document.querySelector("button");
btn.addEventListener("click", myListener1);
btn.addEventListener("click", myListener2);

function myListener1(){
  console.log("inside Listener 1");
}

function myListener2(){
  console.log("inside Listener 2");
}

addEventListener is a method available on each HTML element. The first argument is the name of the event. In the above code the event is click. The second argument is the function I want to run when the listener fires when this event is recognized.

It is also possible to remove a listener:

var btn = document.querySelector("button");

btn.addEventListener("click", myListener1);
btn.addEventListener("click", myListener2);

function myListener1(){
  console.log("inside Listener 1");
}

function myListener2(){
  console.log("inside Listener 2");
}

setTimeout(function(){btn.removeEventListener('click',myListener1);
                     console.log("Listener 1 removed.");
                     },2000);


removeEventListener method allows to remove listener. In the above example, Listener 1 is removed after 2 seconds.




JavaScript - Events - Event Handlers



window.onload = function() {
  console.log("Window loaded.");
};


Now, say - I have the following code snippet:
<body>
  <button>Click Here</button>
</body>

Now, let us add an onclick event on this button:

var btn = document.querySelector("button");

btn.onclick = function(){
  console.log("Button Clicked");
};

We have setup the onclick handler. On pressing the button we can see the output on the console. This is a very useful concept.

But, how can we know, which specific functions are available on the HTML element?
Technique 1: Log the element to the console and then check the properties and then we can identify the event handlers by the on* prefix on the event handler variables.
Technique 2: Google for JavaScript <<element name>> <<events >> and we can find the relevant links with information about it.

We can add the onclick event on any HTML element. We can add the onclick event on the document itself:

document.onclick = function(){
  console.log("Clicked");
};

But, there is one major disadvantage of this approach. Now, suppose we have two event handlers associated with the same button element:

var btn = document.querySelector("button");

btn.onclick = function(){
  console.log("Button Clicked");
};

btn.onclick = function(){
  console.log("Button Clicked 2");
};

Now we see only the message:
Button Clicked 2

.. on the console.

This has happened because the first event handler is simply overwritten. Hence, it is no longer available. Hence, this can become a problem as there will be times when you will need multiple listeners!

JavaScript - Events - How does it work?

You have a general event interface which JavaScript offers. Then you have multiple specific events which implement the top level event:

The following link lists the interfaces based on the main event interface:
https://developer.mozilla.org/en-US/docs/Web/API/Event#Introduction

 Therefore all events in JavaScript share certain properties and methods. Also, there are certain events and properties which are important and more frequently used than others.

The following link lists the properties of the general event interface or object and also specific events which you can listen:
https://developer.mozilla.org/en-US/docs/Web/API/Event#Properties




Refer:
https://developer.mozilla.org/en-US/docs/Web/API/Event
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events

Practice at:
http://jsbin.com/?js,console

JavaScript - Document Object Model - Dialogs

There are built in dialogs the window object offers. Dialogs are basically pop-ups the user will see and the one very prominent one which is used for debugging instead of console.log is the Alert.

Alert:
It is a function on the window object. It is used like this:
alert("This is an alert");

I get this window here. We can only click OK.

Confirm:
Apart from alert we have confirm function which will provide the user with two options:

  • Cancel
  • OK


confirm("Are you sure?");


I can also use this with console.log():

console.log(confirm("Are you sure?"));

If the user chooses OK. Then true is returned.
If the user chooses Cancel. Then false is returned.

Prompt:
The prompt dialog will provide the user with a textfield for inputting:
console.log(prompt("What is your Name ?"));



Once the user types in the answer in the textField and presses OK. The answer is returned.
We must really think before using them as there are better ways with modals - as in page pop ups.



Practice at:
http://jsbin.com

Refer:







JavaScript - Document Object Model - Elements and Nodes

Let us first explore the cross browser method of deleting elements. Consider the following body code:

<body>
  <h1 id="firstId">hey there</h1>
<ul>
  <li ><a href="#">Link 1</a></li>
  <li class = "dimple">full</li>
  <li class = "pimple">ness</li>
  </ul>
</body>


Now, instead of the following:

var a = document.querySelectorAll("li")[1];
a.parentElement.removeChild(a);

we can also use:

var a = document.querySelectorAll("li")[1];
a.parentNode.removeChild(a);

In both cases the second list item is removed. Now, when we open in developer tools of chrome. We can see that in the Elements tab - there are numerous nodes. Now, all elements are nodes. But the DOM also contains nodes which are not HTML elements. Hence, we cannot use parentElement and parentNode interchangeably all the time. But, if you are using elements in an HTML then parentElement is the one which we need to use.


Monday, September 17, 2018

JavaScript - Document Object Model - Delete Element

Let us first explore the cross browser method of deleting elements. Consider the following body code:

<body>
  <h1 id="firstId">hey there</h1>
<ul>
  <li ><a href="#">Link 1</a></li>
  <li class = "dimple">full</li>
  <li class = "pimple">ness</li>
  </ul>
</body>


Now, if you want to remove the second list item with text = full . Then we do it in the following manner:

var a = document.querySelectorAll('li')[1];
a.parentElement.removeChild(a);

This looks somewhat inconvinient as we are first selecting the parent and then removing the child. But, this is the only method with is supported by the older browsers.

The better way would be to just call the remove method.
var a = document.querySelectorAll('li')[1];
a.remove();

But use this with caution as it does not work with all the browsers.

JavaScript - Document Object Model - Insert Element

Let us work on the following body code:

<body>
  <h1 id="firstId">hey there</h1>
<ul>
  <li ><a href="#">Link 1</a></li>
  <li class = "dimple">full</li>
  <li class = "pimple">ness</li>
  </ul>
</body>


Consider the following example:

var p = document.createElement("P");
p.textContent = "A new Paragraph!";
p.style.fontSize = "16px";
console.log(p);
// let us decide where we want to add it

var a = document.querySelectorAll("li")[0];
a.appendChild(p);

This will insert the paragraph inside the first list item after the anchor tag. Now, if I want to insert it before the anchor tag.

var p = document.createElement("P");
p.textContent = "A new Paragraph!";
p.style.fontSize = "16px";
console.log(p);
// let us decide where we want to add it

var li = document.querySelectorAll("li")[0];
var a = li.firstElementChild;
li.insertBefore(p,a);


So, this is how we can add the elements at different places of our document. 

JavaScript - Document Object Model - Query Selectors - Practice

Consider the following body code:

<body>
<ul>
  <h1 id="firstId">hey there</h1>
  <li ><a href="#">Link 1</a></li>
  <li class = "dimple">full</li>
  <li class = "pimple">ness</li>
  </ul>
</body>

Using query selectors on it:

document.querySelector("a").style.backgroundColor = "red";

.. this will change the background of the first anchor tag to red.

document.querySelector(".pimple").style.backgroundColor = "red";

.. this will change the last list item to red color - since it is having the class = pimple.

Since, .pimple class is the third list item. We can also select it using:

document.querySelectorAll("li")[2].style.backgroundColor = "red";

Now, if I want to highlight the link:
document.querySelector("li").firstElementChild.style.backgroundColor = "red";

If I want to change the text of the link:

document.querySelector("li").firstElementChild.textContent = "Its a Link";


JavaScript - Document Object Model - Selecting Elements

First the mediocre way:

console.log(document.getElementsByTagName("li"));

This will return an complex object with an array containing all the list elements. 

Now, add the following body code with CSS class names:

<body>
<ul>
<h1 id="firstId">hey there</h1>
  <li class = "simple">Mind</li>
  <li class = "dimple">full</li>
  <li class = "pimple">ness</li>
  </ul>
</body>


The following will list all elements by Class Name:
console.log(document.getElementsByClassName("simple"));

You can also get element by Name:
console.log(document.getElementById("simple"));

Query Selectors: 

There is a best way as well. JavaScript also has querySelectors:
console.log(document.querySelector("li"));

querySelectors use the CSS selectors. Now, if you want to select using the class Name:
console.log(document.querySelector(".simple"));

But, this returns only one element. But, if you want to return all the elements as an array:
console.log(document.querySelectorAll(".simple"));

We can also use the hashtag (#) selector to select by ID:

Add the follow

console.log(document.querySelector("#firstId"));

... this selects element by ID.

After selecting, we can change the background color of the selected element:

console.log(document.querySelector("#firstId").style.backgroundColor="red");

query selector makes it easier as you do not have this chain calls. 










JavaScript - Document Object Model - Traversing DOM

Plug in the following body in your html code:

<body>
<ul>
  <li>Mind</li>
  <li>full</li>
  <li>ness</li>
</ul>
</body>


Try the following to practice traversing DOM:

console.log(document.body.firstElementChild);
console.log(document.body.firstElementChild.firstElementChild);
console.log(document.body.firstElementChild.firstElementChild.nextElementSibling);
console.log(document.body.lastElementChild);
console.log(document.body.firstElementChild.parentElement);


Practice at:
http://jsbin.com


Sunday, September 16, 2018

JavaScript - Document Object Model - DOM Interaction

After window object and location object. Let us now check out the Document Object. The document object is just another object on the window object.

So, If I run:

console.log(document);

... the screen is filled with lot of information. This is not really helpful. We can access the URL property to get our current URL:

console.log(document.URL);

But, we could use the location object for the same. The document object has the title property. So, when I run the following:

console.log(document.title);

.. I can see the title of the page. The document also has the body. So, if I type this:

console.log(document.body);

.. we get our DOM. That is, our translated HTML code and all the events in it. So, this is a very important part. So, if I want to view the children:

console.log(document.body.children);

I get an array of all the HTML tags represented as objects here. Because, they are translated into objects by the browser with their own attributes and properties and we can work with that and manipulate this.

Now, I will add the following to the body element:

<body>
<h1>hey there!</h1>
</body>

Now, to view the text content in the first child element of the body (h1 tag):

console.log(document.body.children[0].textContent);

We can also change the textContent in the H1 tag:

document.body.children[0].textContent = "Its me!"

This concept is really useful at a lot of places. This is because, you do not need to reload the page. That is, you do not need to get a new page from the server, but, you change the existing page. And, single page applications like angular - do exactly this. They have one single page and change it all the time. And, we can do this on our own as well by accessing the properties of your HTML elements.
You change them or you can get them or you can do whatever you need to do.

Now, how do we find out which property an element has ? We can log

console.log(document.body.children[0]);

These are all the properties you can access.  Now, let us access the style property:
document.body.children[0].style.backgroundColor = "red";

Practice at:
http://jsbin.com


Thursday, September 13, 2018

JavaScript - Document Object Model - Location object

The location object in JavaScript refers to the location bar in the browser. Examples:

  • console.log(location.pathname)
  • console.log(location.reload())
  • console.log(location.replace("https://www.google.com"))


Location object is very useful to know where you are and to get to another point where you want to navigate to.

Refer:
https://developer.mozilla.org/en-US/docs/Web/API/Location

Practice at:
http://jsbin.com

JavaScript - Document Object Model - Window object


let a = window.innerWidth;
console.log(a);

Since, we are in the widow is the global object. That is why we can just use it as:
console.log(innerWidth);

If we want to actually, see the width of the window, check the outerWidth variable
console.log(outerWidth);

To check the height of the window:
console.log(innerHeight);
console.log(outerHeight);

To know all the available properties on the window object:
console.log(window);

The window object is a really complex object - giving access to high level features here. The methods: setTimeout and setInterval are also the methods available on the window object.

localStorage: It is a built in storage which will save certain values in the browser - as long as the application is running here. We can use the setItem method on the localStorage:

localStorage.setItem('key1',55);

Now, we can get the value stored against the key using the getItem method.
console.log(localStorage.getItem('key1'));

sessionStorage: We also have sessionStorage, which is similar to localStorage:

sessionStorage.setItem('key1',55);
console.log(sessionStorage.getItem('key1'));

The difference is the localStorage will persist. But the sessionStorage will be deleted or emptied when the user closes the tab or the browser.

location: The window object also has the location you are currently at:
console.log(window.location);

document: The window object also has access to the document or the DOM:
console.log(window.document); // the dom

open: This will open the URL in a separate tab:
window.open("http://www.google.com");

The goal is not to learn all. But, to know how to find and use these objects. The global scope we are referring to the window object. So, the global scope is the window object. Therefore, we do not need to use window.anything... we can use
window.open("http://www.google.com");

as

open("http://www.google.com");

Refer:
https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction


Practice at:
http://jsbin.com/?js,console

JavaScript - Built in Feature - Regular Expressions

Regular Expressions are patterns used to match character combination in strings. Below are some examples:

var myString = "a quick brown fox jumped over the lazy dog";
console.log(myString);

var myPattern = /fox/;
console.log(myPattern);

console.log(myPattern.exec(myString));
console.log(myPattern.test(myString));
console.log(myString.match(myPattern));
console.log(myString.search(myPattern));

Console Output:

  • "a quick brown fox jumped over the lazy dog"
  • [object RegExp] { ... }
  • ["fox"]
  • true
  • ["fox"]
  • 14

Regular expressions are a science of their own. There are a lot of special characters you can use to build complex queries.

Consider the following stackoverflow question:
https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript

Without regular expressions, you would have to loop through each character in the string to search for patterns. Using pattern matching with regular expressions makes this problem simple. The pattern does look difficult. But, we can google for help. Also, we we know it, then the difficulty reduces. It is quick as it offers a great performance and it is a one liner. You do not have to write multiple nested loops to acheive the same with slower performance.

The 3 important methods in Regular expressions:

  • exec
  • test
  • match


Refer:



Practice at:

JavaScript - Built in Functions - Date Object

Date object is another important built in Object in JavaScript. Check out the following examples:

var currDate = new Date();
console.log(currDate.toString());

var specificDate = new Date(2018,14,1);
console.log(specificDate.toString());

var specificDate = new Date('2018/10/1');
console.log(specificDate.toString());

console.log(Date.parse('2018/10/1'));
console.log(currDate.getDate());
console.log(currDate.getDay());


Console Output:

  • "Thu Sep 13 2018 06:20:34 GMT+0530 (India Standard Time)"
  • "Fri Mar 01 2019 00:00:00 GMT+0530 (India Standard Time)"
  • "Mon Oct 01 2018 00:00:00 GMT+0530 (India Standard Time)"
  • 1538332200000
  • 13
  • 4



Practice at:




Refer:



Wednesday, September 12, 2018

JavaScript - Built in Functions - Math Object

In JavaScript, we may use some built in objects. One amongst them is the Math object.
Some useful examples using Math object:

var myPI = Math.PI;
console.log(myPI);

var myE = Math.E;
console.log(myE)

var a = -5.5648;
console.log(Math.abs(a))
console.log(Math.ceil(a))
console.log(Math.floor(a))
console.log(Math.exp(10)); // e to the power of 10
console.log(Math.log(10)); // log of 10 to the base e
console.log(Math.max(10,20,30,40,50,60,70,80,90,100)); 
console.log(Math.min(10,20,30,40,50,60,70,80,90,100)); 
console.log(Math.random()); // Generates a random number between 0 and 1
console.log(Math.random()*100); // To get a random number between 0 and 100
console.log(Math.floor(Math.random()*100 + 1)); // To get a random integer between 1 and 100




Console Output:

  • 3.141592653589793
  • 2.718281828459045
  • 5.5648
  • -5
  • -6
  • 22026.465794806718
  • 2.302585092994046
  • 100
  • 10
  • 0.1347258816281942
  • 45.48059516716245
  • 90





Refer:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math

Practice at:
http://jsbin.com

JavaScript - Built in Functions - String Functions

In JavaScript, a string is treated as an array. The following are some commonly used string functions:

var myString = "  a quick brown fox  ";
console.log(myString);
console.log(myString.length);
console.log(myString[12]);
console.log(myString.charAt(12));
console.log(myString.concat("jumped over the lazy dog"));
console.log(myString.concat("jumped over the lazy dog").toUpperCase());
console.log(myString.concat("jumped over the lazy dog").toLowerCase());
console.log(myString.concat("jumped over the lazy dog").split(" "));
console.log(myString.trim());
console.log(myString.slice(4,12));


Console Output:

  • "  a quick brown fox  "
  • 21
  • "o"
  • "o"
  • "  a quick brown fox  jumped over the lazy dog"
  • "  A QUICK BROWN FOX  JUMPED OVER THE LAZY DOG"
  • "  a quick brown fox  jumped over the lazy dog"
  • ["", "", "a", "quick", "brown", "fox", "", "jumped", "over", "the", "lazy", "dog"]
  • "a quick brown fox"
  • "quick br"




Practice at:



Refer:



JavaScript - Built in Functions - parseInt - toString - toFixed

Built In Methods covered:

  1. parseInt()
  2. toString()
  3. toFixed()

There are some other useful built in functions which allow you to transform values. Consider the following code snippet:

var myNum = "25";
console.log(myNum+" is a "+typeof(myNum));

Console Output:
"25 is a string"

Now, we can use the parseInt method - which is available on the window object. That is, parseInt is available on the Global Scope.

var myNum = "25";
console.log(parseInt(myNum)+" is a "+typeof(parseInt(myNum)));

Console Output:
"25 is a number"

Now, let me try with a string which is not a number:

var myNum = "fdfdf";
console.log(parseInt(myNum)+" is a "+typeof(parseInt(myNum)));

Console Output:
"NaN is a number"


parseInt takes another argument optionally. Here I can specify the base digits of system I am operating.  The default is the decimal system, But, I can change it to hexadecimal system.  For example:

var myNum = "fbb23";
console.log(parseInt(myNum,16)+" is a "+typeof(parseInt(myNum)));

And, now if I hit run:

"1030947 is a number"

JavaScript has transformed from Hexadecimal system to Decimal System.

var myNum = 123;
var myNumStr = myNum.toString();
console.log(myNum+ " is now a "+typeof(myNumStr));

Console Output:
"123 is now a string"

toString is a method defined on the Object.prototype. This is the base prototype of all the objects. Therefore every object has by default has this toString() method. We can apply this on any object in JavaScript.

var myNum = 10.3;
var myNumFixed = myNum.toFixed();
console.log(myNumFixed+ " is now a "+typeof(myNumFixed));

Console Output:
"10 is now a string"

We can also specify the number of decimal places

var myNum = 3.1425;
var myNumFixed = myNum.toFixed(2);
console.log(myNumFixed+ " is now a "+typeof(myNumFixed));

Console Output:
"3.14 is now a string"


These are some basic built in parsers - used for transforming values.

Practice at:
http://jsbin.com