Variables and Constants

Vlad O.

Updated:

Fundamentals of variables in JavaScript, how they work, their scope, and best practices for using them in your code. Whether you are a beginner or an experienced developer, this guide will provide you with valuable insights into working with JavaScript variables.

What are Variables in JavaScript?

In JavaScript, variables are containers that hold data. They are used to store various types of information, such as numbers, strings, objects, or functions, which can be used and manipulated throughout your code. Variables act as labels for values and enable you to reference and modify data dynamically, making them a foundational concept in programming.

Declaring and Assigning Variables

To declare a variable in JavaScript, you use the ‘var’, ‘let’, or ‘const’ keyword followed by the variable name. For example:

var age;
let username;
const pi = 3.14;

Variables declared with ‘var’ have function scope, while variables declared with ‘let’ and ‘const’ have block scope. The value of a variable can be assigned using the assignment operator ‘=’. For example:

id = 1; // the same as 'var id=1;'
var age = 30;
let username = 'John';
const pi = 3.14;

Understanding Scope

The scope of a variable determines where in your code it can be accessed. Variables declared with ‘var’ are function-scoped, meaning they are accessible within the function they are declared in. On the other hand, variables declared with ‘let’ and ‘const’ are block-scoped, meaning they are accessible within the block (a pair of curly braces) they are declared in.

Keywords and Best Practices

It is essential to choose the right keywords when declaring variables. Use ‘var’ when you need function scope, ‘let’ when you need block scope and plan to reassign the variable, and ‘const’ when you need block scope and do not intend to reassign the variable.

Examples

Let’s see some examples of using variables in JavaScript:

// Using var
function exampleVar() {
  if (true) {
    var x = 10;
  }
  console.log(x); // Output: 10
}
// Using let
function exampleLet() {
  if (true) {
    let y = 20;
  }
  console.log(y); // Error: y is not defined
}

// Using const
function exampleConst() {
  const z = 30;
  console.log(z); // Output: 30
}
Posted in Javascript tagged as es6