Search This Blog
This blog is about Programming. You will find all the concepts with it's example. You can find example of different functions with it's explanation.
Featured
- Get link
- X
- Other Apps
Javascript Variables and Constants
Variables in JavaScript is used to store values. Variables hold the values which later on going to be used in program.
In JavaScript, you can declare variables using these 3 keywords : var, let and const. Below are the examples of how you can declare variables with var, let and const keywords.
Declare variable with var keyword :
var x = 5;
let x = 5;
const x = 5;
Variables you have declared with const will have a fixed value. Once declared and assigned, you cannot alter the value of the variable in later stage.
Variables declared with var keyword is having scope of throughout of program. Which means if you have declared any variable with var keyword then it will be accessible at all places in the program (will see example for the same in upcoming tutorials)
Variables declared with let keyword is having limited scope that is block scope. The variable which is declared with let keyword can only be accessible within which it is declared. Refer to the below example for better clarity.
function fun() { let x = 5; console.log(x); } fun(); console.log(x);
const x = 5; x = 10; // this will give you error
You can change the value of variables which are declared with let and var keyword after the declaration.
You must have to assign value at the time declaration of constant as you cannot assign value at later stage.
There are some rules for declaring variables in JavaScript :
- The variable name must starts with alphabet or an underscore(_) or dollar sign ($). Variable names cannot start with a number.
let x = 5; // valid let _x = 5; //valid let $x = 5; // valid
- You cannot use keywords as variable name in JavaScript.
let var = 5; // Invalid let function = 5; // Invalid
- JavaScript is a case-sensitive language. This means variables with different cases will be treated as separate variables.
let x = 5; let X = 5; // These both variables are different
Popular Posts
JavaScript : Get Started with JavaScript
- Get link
- X
- Other Apps
Comments
Post a Comment