Skip to main content
Published on

Variables and Types in JavaScript

Share:

Introduction

Understanding variables and types is essential for any JavaScript developer. This guide will give you a clear understanding of how JavaScript handles variables and the various types available in the language.

Variables in JavaScript

Variables are containers for storing data. In JavaScript, they can be declared using var, let, or const.

var

var is the oldest way to declare variables in JavaScript, but it has some limitations, such as function scope and hoisting.

var name = 'John';

let

let was introduced in ES6 (ECMAScript 2015) and addresses some of the issues with var, mainly related to block scope.

let age = 30;

const

const is also an ES6 addition and is used to declare constants. Once a value is assigned to a constant, it cannot be changed.

const API_URL = 'https://api.example.com';

Data Types in JavaScript

JavaScript is a dynamically typed language, which means variables can store different types and can change type.

Primitive Types

  1. String: To represent textual data.
let greeting = 'Hello, world!';
  1. Number: To represent numbers (integers or floating-point).
let height = 1.76;
  1. Boolean: Represents a logical entity with two values: true or false.
let isRaining = false;
  1. Undefined: A variable with no assigned value.
let notDefined;
  1. Null: Represents the intentional absence of a value.
let empty = null;
  1. Symbol: Introduced in ES6, creates unique and immutable values.
let symbol = Symbol();
  1. BigInt: For very large integers.
let bigNumber = 9007199254740991n;

Object Types

In addition to primitive types, we have object. In JavaScript, objects are collections of properties.

let person = {
  name: 'Ann',
  age: 25,
};

Arrays

Arrays in JavaScript are used to store multiple values in a single variable.

let fruits = ['Apple', 'Banana', 'Orange'];

Type Conversion

JavaScript is a loosely typed language, which means automatic type conversions occur.

let number = '5';
let sum = number + 10; // '510', not 15

Conclusion

Understanding variables and types is fundamental to programming in JavaScript. With this knowledge, you are better prepared to explore the nuances of the language and start building more complex and efficient programs.

Happy coding!