DEV Community

Santhosh Kumar
Santhosh Kumar

Posted on

JAVASCRIPT VARIABLES

This post was originally published on my blog, find original post here

Variables are core part of JavaScript like every programming language , They let you store information to be referenced and manipulated .

What is a variable ?

A variable is simply a place or more like a container that hold information.
We need to label the information with a descriptive name, so our program could be understood more clearly by the reader. we can modify, replace or delete the information in a variable by its name.

To create(define or declare) a variable, use let keyword.

let firstName;

when we assign or store the information, we use the = keyword

let firstName;
firstName = "Deepak"; // store the string 

we use camelCase while naming the variable

In single line, we can declare and assign a value to a variable

let firstName = "Deepak";

we can also declare multiple variables at once in a single statement

let firstName = "Deepak", lastName = "Kumar"; // multiple assignments

You can use any unicode character in a variable name. You can even use emoji as variable name 🎉

let \u1f60b1 = "iPhone";

It is not recommended to use emoji as identifier

We can also copy data from one variable to another

let firstName = "Deepak";
let firstName2 = "Suriya";
firstName = firstName2;

Variable naming

  • Variables must be identified with unique names.
  • Names can contain letters, digits, underscores, and dollar signs.
  • Reserved like let can not be used as variable name.
  • Variable names are case sensitive.

country and Country are different variables

  • Variable names must begin with letters.
    • Variable names can also begin with $ and _.
let $ = 4; // 4
let _ = $ + 1; // 5

Constants

Variable declared with let can be changed or reassigned later. Sometimes you don't want your variable to be changed like PORT number of your server. Once const is initialized, its value can never be changed again. An attempt to do so would cause an error.

const PORT = 1313; // declare a constant

constants are named using capital letters and underscores.

const IP_ADDRESS = '127.0.0.1';
const WHITE_COLOR = '#ffffff';

Constants can also used as aliases for difficult to remember values like color codes.

Using var

var also declares a variable like let. You can find the var in old scripts.

var score = 10;

var is slightly different from let. We will cover the differences later.

Top comments (0)