DEV Community

Cover image for JavaScript Variables
Lena
Lena

Posted on • Originally published at Medium

JavaScript Variables

They allow you to store data values in them for future use. Think about it this way, the variable is like a container where you can put a fruit. In the blue container, you can place an apple; in the yellow container, you can place an orange. When you need to find your orange, you refer to the yellow container.

Variables in JavaScript are declared using var, let or const.

var num;
let num1;
const num2; //Error. It must be initialized
Enter fullscreen mode Exit fullscreen mode

The assignment operator = is used to give the variable a value. Note = does not mean equal to as in arithmetic.

The semicolon (;) is used in JavaScript like a sentence’s full stop (.). Did you see what I did there? 🙂

It indicates the end of that line of code. The code will run without the semicolon, but it is standard practice to include it.

The keyword var was used before 2015, and coding for older browsers

var x;
x = 1;
var y = 3;
var num = 100;
Enter fullscreen mode Exit fullscreen mode

Variables can also be declared using a newer convention introduced in 2015, let and const

The keyword let is used if the value is likely to change.

let x;
x = 2;
let y = 24;
let num1 = 120;
Enter fullscreen mode Exit fullscreen mode

The advisable method to declare a variable is using the keyword const. In this case, the value does not change.

const a = 3;
const b = 5;
const num2 = 150;
Enter fullscreen mode Exit fullscreen mode

If you try to change the value of num2, it would result in an error.

num2 = 200 // Error
Enter fullscreen mode Exit fullscreen mode

More than one variable can be declared on the same line of code.

let x = 1; y = 2; z = 3;
Enter fullscreen mode Exit fullscreen mode

Alternatively, it can be written as such

let x, y, z;
x = 1;
y = 2;
z = 3;
Enter fullscreen mode Exit fullscreen mode

Variable names can be simple or more elaborate. Ideally, they should be descriptive. It should describe the value stored in it. For example, if you want to store the price of an apple in a variable. Instead of declaring it as x, which is ambiguous.

const x = 1;
Enter fullscreen mode Exit fullscreen mode

Use

const price = 1;
Enter fullscreen mode Exit fullscreen mode

Even better

const priceOfApple = 1; // The variable is written in camelCase
Enter fullscreen mode Exit fullscreen mode

Variables can store numbers, characters, strings or Boolean values. We will talk about these in the future. Let’s take a look at some more examples.

const firstName = 'John'; // String
let age = 24; // Integer
const loggedIn = true; // Boolean
Enter fullscreen mode Exit fullscreen mode

Rules for naming variables:

  1. They must start with a letter, an underscore (_) or the dollar sign ($)
  2. They cannot begin with a number.
  3. They are case-sensitive; A is not the same variable as a.
  4. JavaScript uses camelCase.

Top comments (0)