JavaScript variables and data types are two fundamental concepts that you’ll have to learn about before proceeding with your programming journey. A variable in Javascript is a container that holds a value inside of it. You can have many named containers, each of which contains a different value. You can then manipulate these named containers and their values within your code to achieve a certain goal. Variables are crucial as they allow you to store data, manipulate it, and reference it elsewhere in your script.

3 ways to declare and use variables

In JavaScript, you can declare variables in three ways: automatically, using var, or using let.

Declaring variables automatically

In Javascript, variables can be assumed right away without explicitly declaring them. So you can just write:

x = 1;
y = 2;
console.log(x + y) // Output: 3

This is considered the least favorable way to use variables because it gives no clarity about when a variable was first created as opposed to when it’s used later in the code. It creates variables that are globally scoped no matter where they are declared. And it opens up the door to errors caused by typos in the variable names.
In most modern environments, the above code will even throw an error and will not be interpreted.

Declaring variables with var

The var keyword is function-scoped. This means that if a variable is declared inside a function using the var keyword, it can only be accessed within that function. It can also be reassigned and redeclared within its scope. Here’s an example:

function exampleFunction() {
  var x = 2;
  console.log(x); // Output: 2
  x = 3;
  console.log(x); // Output: 3
  var x = 4;
  console.log(x); // Output: 4
}
console.log(x); // Output: Error! x is not defined

Declaring variables with let

Then we have let, which was introduced in ES6. It’s block-scoped, meaning it exists only within the block where it is declared.

The let keyword works similarly to var, but it doesn’t allow you to redeclare variables. You can, however, reassign new values to them. Here’s how you can use let:

function exampleFunction() {
  let x = 2;
  console.log(x); // Output: 2
  x = 3;
  console.log(x); // Output: 3
  let x = 4;      // Error! x is already declared.
  console.log(x); 
}
console.log(x); // Output: Error! x is not defined

The let keyword is currently the recommended way to declare variables in Javascript.

If you want more insights into how variable scopes work, I wrote a separate post about Javascript variable scopes.

What are Javascript constants?

You will face numerous cases where you would like to declare a variable but you don’t intend to change its value later on. Maybe you’re defining a mathematical constant like π (PI). You would want to use a constant instead of a variable in these cases. Here’s an example of how const works:

const pi = 3.14159265359;
console.log(pi); // Output: 3.14159265359
pi = 4; // Output: Error! Assignment to constant.

While you can technically use a normal variable to store constant values, JavaScript constants give you better code readability and security. So it’s recommended to use constants whenever you’re defining values that you do not intend to change.

Understanding Data Types in JavaScript

Data types define the kind of data that a variable can hold. JavaScript is a loosely typed language (also called dynamically typed), meaning that you don’t have to specify the type of data that the variable will hold and the same variable can be used to hold different data types at different stages of the code. There are two categories of data types in JavaScript: primitive and non-primitive.

Primitive Data Types in JavaScript

Primitive data types are types that allow you to store a single value inside of them.

  • String is used to store data in the form of text.
  • Number can be used to store both integers and floating-point numbers.
  • Boolean stores a logical entity and can have two values: true or false.
  • Null has one value: null, representing no value or no object.
  • Undefined means a variable has been declared but has not yet been assigned a value.
  • Symbol is a unique and immutable data type that is often used as an identifier for object properties.

Non-primitive Data Types in JavaScript

Unlike primitive data types, non-primitive types can be used to store multiple values inside of them.

  • Object: An object is an entity that has properties and values. Here’s an example of how to create and use an object in JavaScript:
// Create an object
let car = {
  make: 'Toyota',
  model: 'Corolla',
  year: 2020,
  color: 'blue'
};

// Access properties of the object
console.log(car.make); // Output: Toyota
console.log(car.year); // Output: 2020

// Modify a property of the object
car.year = 2022;
console.log(car.year); // Output: 2022

// Add a new property to the object
car.price = 20000;
console.log(car.price); // Output: 20000

// Delete a property from the object
delete car.color;
console.log(car.color); // Output: undefined
  • Array: An array can hold a group of values in a specific order. It usually holds values of the same type (strings, numbers..) but it can also hold a combination of value types.
// Create an array
let fruits = ['Apple', 'Banana', 'Cherry'];

// Access elements of the array
console.log(fruits[0]); // Output: Apple
console.log(fruits[1]); // Output: Banana
console.log(fruits[2]); // Output: Cherry

// Modify an element of the array
fruits[1] = 'Blueberry';
console.log(fruits[1]); // Output: Blueberry

// Add a new element to the array
fruits.push('Durian');
console.log(fruits); // Output: [ 'Apple', 'Blueberry', 'Cherry', 'Durian' ]

// Delete an element from the array
fruits.splice(1, 1);
console.log(fruits); // Output: [ 'Apple', 'Cherry', 'Durian' ]

// Get the length of the array
console.log(fruits.length); // Output: 3

Javascript also has a whole host of functions to do all sorts of magic with arrays. Functions like join() , pop() , shift() and many more. But this is a topic of its own.

Type Conversion in Javascript

In Javascript, you can use type conversion (also called type casting) to convert one data type to another. Type conversions can be either implicit (done by JavaScript automatically) or explicit (done by you intentionally).

Here are some examples of type conversions in JavaScript:

  1. String to Number: You can convert a string to a number using the Number() function. If the string cannot be converted into a number, it will return NaN (Not a Number).
let str = "123";
let num = Number(str); 
console.log(num); // Output: 123
  1. Number to String: You can convert a number to a string using the String() function.
let num = 123;
let str = String(num);
console.log(str); // Output: "123"
  1. Boolean to String: You can convert a boolean to a string using the String() function.
let bool = true;
let str = String(bool);
console.log(str); // Output: "true"
  1. Implicit Conversion: JavaScript automatically converts types in certain situations. For example, when you try to concatenate a string and a number, the number is implicitly converted to a string.
let num = 123;
let str = "Hello ";
console.log(str + num); // Output: "Hello 123"

As you can see, Javascript data types are very flexible. Variables can hold values of any type and these values can be automatically converted between types as needed.

Final Notes

Properly understanding Javascript variables and data types, and how to use them together, is fundamental to becoming proficient in Javascript, and in any programming language for that matter. Before proceeding with more advanced concepts in Javascript, make sure you have a robust understanding of variables and data types first. And don’t forget to apply everything you learn through coding!

For more information, you can check Mozzila Javascript Guide which covers all aspects of Javascript.

Similar Posts