--> Sayadasite: Variables in Javascript

Multiple Ads

Search

Menu Bar

Variables in Javascript

Client side Java script Server side Java script Data types  variables Operators  Expressions  Functions  Objects  Array  Date and math related objects Document objectmodel Event handling

Variables

In JavaScript, variables are named containers for storing data values. They allow you to store, retrieve and manipulate information within your programs. A variable is like a container that holds data that can be reused or updated later in the program. Variables are declared using the keywords var, let, or const.

1. var Keyword

The var keyword is used to declare a variable. It has a function-scoped or globally-scoped behaviour.

var n = 5;

console.log(n); (statement in JavaScript is used to output the value of the variable n to the console.)

​var n = 20; // reassigning is allowed

console.log(n);

Output

5

20

var x = 5;
var y = 6;
var z = x + y;

Output (The value of z is 11)

2. let Keyword

The let keyword is introduced in ES6, has block scope and cannot be re-declared in the same scope.

let  n= 10;

n = 20; // Value can be updated

// let n = 15; //cannot redeclare

console.log(n)

Output

20

let x = 5;

let y = 6;

let z = x + y;

Output

The value of z is 11

3. const Keyword

The const keyword declares variables that cannot be reassigned. It's block-scoped as well.

const n = 100;

// n = 200; This will throw an error

console.log(n)

Output

100

const x = 5;
const y = 6;
const z = x + y;

Output

The value of z is 11

Some more declarations

Example

const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';

You can declare many variables in one statement.

Start the statement with let or const and separate the variables by comma:

Example

let person = "John Doe", carName = "Volvo", price = 200;


No comments: