- The JavaScript this Keyword
- Note
- this in a Method
- this Alone
- Example
- Example
- this in a Function (Default)
- Example
- this in a Function (Strict)
- Example
- this in Event Handlers
- Example
- Object Method Binding
- Example
- Example
- Explicit Function Binding
- See Also:
- Example
- Function Borrowing
- Example
- This Precedence
- Local Variable in JavaScript
- Examples of Local Variable in JavaScript
- Example #1
- Example #2
- Example #3
- Example #4
- Conclusion
- Recommended Articles
- How to Access & Declare Local Variable in Javascript[With Examples]
- Declare Local Variable in Javascript
- Example of Local Variable in Javascript
- How to Access Local Variable in Javascript
- how to Access Local Variable Outside Function in Javascript
- Difference Between Local and Global Variable in Javascript
- About
- Recent Posts
The JavaScript this Keyword
In JavaScript, the this keyword refers to an object.
Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:
In an object method, this refers to the object. |
Alone, this refers to the global object. |
In a function, this refers to the global object. |
In a function, in strict mode, this is undefined . |
In an event, this refers to the element that received the event. |
Methods like call() , apply() , and bind() can refer this to any object. |
Note
this in a Method
When used in an object method, this refers to the object.
In the example on top of this page, this refers to the person object.
Because the fullName method is a method of the person object.
this Alone
When used alone, this refers to the global object.
Because this is running in the global scope.
In a browser window the global object is [object Window] :
Example
In strict mode, when used alone, this also refers to the global object:
Example
this in a Function (Default)
In a function, the global object is the default binding for this .
In a browser window the global object is [object Window] :
Example
this in a Function (Strict)
JavaScript strict mode does not allow default binding.
So, when used in a function, in strict mode, this is undefined .
Example
this in Event Handlers
In HTML event handlers, this refers to the HTML element that received the event:
Example
Object Method Binding
In these examples, this is the person object:
Example
const person = firstName : «John»,
lastName : «Doe»,
id : 5566,
myFunction : function() return this;
>
>;
Example
const person = firstName: «John»,
lastName : «Doe»,
id : 5566,
fullName : function() return this.firstName + » » + this.lastName;
>
>;
i.e. this.firstName is the firstName property of this (the person object).
Explicit Function Binding
The call() and apply() methods are predefined JavaScript methods.
They can both be used to call an object method with another object as argument.
See Also:
The example below calls person1.fullName with person2 as an argument, this refers to person2, even if fullName is a method of person1:
Example
const person1 = <
fullName: function() <
return this.firstName + » » + this.lastName;
>
>
const person2 = firstName:»John»,
lastName: «Doe»,
>
// Return «John Doe»:
person1.fullName.call(person2);
Function Borrowing
With the bind() method, an object can borrow a method from another object.
This example creates 2 objects (person and member).
The member object borrows the fullname method from the person object:
Example
const person = <
firstName:»John»,
lastName: «Doe»,
fullName: function () <
return this.firstName + » » + this.lastName;
>
>
const member = firstName:»Hege»,
lastName: «Nilsen»,
>
let fullName = person.fullName.bind(member);
This Precedence
To determine which object this refers to; use the following precedence of order.
Precedence | Object |
1 | bind() |
2 | apply() and call() |
3 | Object method |
4 | Global scope |
Is this in a function being called using bind()?
Is this in a function being called using apply()?
Is this in a function being called using call()?
Is this in an object function (method)?
Is this in a function in the global scope.
Local Variable in JavaScript
A local variable in JavaScript is declared inside a block or a function. These variables are accessible within the function or block only. Furthermore, local variables are bound to their value within the local scope only. JavaScript has two types of variables, i.e. Global and Local Variables. Each type of variable works on scoping. Scoping is the one which determines the accessibility of variables. As such, JavaScript variables can hold data or any information which can be changed. In JavaScript, we use the var keyword to declare variables. The two types of variables allow users to program according to their scope.
Web development, programming languages, Software testing & others
Syntax of Local Variable in JavaScript
Syntax of local variables is not so difficult, but this is the one which we use as a programmer in our daily routine.
function sample() < var x = ; //local variable >
Variables which are declared inside a function will be local to that function. Hence, Local variables have a function scope. These can only be accessed within the function scope. As Local variables have scope only to that particular function where it has been declared, variables with the same name can be declared elsewhere in various functions. These local variables are created when the function starts and are deleted when the function gets completed. Inside the body of the function, the local variable takes higher precedence over the global variable with the same names. If the user is going to declare a variable or a function parameter with the same name as that of a global variable, the latter is hidden. These local variables can not be accessed or modified outside functions declaration. Local variables are declared or used for variables that are only needed in a specific class/ module/ sub.
Examples of Local Variable in JavaScript
Given below are the examples of Local Variable in JavaScript:
Example #1
Simple local variable declaration in JavaScript.
Local Variable declaration in JavaScript
Here the variable is declared inside a function and hence is a local variable declaration.
Example #2
Local variable and global variable having the same names.
Local variable having same name as global variable.
So the above example shows some differences between how a global variable is declared and accessed and how a local variable can take in the same name as a global variable and be accessed inside the function scope.
Example #3
How local variables are used for calculating the sum.
Usage of local variables for addition
On clicking on the button:
So these are the values of looping.
Variable a is a global variable and hence can be accessed anywhere, as we have accessed it in a function along with the local variables.
Block Level Scoping: In JavaScript, there are no block-level scoping, i.e. Variables defined in if block can be accessed outside the if block but within the function.
Example #4
Block-level scoping for local variables in JavaScript.
Variable with block level scope
Using these local variables reduces the conflict of naming variables. Such as, two different functions can have the same name of local variables without causing any conflict. It means few errors and few debugging problems. With just less number of exceptions, all the code should be in the form of functions so that all of the variables are local. If the user misspells the variable name that is already declared, it is taken as a new variable. And hence users need to make sure to include keywords when on declaring the new variable and can declare before referring to it in the code.
Many of the time, it is better to use local variables when possible. For example, it is better to use the var keyword to declare a new variable before it being referred to by other statements. If the user forgets to include the var keyword, that particular variable will be considered a global variable, which can cause debugging problems. It is even better to pass the local variables from one function to the other as parameters than to use them as a global variable. This is going to make code understandable with lesser chances of errors.
Conclusion
With this, we shall conclude the article “Local Variable in JavaScript”. We have seen what Local Variable in JavaScript means and its Syntax. We have also seen How Local variables are declared and how they are used in coding. We have also seen an example of the difference between Global and Local variables, which has given us a better idea to decide what type of variable declaration would be better for us as a programmer. We have also checked out an example of Block scoping of a local variable, which JavaScript does not allow inside < >brackets. And a point to remember is that both local variables and global variables can have the same names; it depends upon where these variables have been called over.
Recommended Articles
This is a guide to Local Variable in JavaScript. Here we discuss the introduction and examples of a local variable in JavaScript. You may also have a look at the following articles to learn more –
89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
JAVASCRIPT Course Bundle — 83 Courses in 1 | 18 Mock Tests
343+ Hours of HD Videos
83 Courses
18 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
How to Access & Declare Local Variable in Javascript[With Examples]
Local variables are variables that can only be accessed within the function or block statement that they have been declared in. Block statements include if , if else , while , for and do while .
Declare Local Variable in Javascript
You can use var , let , and const keywords to create local variables within a function.
function functionWithLocalVariable() < var username ="OscarKittyKat"; const name="Oscar Wilden"; let estimatedWorth2022 = 2585000; >functionWithLocalVariable();
If you log the variables inside the function, you will get their values.
function functionWithLocalVariable() < var username ="OscarKittyKat"; const name="Oscar Wilden"; let estimatedWorth2022 = 2585000; console.log(username); console.log(name); console.log(estimatedWorth2022); >functionWithLocalVariable();
These variables cannot be accessed outside the function. A quick check using a console log shows the variable as not defined outside of the function.
function functionWithLocalVariable() < var username ="OscarKittyKat"; const name="Oscar Wilden"; let estimatedWorth2022 = 2585000; >functionWithLocalVariable(); console.log(username); console.log(name); console.log(estimatedWorth2022);
To create local variables within a block, you can use only use let and const keywords. Block scope was introduced in the ES6 Javascript version. You can use the power of block scope with if , if else , while , for and do while statements.
The variables cannot be accessed outside the block. Checking the variable designation using a console log shows the variable as not defined outside the if else block but gives a result of child when read inside the block it is declared in.
var age = 17; if(age <18)< const designation = "Child"; console.log(designation); >else < const designation = "Adult"; console.log(designation); >console.log(designation);
Example of Local Variable in Javascript
Local Variable Within Function and Block Example
function getWordExistInPage() < let totalpages = 2; for(let page=0; pageconsole.log(totalpages); console.log(page); > getWordExistInPage(); console.log(totalpages);
page is a local block scope variable inside for loop while totalpages is a local function scope variable inside function getWordExistInPage .
You can only read the value of page within the for loop while you can only read the value of totalpages inside the function getWordExistInPage .
How to Access Local Variable in Javascript
To get access to local variables in Javascript, you can make a function call within the function that has the variables and pass the variable as a function parameter.
function functionWithLocalVariable() < let localVariable = "I am a local Variable Being passed to another function"; functionThatUsesTheLocalVariable(localVariable); >function functionThatUsesTheLocalVariable(variable) < console.log(variable); >functionWithLocalVariable();
how to Access Local Variable Outside Function in Javascript
You can pass local variable to another function by making the variable the return value of the function.
When you call the function within another function this new function will get the value of the variable.
function functionWithReturnValue() < let independenceYear = 1963; return independenceYear; >function getHowManyYearsSinceIndependence() < let yearsSinceIndependence = 2022 - functionWithReturnValue()); console.log(yearsSinceIndependence); >getHowManyYearsSinceIndependence();
Difference Between Local and Global Variable in Javascript
Global variables can be accessed by any part of you code on that file while local variables can only be accessed by code within the function or block they are declared in.
Hi there! I am Avic Ndugu.
I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.
Front End Developer Newsletter
Receive a monthly Frontend Web Development newsletter.
Never any spam, easily unsubscribe any time.
Start understanding the whole web development field now
Stop all the confusion and start understanding how all the pieces of web development fit together.
Never any spam, easily unsubscribe any time.
About
If you are just starting out you can test the waters by attempting the project-based HTML tutorial for beginners that I made just for you.
Okay, you got me there, I made it because it was fun and I enjoy helping you on your learning journey as well.
You can also use the HTML and CSS projects list as a source of projects to build as you learn HTML, CSS and JavaScript.
Recent Posts
Copyright © 2018 — 2023 DevPractical. All rights reserved.