Variable in Javascript

In JavaScript, a variable is a container that holds data or values that can be used and manipulated within your code. Variables are a fundamental concept in programming and are used to store, retrieve, and update information.

Variable in javascript definition:

A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript : local variable and global variable. There are some rules while declaring a JavaScript variable (also known as identifiers). Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.

Here are the basic ways to declare variables in JavaScript:

  1. Using var (older way):
    • var was the original way to declare variables in JavaScript.
    • Variables declared with var are function-scoped, meaning they are only accessible within the function where they are declared, or globally if declared outside of any function.
    • Example:javascriptCopy codevar myVar = 10;
  2. Using let (introduced in ECMAScript 2015, ES6):
    • let allows you to declare block-scoped variables, which means they are limited to the block or statement in which they are declared.
    • Example:javascriptCopy codelet myVar = 10;
  3. Using const (introduced in ECMAScript 2015, ES6):
    • const is used to declare variables that should not be reassigned once they are assigned a value. It is also block-scoped.
    • Example:javascriptCopy codeconst pi = 3.14159;

Here are some important points to keep in mind when working with variables in JavaScript:

  • Variable names (identifiers) are case-sensitive.
  • Variable names can consist of letters, numbers, underscores, and dollar signs but must start with a letter, underscore, or dollar sign.
  • JavaScript has a few reserved words (e.g., if, else, while, function) that cannot be used as variable names.
  • Variables can hold different data types, such as numbers, strings, arrays, objects, functions, and more.
  • You can reassign a value to a variable declared with let, but you cannot reassign a value to a variable declared with const.
  • It’s good practice to use const by default and only use let when you need to reassign a variable’s value.

Here’s an example of using variables in JavaScript:

javascriptCopy code

let message = "Hello, World!"; console.log(message); // Outputs: Hello, World! message = "Welcome to JavaScript"; console.log(message); // Outputs: Welcome to JavaScript

This code declares a variable message, assigns a string value to it, and then logs the value to the console. Later, it reassigns a new value to the message variable.

Javascript training in hyderabad


Enquiry Now
close slider
Scroll to Top
Call Now Button