Friday, 8 December 2017

JavaScript | Scope and Events in JavaScript

Scope in JavaScript
The scope defines the accessibility of a variable, objects, and function. It is nothing but the boundary line.

There are only two types of scope:
1. Local Scope
2. Global Scope


Local Scope
It defines that something is only accessible in a limited scope. When you declare a variable within the function, it becomes local to that function. It's not accessible to the other functions or outside the function.

Example
<!DOCTYPE html> 
<html> 
<title>Scope in JavaScript</title> 
 
<head></head> 
 
<body> 
    <script language='javascript'>
        printName();
        document.write("<br>Outside the function<br>"); 
        //cannot access the name variable to outside  
        document.write("My name is " + name); 
        document.write(); 
 
        function printName() { 
            //local variable declaration means local scope  
            var name = "Algos"; 
            document.write("Inside the function<br>");
            document.write("My name is " + name); 
        } 
    </script> 
</body> 
</html>

Output
Inside the function
My name is Algos
Outside the function
My name is


Global Scope
It can be accessible to the other functions, as it becomes global to all. You can access it within the function. It is defined anywhere in your JavaScript code.

Example
<!DOCTYPE html> 
<html> 
<title>Scope in JavaScript</title> 
<head></head> 
<body> 
    <script language='javascript'> 
        document.write("Global Scope in JavaScript</br>"); 
        //global variabe declaration  
        var name = "Algos"; //it can be accessible to all within JavaScript code  
        printName(); 
 
        function printName() { 
            //access the test variable,  
            //it can be accessible because it is global in scope  
            document.write("My Name is " + name); 
        } 
    </script> 
</body> 
</html> 

Output
Global Scope in JavaScript
My Name is Algos


Events in JavaScript
All the objects have properties and methods. Some objects also have "events". Every element on a Web page has certain events that can trigger invocation of the event handlers. The "event handler" is a command that is used to specify the actions in response to an event. Attributes are inserted into HTML tags to define the events and event handlers.

Different types of events are listed below:
1. Mouse click event.
2. Web page or an image loading.
3. Moussing over a hot spot on the web page.
4. Selecting an input box in an HTML form.
5. Submitting an HTML form.
6. Keystroke.

Example: onclick event
<!DOCTYPE html> 
<html>
<head>onlcick event example</head> 
    <body> <button onclick="clickme()">Click me</button> 
        <script language='javascript'> 
            function clickme() { 
                alert("onclick Event of Button"); 
            } 
        </script> 
    </body> 
</html> 


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...