Saturday 4 July 2020

Variables in javascript | Declaring a variable - Online help

In this post, we are going to talk about what is variables in javascript? and how to declare the variables in javascript. So stay tuned till the end and let's get started.

Variable in Javascript:

A variable in javascript is a name assigned to the computer memory location to store data. As the name suggests, the value of the variable can vary, as the program runs. Before you use a variable in a JavaScript program, you must declare it.  Variables are declared with the var keyword.


Variables in javascript | Declaring a variable - Online help


Rules for variable names:

  • They must begin with a letter, digit, or underscore character.
  • We can’t use spaces in names.
  • Variable names are case sensitive.
  • We can’t use a reserved word as a variable name.


Declaring JavaScript variable:

To declare the variable using the var keyword. You can declare one variable at a time or more than one. You can also assign values to the variables at the time you declare them.


Different methods of declaring JavaScript variables:

//declaring one JavaScript variable

var firstname;


//declaring multiple JavaScript variables

var firstname, lastname;


//declaring and assigning one JavaScript variable

var firstname= ’homer’;


//declaring and assigning multiple JavaScript variable

var firstname= ’homer’, lastname= ’simpson’;


JavaScript variable scope:

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

  • Global variables:  A global variable has a global scope which means it is defined everywhere in the JavaScript code.
  • Local variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to the function.

Within the body of a function, a local variable takes precedence over a global variable with the same name. if you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. The following example explains it:

<script type= “text/javascript”>
<!—
Var myvar=”global”; // declare a global variable
Function checkscope()
{
Var myvar=”local”; //declare a local variable 
Document.write(myvar);
}
//-->
</script>

This produces the following result:
local

I hope you guys understand what is variables in javascript. If you find any mistake or having any queries then please comment down below. Thank you for reading.


Recommended post:



No comments:

Post a Comment