javascript notes

Javascript [.js]

Introduction:

  • HTML’s first version, designed by Tim Berners-Lee from 1989 to 1991, was fairly static in nature. 
  • Except for link jumps with the a element, web pages simply displayed content, and the content was fixed. 
  • In 1995, the dominant browser manufacturer was Netscape, and one of its employees, Brendan Eich, thought that it would be useful to add dynamic functionality to web pages. 
  • So he designed the JavaScript programming language, which adds dynamic functionality to web pages when used in conjunction with HTML. 
  • For example, JavaScript provides the ability to update a web page’s content when an event occurs, such as when a user clicks a button. 
  • It also provides the ability to retrieve a user’s input and process that input.
Javascript is scripting or interpreted language .i.e the code executes line by line when the browser load the javascript into the memory. 
Why JavaScript:
  • JavaScript adds behavior to the web page where the web page is capable of responding to actions by your visitors without needing to load a new web page in order to process their request.
  • We need JavaScript to add interaction to websites. Otherwise all sites would be mostly read only static text and images or we'd need third party plug-ins like Adobe Flash or Sun Java.
  • There is some low level animation possible with CSS and HTML5 now but for real functionality you need JS.
  • There are also a lot of transpilars that target JS. You can nowadays write your code in any other popular programming language and then transpile it to JavaScript.


Advantages of using JavaScript:

  1. Fast and Responsive
  2. Platform independent
  3. Javascript is a relatively easy language
  4. Executed on the client side
  5. -JavaScript is comparatively fast for the end user
  6. Extended functionality to web pages
  7. Event-Based Programming language
  8. Procedural programming capabilities
  9. Easy to debug and test



ALERT:


  • Dialog boxes are methods of the window object. However, we can invoke them without explicit reference to window. 
  • They may be used depending on the type (alert, confirm, prompt) to display an information or to get input from the user.
  • The Window.alert() method displays an alert dialog with the optional specified content and an OK button.
  • Dialog boxes are modal windows - they prevent the user from accessing the rest of the program's interface until the dialog box is closed.

Syntax:

window.alert("this page is not valid");
(or)
alert(“this page is not valid”)

Example:

  • Here we used a function for the button, whenever the user click on that button the alert will shown like “ page is not valid ”.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert box...</h2>
<button onclick="myFunction()">Click here to check the validity of the page...</button>
<script>
function myFunction() {
alert("this page is not valid");
}
</script>
</body>
</html>

  • The output of the above program will display a alert box like below,



JS CONSOLE:


  • The console.log() is a function that writes a message to log on the debugging console, such as Webkit or Firebug.
  • In a browser you will not see anything on the screen. It logs a message to a debugging console.
  • It is only available in Firefox with Firebug and in Webkit based browsers (Chrome and Safari). It does not work well in all IE releases.
  • The console object is an extension to the DOM.
  • The console.log() should be used in code only during development and debugging.

Syntax:

console.log(message);

Example:

  • Use the same example which is used for alert, but instead of alerting it as message print it in console.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert box...</h2>
<button onclick="myFunction()">Click here to check the validity of the page...</button>
<script>
function myFunction() {
    console.log("this page is not valid");
}
</script>
</body>
</html>

  • The output will display in the console window, but not in the browser window.
  • For viewing the console window: go to the webpage and right click on it. You can see the option called inspect as the last option.
  • Click on that and it will brings you to the debug window, there you can see the console window.




  • You can also do some arithematic and string operations directly, in the console.




My first JavaScript program:

<!DOCTYPE html>
<html>
<body>
<h2>My first javascript program...</h2>
<script> 
document.write('JavaScript is awesone...');
</script>
</body>
</html>

  • we call a function document.write which writes a string into our HTML document.
  • You should write the javascript functions inside the <script> tag (<script> tag is used to define a client-side script which is JavaScript).
  • The output of the above program will display in the browser like below.


Script tag:

  • In the html file we write all the javascript inside script tag . the script tag can be put in the head section or at the end of the body section.
  • It is good practice to keep the script tag at the end of the body section.
Variables In Javascript:
  • Javascript is dynamically typed language. I.e we will not declare variables explicitly as string ,number , boolean and every thing is declared as var.
var name = “john”;
  • Before you use a variable in JavaScript code, you should use var to declare the variable in a declaration statement.
DATA TYPES:

Below are the primitive data types available in Javascript,
  • Boolean.
  • Number.
  • String.
  • Null.
  • Undefined.
Boolean:
A boolean represents only one of two values: true, or false. Think of a boolean as an on/off or a yes/no switch.
var boo1 = true;
var boo2 = false;
Number:
There is only one type of Number in JavaScript. Numbers can be written with or without a decimal point. A number can also be +Infinity, -Infinity, and NaN (not a number).
Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.
JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard. 
var num1 = 35;
String:
Strings are used for storing text. Strings must be inside of either double or single quotes. In JS, Strings are immutable (they cannot be changed).
JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Each element in the String occupies a position in the String. 
var str1 = 'welcome';
Null:
Null has one value: null. It is explicitly nothing.The value null represents the intentional absence of any object value.Null is not an identifier for a property of the global object, like undefined.
var x = null;
Undefined:
A variable that has no value is undefined.
var abc;
console.log(abc); // undefined

Dynamically Typed:
  • Dynamically-typed languages are those (like JavaScript) where the interpreter assigns variables  to a type at runtime based on the variable's value at the time.
  • For instance, The idea of dynamic types is that makes code flexible, i.e. if you’ve got a function which returns a number, you don’t actually have to return a number, you can return anything you like.

Example:

  • In the .js file create a object to the employee variable. We can see in detail about object creation in the following sections. Now, you can see the various types of data to take their types themselves.

var emp = 
{ name : "john",
  age :23,
  gender :'male'
}
console.log(emp);

  • In the console you can see the output as,


NAN:

  • The NAN is a global property whose value represents “NOT A NUMBER”.
  • NaN always compares unequal to any number, including NaN, it is usually used to indicate an error condition for a function that should return a valid number.
  • Use the isNaN() global function to see if a value is an NaN value.

Syntax:

var val = Number.NaN;



Example:

  • In the console, try to perform with some illegal number operations, the output will shown as NaN.


  •  Here we can see an example with isNaN(),

<html>
<body>
<script>
function nan(a) {
if (isNaN(a)) {
return NaN;
}
return a;
}
console.log(nan('Number'));  
</script>  
</body>
</html>

  • In this above example, the output will be NaN. but, if you change the value of isNaN(3)  to any number it will display the output as number.






== vs === in JavaScript:

  • ==    only compares values.
  • ===  compares values and its type.

  • JavaScript has both strict and type converting comparisons. A strict comparison (===) is only true if the operands are of the same type and the contents match.
  • The more commonly-used abstract comparison (==) converts the operands to the same type before making the comparison. For relational abstract comparisons, the operands are first converted to primitives, then to the same type, before comparison.

== Equality operator:

  • The equality operator converts the operands if they are not of the same type, then applies strict comparison.
  • If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

For instance, go to the console and type the variables of same type and apply the another type like string or boolean and check the output.


  • Here the output is shown as true in both of the cases because of the equality operator itself converts both of the operands into same type.

Example:

<body> 
<script>
var x = "20";
var y = 20;
if(x == y){
alert('x value is equal to y');
}
else
{
alert('x value is not equal to y');
}
</script>
</body>

  • The output of the above file will display in the browser like below,


=== Identity or Strict equality:

  • The identity operator returns true if the operands are strictly equal (see above) with no type conversion. 
  • The === operator checks for equality which means that the type and value are the same.
  • The == operator checks for equivalence which means that the value is the same and it disregards the type.

Example:

       <script>
       var x = "20";
       var y = 20;
       if(x === y){
       alert('x value is equal to y');
       }
       else
       {
        alert('x value is not equal to y');
       }</script>

  • The output of the above file will display like below,


Comparison with 0 and 1:

  • 1 is considered as true and 0 is considered as false.

Example:

     <body>
      <script>
      var x = true;
      var y = 1;
      if(y == true){
      alert('true');
      }
      else
      {
      alert('false');
      }
      </script>
      </body>


  • you can modify the behavior of the property, you can make them non-enumerable, non-writable or even non-cofigurable. 
  • Configurable properties are the only ones that can be removed using the delete operator. 
  • In default it is false.
Syntax;

Object.defineProperty(obj, prop, descriptor)

Example:

<body> 
<script>
‘use strict';
var empObject = {
name:'john', 
age:24, 
salary:4000};
Object.defineProperty(empObject, 'age', { configurable: true });
delete empObject.age;
console.log(empObject);
</script>
</body>



  • If the configurable is set to be false it will show the output as,


When configurable is set fo false:

  • you cannot delete the property by using the keyword delete
  • you cannot change the property enumerable
  • you can change the property writable from true to false but not the other way around
  • you cannot change configurable to true if its current state is false

Functions:

  • A function is a group of reusable code which can be called anywhere in your program. 
  • This eliminates the need of writing the same code again and again.
  • A function is a subprogram designed to perform a particular task.
  • Functions are executed when they are called. This is known as invoking a function.
  • Values can be passed into functions and used within the function.
  • Functions always return a value. In JavaScript, if no return value is specified, the function will return undefined.

  • Functions allow a programmer to divide a big program into a number of small and manageable functions.

Syntax:

       function functionname(parameter-list)
      {
       statements
      }

Function parameters:

  • In JavaScript, there is a facility to pass different parameters while calling a function.
  • These passed parameters can be captured inside the function and any manipulation can be done over those parameters. 
  • A function can take multiple parameters separated by comma.
  • Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. 
  • If a function is called with missing arguments, the missing values are set to undefined.

Example:

function add(x, y){
return x + y;
};

Hoisting:

  • One of the advantages of JavaScript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code.
  • In other words, a variable can be used before it has been declared.
  • However in contrast, undeclared variables do not exist until code assigning them is executed. 
  • Therefore, assigning a value to an undeclared variable implicitly creates it as a global variable when the assignment is executed. 
  • This means that, all undeclared variables are global variables.
  • Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

Example:

num = 7;
console.log(num);    // it will return 7
var num;
Variable scope:

  • A variable’s scope is the context in which the variable exists. Scope refers to the visibility of variables.
  • The scope specifies from where you can access a variable and whether you have access to the variable in that context.
  • Variables have either a local scope or a global scope.

Var:

  • In Javascript if we define a variable with key word var then that variable is available in complete function even if is defined in block like if or for.
  • The var statement declares a variable, optionally initializing it to a value.
  • Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.

Example:

<script>
function add(x, y)
{
if (x > 9)
{
var p = 20;
}
console.log(p);
return x + y;
}
var z = add(10, 20);
console.log(z);
</script>

  • The variables inside the function scope is always accessible out of the scope also,


Let:

  • In Javascript if we define a variable with key word let then that variable is not available in complete function.
  • The let statement declares a block scope local variable, optionally initializing it to a value.
Example:

<script>
function add(x, y)
{
if (x > 9)
{
let p = 20;
}
console.log(p);
return x + y;
}
var z = add(10, 20);
console.log(z);
</script>

  • The output of the above file will show error as not defined because let is accessible only within the scope. So, if you try to call or invoke it out of the scope it will show error.


Return function as output from another function:

  • In Javascript we can return the function as output from another function.
  • When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller.

Example:

<script>
function myfun() {
return "welcome to the js world...";
}
var show = myfun(); 
alert(show);
</script>




  • The output of the the above code will display an alert with the msg as “welcome to the js world...”. Here it will call the another function to return the message.


Closure:

  • A closure is an inner function that has access to the outer (enclosing) function’s variables scope chain. 
  • The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.
  • The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. 
  • Note that the inner function cannot call the outer function’s arguments object. however, even though it can call the outer function’s parameters directly.

Example:

  <script>
  var z = 20;
  function a()
  {
  var m = 40;
  function b() {
  let p = 47;
  console.log(p);
  }
  return b; // return function reference
  }
  var s = a(); //s holds refernce to b function
  s();
  </script>

  • In the browser you can see the output as 47 in the console window,


Anonymous functions:

  • Anonymous functions are functions that are dynamically declared at runtime.
  • They’re called anonymous functions because they aren’t given a name in the same way as normal functions.
  • Otherwise, In Javascript we can have functions without  the name. And they are called as anonymous functions.

Example:

  <script>
   var mathAdd = function (a, b) {
   return a + b;
   };
   var m = mathAdd(20, 30);
   console.log(m);
   </script>

  • Here, mathAdd is the variable which stores the returned object,
                        function is the function operator,
           Inside the function covered with curly brackets are considered as function   
            body.
  • The above code will gives the output as 50 according to the code,


Pass function as parameter to another function:

  • In Javascript we can pass the function as parameter to  another function.

Example:

<script>
function display(msg){
console.log(msg);
}
function demoDisplay(x, data){
x(data);
}
demoDisplay(display, "welcome to js development...");
</script>

  • Here, we declared one function with parameter. For the first parameter we are passing the function name display which is the reference of the function but not invoking.
  • X is contained the reference to the display function.
  • The output will display like below in the console,

Immediately Invoked Functions:

  • In Javascript we can invoke the function immediately as part of the declaration itself with special syntax. 
  • They are called as Immediately Invoked functions are Self Invoked Functions

Example:

<script>
(function display(msg){
console.log(msg);
})("welcome to IIF.. in js");
</script>

  • In genereal, in javascript we used to define and invoke functions seperately.
  • But in case of Immediately invoked function, you have to define and  invoke the function immediately.
  • If we want to do that first we need to cover the function with paranthesis to indicate them as immediately invoked functions.
  • Use another function paranthesis to invoke the function.
  • The output of the above code will be displayed in the browser like below,


Arguments Object Inside a function:

  • In Javascript functions we can access all the parameters or arguments passed to a function using the special argument object available inside every function.

Example:

<script>
function total(){
var total = 0;
for (let index = 0; index < arguments.length; index++) {
const item = arguments[index];
total= total + item;    
}
console.log(total);
}
total(10, 20, 30);
</script>
  • Here, we defined a function as total and called the function with three parameters without defining the controls like x, y, z.
  • For that javascript provides a default parameter called argument, which is implicitly  attached. 
  • For displaying the total, we create a for loop to loop through the items.
  • Run the above code and you will get the value of the total,


DOM and EVENTS:

  • DOM is a object representation of the html elements present in the document.
  • The Document Object Model (DOM) is a programming interface for HTML and XML documents. 
  • It represents the page so that programs can change the document structure, style, and content. 
  • It connects web pages to scripts or programming languages. 
  • Usually that means JavaScript, but modelling HTML, SVG, or XML documents as objects is not part of the JavaScript language. 
  • The DOM represents the document as nodes and objects. That way, programming languages can connect to the page.
  • A Web page is a document. This document can be either displayed in the browser window or as the HTML source. 
  • But it is the same document in both cases. The Document Object Model (DOM) represents that same document so it can be manipulated. 
  • The DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript.
  • All of the properties, methods, and events available for manipulating and creating web pages are organized into objects.


Logical tree:

  • The DOM model represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. 
  • DOM methods allow programmatic access to the tree; with them you can change the document's structure, style or content. 
  • Nodes can have event handlers attached to them. Once an event is triggered, the event handlers get executed.


How to use DOM and Events:

  • Using DOM, JavaScript can perform multiple tasks. It can create new elements and attributes, change the existing elements and attributes and even remove existing elements and attributes. 
  • JavaScript can also react to existing events and create new events in the page.

DOM methods:

  • getElementById:
  •   To access elements and attributes whose id is set.

  •  innerHTML :
  • To access the content of an element

  • getElementsByTagName: 
  • To access elements and attributes using tag name. This method will return an array of all the items with the same tag name.

  •  getElementsByClassName():
  • It returns a collection of all elements in the document with the specified class name,

Example:

        <body>
        <div id="divjs">
        JavaScript is awesome,,,
        JavaScript is a powerful language...
        JavaScript cosists of many libraries...
        </div>
        <script >
        var divelem = document.getElementById("divjs").innerHTML;
        alert(divelem);
        </script>
        </body>

  • It is a best practice to put the <scrtipt> tag inside the end of the body section,


EVENTS:

What is events?

  • In general, events are reffered as the user action or the browser action.
  • In programming, an event is an action that occurs as a result of the user or another source, such as a mouse being clicked, or a key being pressed. 
  • When the page loads, it is called an event. When the user clicks a button, that click too is an event. 
  • Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. 

Example:

  • If a user clicks a button on a webpage.
  • pressing any key.
  • closing a window.
  • resizing a window.
  • A web browser completely loading a web page.
  • A file being created or modified on a filesystem etc.

Event Handler:

  • Event handlers are embedded in documents as attributes of HTML tags to which you assign JavaScript code to execute. The general syntax is
  • < tag eventHandler = " JavaScript Code " >
  • where tag is some HTML tag and eventHandler is the name of the event handler.

  • An event handler is a routine that is used to deal with the event, allowing a programmer to write code that will be executed when the event occurs.
  • Using JavaScript, you can respond to an event using Event Handlers. You can attach an event handler to the HTML element for which you want to respond to when a specific event occurs. 
  • For example, you could attach the onMouseover event handler to a button and specify some JavaScript to run whenever this event occurs against that button.

Event Listener:

  • The addEventListener() method attaches an event handler to the specified element.
  • The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.
  • You can add many event handlers to one element.

Adding Event Listeners:

  • You can add an event listener directly in the HTML code in the following way:

                  <button onclick="alert('Hello, world');"></button>

  • However, mixing the JavaScript code with the HTML directly is generally a poor practice for the same reason that you don't integrate style commands into HTML but rather reference the styles in a separate CSS file.

Adding the addEventListener Method:

  • You can also add event listeners using a method called addEventListener. If you use this method, you need to add some conditional functions to check for browser functionality before running the function.
  • The format for adding events using this method is as follows:

document.addEventListener('click', myfunction, false);

  • In the above format, you start by adding the method to the Document object. 
  • In the parentheses, list the event listener but without the on. (In this example, the event listener is onclick, which is shortened to click.
  • You then add the function to run. (The function is declared elsewhere.) 
  • The false refers to an advanced, rarely used parameter for event handling.

Click event:

  • The onclick attribute fires on a mouse click on the element.
  • This is the most frequently used event type which occurs when a user clicks the left button of his mouse. 
  • You can put your validation, warning etc.
Example:

    <body>
    <div id="displayDiv">
    userName : <input type="text" id="userName">
    </div>
    <div>
    password : <input type="password" id="userName">
    </div>
    <div>
    <button id="loginButton"  onclick="validateLogin()">Login</button>
    </div>
    <script>
    function validateLogin(){
    var userValue =        document.getElementById("userName").value;
    if(userValue == ""){
    alert("user name is required");
    }
    }
    </script>   
    </body>   

  • The output of the above file will display like below,


Some of the DOM events occurs when you work with the events are,

  • When a user clicks the mouse
  • When a web page has loaded
  • When an image has been loaded
  • When the mouse moves over an element
  • When an input field is changed
  • When an HTML form is submitted
  • When a user strokes a key

Onchange event:

  • The onchange attribute fires the moment when the value of the element is changed.
  • Execute a JavaScript when a user changes the selected option of a <select> element.
  • It's fired for <input>, <select>, and <textarea> elements when a change to the element's value is committed by the user. 
  • Unlike the input event, the change event is not necessarily fired for each change to an element's value.
  • This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed. 
  • The other difference is that the onchange event also works on <select> elements.


Example:

<label>Choose ur favourite language:
<select id="favlang" name="favlang">
<option value="">Select One …</option>
<option value="javascript">javascript</option>
<option value="php">php</option>
<option value="ASP.net">ASP.net</option>
</select>
</label>
<p id="demo"></p>
<script>
document.addEventListener('DOMContentLoaded',function()document.querySelector('select[name="favlang"]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
if(!event.target.value) alert('Please Select One');
else alert('You like ' + event.target.value + ' as ur fav lang.'); 
var x = document.getElementById("favlang").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>       

  • The output of the above code will display the output like below,


OnKeypress event:

  • The keypress event is fired when a key that produces a character value is pressed down. 
  • The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers.

  • To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.
  • The keypress() method triggers the keypress event, or attaches a function to run when a keypress event occurs.
  • Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. 
  • KeyboardEvent objects describe a user interaction with the keyboard. Each event describes a key.

Example:

            <body bgcolor = "lace">    
            <div id="displayDiv">
            userMobile : <input type="text" 
            id="userMobile" onkeypress="allowOnlyNumbers(event)">
            </div>
            <script>
            function allowOnlyNumbers(evt){
            if(evt.keyCode <48 || evt.keyCode >57 ){
            evt.preventDefault();
            } 
            }     
            </script>  
            </body>      

  • The text control wont allow the user to type the text according to the code,


addEventListener:

  • The document.addEventListener() method attaches an event handler to the document.
  • The EventListener interface represents an object that can handle an event dispatched by an EventTarget object.
  • EventListener accepts both a function and an object with a handleEvent() property function. 





Example:

      <body bgcolor = "lace">
       <div id="displayDiv">
       userMobile : <input type="text" id="userMobile">
       </div>
       <script>
document.getElementById("userMobile").addEventListener("keypress",      allowOnlyNumbers)
       function allowOnlyNumbers(evt){
       if(evt.keyCode <48 || evt.keyCode >57 ){
       evt.preventDefault();
       } 
       }     
       </script>  
       </body>       

  • Here, we followed the same example of previous one. Here we add the EventListener in the js section i.e inside the <script>tag.
  • Sometimes it is a good practice to define event listeners inside the script.
  • The addEventListener holds two parameters as, name of the event and event listener.
  • The output of the above code will display in the browser like this,


Mouse events:

  • Events that occur when the mouse interacts with the HTML document belongs to the MouseEvent Object.
  • The MouseEvent interface represents events that occur due to the user interacting with a pointing device (such as a mouse). 
  • Common events using this interface include click, dblclick, mouseup, mousedown.
  • The MouseEvent inherits all the properties and methods from UiEvent and Event Object.





mouse over and mouse out events:

  • Mouseover:
    • The mouseup event is fired when a pointing device button is released over an element.
  • Mouseout:
    • The mousedown event is fired when a pointing device button is pressed on an element.

  body bgcolor = "cyan">
   <div onmouseover="addSomeText(this)" onmouseout="changeText(this)">
   drop some text here...
   </div>
   <script>
   function addSomeText(currentElement){
   currentElement.innerText = "Welcome to Hover";
   }
   function changeText(currentElement){
   currentElement.innerText = "you have moved from the div element";
   }</script>
   </body> 


  • When the mouse pointer is over the text,


  • When the user moves the mouse pointer out of the text,


Window.onload:

  • The onload event occurs when an object has been loaded.
  • onload is most often used within the <body> element to execute a script once a web page has completely loaded all content.
  • By default, it is fired when the entire page loads, including its content (images, css, scripts, etc.)
  • In some browsers it now takes over the role of document.onload and fires when the DOM is ready as well.
  • When we want to execute the some code or function which is defined in the script once the html document is loaded mean all the dom has been initialized.

We use to access the elements,

  • To fetch the values
  • Set the values
  • Attach the events
  • Set styles

Examples:

<body bgcolor = "cyan">
<div id="displayDiv">
userMobile : <input type="text" id="userMobile">
</div>
<script>
window.onload = function() {
alert("hello!");
document.getElementById("userMobile").addEventListener("keypress",      allowOnlyNumbers)
function allowOnlyNumbers(evt){
if(evt.keyCode <48 || evt.keyCode >57 ){
evt.preventDefault();
}}}
</script>   
</body>          

event.preventDefault:

  • The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.
  • The preventDefault() method prevents the browser from executing the default action.
  • You can use the method isDefaultPrevented to know whether this method was ever called (on that event object).
  • The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. 
  • Here, in our code we use the preventDefault() method to prevent the key pressed as non numerals as inputs.







  • When the page loads the first thing will display as alert message before the text box come.


  • After that the text box will appear and it won’t accept the characters.

JSON: [ JavaScript Object Notation ]

  • JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange format. 
  • The JSON format was originally specified by Douglas Crockford, and is described in RFC 4627. The official Internet media type for JSON is application/json. The JSON filename extension is .json. 
  • It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language.
  • JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. 
  • These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

  1. A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

  1. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.


JSON.Stringify:

  • The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values.
  • If a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Example:

<bodY>
<script>
var emp = {name:'willy', age:28, salary:37000};
var empJSON = JSON.stringify(emp);
console.log(emp);
</script>
</bodY>

  • In the console window, you can parse the emp.JSON file and you can access the data within it.


CONSTRUCTOR FUNCTION:

  • It is class kind of code used in the before ES6 version of the Javascript.
  • A constructor is useful when you want to create multiple similar objects with the same properties and methods. 
  • It’s a convention to capitalize the name of constructors to distinguish them from regular functions. 
  • The function statement is not the only way to define a new function. you can define your function dynamically using Function() constructor along with the new operator.
Example:

    <body>
    <script>
    function BankAccount(accountName1,accountNumber1){
    this.accountName = accountName1;
    this.accountNumber = accountNumber1;
    this.balance = 1000;
    }
    var johnAccount = new BankAccount("john",100);
    console.log(johnAccount.balance);
    console.log(johnAccount.accountNumber);
    </script>
     </body>

  • ‘this’ refers to the new object.
  • The new keyword it assigns the received parameters to the name and account number property of the current instance. 
  • so the constructor can be used to create objects with initialized name and account number properties.
  • The output of the above file will be dispalyed in the browser like below,


Constructor functions with methods:

  • If we declare function with in the constructor function , then it is called as Member function.
  • If we declare a variable inside a constructor function , then it is called as member variable.

Example:

    <body>
     <script>
     function BankAccount(name,number){
     this.accountName = name;
     this.accountNumber= number;
     this.balance = 1000;
     this.deposit = function (amount){
     try {
     this.balance = this.balance + amount;
     } catch (error) {
     console.error("unable to update the balance");  
     }
     this.withDraw = function(amount){
     this.balance = this.balance - amount;
     }
     }
     }
     var johnAccount = new BankAccount("john",101);
     console.log(johnAccount.balance);
     johnAccount.deposit(2000);
     console.log(johnAccount.balance);
     </script>
     </body>

  • The output of the above file will display in the browser like below,


PROTOTYPE:

  • Prototype is a special object which is assigned as property of any function you make in JavaScript.
  • When a function is created in JavaScript, JavaScript engine adds a prototype property to the function. 
  • This prototype property is an object that has a constructor property by default. 
  • constructor property points back to the function on which prototype object is a property. 
  • We can access the function’s prototype property using the syntax functionName.prototype.
  • In Javascript Prototype is nothing but the secondary blueprint of the Construction function.

Example:

<body>
<script>
function BankAccount(name, number){
this.accountName = name;
this.accountNumber = number;
this.balance = 1000;
this.deposit = function(amount){
this.balance = this.balance + amount;
}
}
BankAccount.prototype.withDraw = function(amount){
this.balance = this.balance - amount;
}
var johnAccount = new BankAccount('john', 101);
johnAccount.withDraw(500);
console.log(johnAccount.balance);
johnAccount.deposit(2000);
console.log(johnAccount.balance);
</script>
</body>

  • The  output of the above file will be displayed in the browser like below,


Advantage:

  • Advantage of using prototypes is there will be only one copy of the method even if you create 100 objects, where as if we define the method in constructor function for each object there will be a copy of the method.

Lets assume that we have below accounts 
  • John
  • Kevin
  • David

Picture representation:






Another usage of prototype:

  • Here we have a built in array property named as middleElement, instead of positioning the array element.
  • There are lot of methods for the array in javascript.But, threre is no method called middleElement in javascript.
  • We want to find middle elements in all the array, for that we can extend the array  functionalities
  • Here,we use prototype which is secondary blueprint from where we can add our own method called as middleElement and it should contain a function which has a index. 
  • From the index we need to calculate the length which was divided by two to give the mean element in the array.

Example:

    <body>
    <script>
    Array.prototype.middleElement = function(){
    let middleIndex = this.length/2 +1;
    return this[middleIndex];
    }
    var fruits = ['apple','mango','banana','cranberry','chikoo','jack-fruit'];
    var vegetables=['tomoto','chikoo','cranberry','chilli','aloo','jack-fruit'];
    var x = fruits.middleElement();
    var z = vegetables.middleElement();
    console.log(x);
    console.log(z);
    </script> 
    </body>

  • Here, we will show the element which is  next to the middle element because len/2 will return the middle element. len/2 + 1 will add one more position to  the right of the array.




Comments

Popular posts from this blog

Javascript For Beginners

Destructuring Assignment in ES6- Arrays