DEV Community

ajidk
ajidk

Posted on

Javascript Variable

4 ways to Declare a Javascript Variable:

  • using var
  • using let
  • using const
  • using nothing

What are Variables?

Variable are container for storing data

example:

var x = 5;
var y = 6;
var z = x + y;
Enter fullscreen mode Exit fullscreen mode

When to Use JavaScript var?

Always declare Javascript variables with var,let or const.
the var keyword is used in all JavaScript code from 1995 to 2015.
the let and const keywords were added to JavaScript in 2015.
if you want your code to run in older browser, you must use var.

When to Use JavaScript const?

if you want a general rules: always declare variables with const.
if you think the value of the variable can change, use let.
in this example, price1,price2, anda total, are variables:

const price1 = 10;
const price2 = 20;
let total = price1 + price2; //30
Enter fullscreen mode Exit fullscreen mode

noted: the two variables price1 and price2 are declared with the const keyword. there are constant values and cannot changed. the variable total is declared with the let keyword.

JavaScript Identifiers

All JavaScript variables mus be identified with unique names.
The general rules for constructing names for variables are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letters.
  • Names can also begin with $ and _.
  • names are case sensitive(a and A different variables).
  • reserved words cannot be used as names.

The Assignment operator

In JavaScript, the equal sign(=) is an assigment operator, not an equal to operator.

s = s + 16
Enter fullscreen mode Exit fullscreen mode

Declaring a JavaScript Variable

You can declare a JavaScript variable with the var or the let keyword:

var carName;
or
let carName;
Enter fullscreen mode Exit fullscreen mode

One Statement, Many Variables

let name='aji', lastName='dk',address:'Indonesia'
Enter fullscreen mode Exit fullscreen mode

Value = undefined

A variable declared without a value will have the value undefined.

Discussion (0)