Javascript Variables
JavaScript variables, often referred to as 'what is variable in javascript', acts as containers that store values that your code can use later. They can hold many types of data, such as numbers, texts, or more complex objects. By using variables, you can label data with a descriptive name, making your code easier to read and manage.
JavaScript Variables
In JavaScript, variables are essential for storing data values. There are four main ways to declare variables.
Automatically
JavaScript allows the automatic or implicit declaration of variables by assigning a value to a name without using var, let, or const. However, this is considered a bad practice because it creates global variables and can lead to unpredictable code behavior.
Example:
Using var
The var keyword was the standard way to declare variables. Variables declared using the var keyword have their scope limited to the function within which they are defined, or they are scoped globally if they are declared outside any function.
Example:
Using let
Introduced in ES6 (ECMAScript 2015), let allows you to declare block-scoped variables, significantly improving code readability and reducing errors related to variable scope.
Example:
Using const
const is utilized for defining variables with values that are intended to remain constant and unchangeable. Similar to let, const also adheres to block-scoping rules.
Example:
When to Use var, let, or const?
Choosing between var, let, or const for variable declaration in JavaScript depends on the variable's intended use and scope. Here's a brief guide on when to use each:
Use var when:
- You need a variable to have function scope or global scope.
- You are working on a codebase where ES6 support is not guaranteed.
- You require hoisting behavior where the variable can be used before it is declared, understanding that it will be undefined until the assignment is reached.
Use let when:
- You need a variable that can change over time.
- You want block-level scope to limit where the variable is accessible, such as within loops or if statements. This can help prevent errors from variable values changing unexpectedly.
- You are working in an environment that supports ES6 features.
Use const when:
- You have a variable whose value should not change once assigned. This helps to prevent bugs and makes your intent clear to anyone reading your code.
- Just like let, you want block-level scope. Use const by default for variables that do not need to be reassigned.
Initializing a Variable
Initializing a variable in JavaScript is a two-step process: declaration and initialization.
To declare a variable, you use the let, var, or const keyword followed by the name you wish to give your variable.
After you have declared a variable, you can initialize that variable with a value.
Now, try writing these lines in the console. After writing these lines, you can write only the variable names and press enter, the output will be the value stored in it.
Note: You can even declare and initialize a variable in a single line. Example:
Updating a Variable
We can update/change the value by just typing the variable name followed by an equals sign and then followed by the new value we want it to store.
Example:
Variable Naming Rules
To declare a Javascript variable, one must know the rules to follow:
Rules are as follows:
- Variables are case-sensitive in Javascript. This means that schoolName and schoolname are considered different variables.
- We can use letters, digits, symbols like dollar sign ($) and underscore ( _ ) in a variable name.
- We cannot start a variable name with a digit (0-9).
- We cannot use any of the reserved keywords (function, return, typeof, break, etc.) of Javascript as a variable name.
Important Points
- Javascript allows multiple white spaces and even line breaks in a declaration of a variable.
- We can separate different variable declarations using a comma.
- In Javascript, we can store any type of value in a variable and also change it any time.
Variable Types
Let's explore Javascript variable types with examples.
Numbers
JavaScript allows you to store both whole numbers (integers) and decimal numbers (floats) in variables. There's no need to declare the type of the variable beforehand; JavaScript dynamically understands the type based on the value assigned to the variable.
Example:
Strings
Strings are sequences of characters used to represent text. They are enclosed in quotes, either single (') or double ("), and can include letters, numbers, and symbols.
Example:
Booleans
Boolean variables can only hold two values: true or false. These are particularly useful for controlling the flow of your program, such as executing code only if a certain condition is met.
Example:
Arrays
An array is a collection of values, which can be of any type, stored in a single variable. Arrays are enclosed in square brackets ([]), and their values are separated by commas. Each item in an array has an index, starting with zero for the first element.
Example:
You can access element of array by its index:
Objects
Objects represent groups of associated data and functions, which are stored as key-value pairs. They are enclosed in curly braces ({}), making it easy to store and access data properties using keys.
Example:
You can reach the properties of an object by employing dot notation:
Dynamic Typing
You might have heard that JavaScript is called "a dynamically typed language". This means that the variable data type is not fixed. A variable can store any type of data, and the user can achieve this without specifying the type of data he/she wants to store(eg: number, string, objects, arrays, etc).
Also, one can change the stored value to any type of data, anytime freely.
Examples:
Try running these lines in console for better understanding.
Constants in JavaScript
You have seen that variables are those, whose values could be changed if required. Now, JavaScript also lets you declare constants. We declare a constant using the keyword const.
Syntax:
These constants are similar to variables but have some properties which are different from variables, such as:
- The constant must be initialized when you declare it, otherwise, it will throw a " SyntaxError: Missing initializer in const declaration ".
- Once assigned a value to a constant, you can’t re-assign values afterward. That is, a value is fixed to a constant.
Example 1:
Example 2:
Note: Though we cannot change the value of the constant, but if the constant value is an object, then we can modify the object's properties.
Example 3:
You can even add, or update or remove properties from a constant object, because you are just changing the details of the object, not the reference. The constant will still point to the same object.
Examples
Example 1: Variables can hold numeric values, including integers and floating-point numbers. These values are directly assigned to variables without quotes.
Example 2: String values are sequences of characters enclosed in quotes. Variables can hold both simple texts and complex strings that include various characters.
Example 3: Boolean variables are used to represent truth values and can either be true or false. They are particularly useful in conditional statements and logic operations.
Example 4: Arrays hold a collection of values, which can be of any type. Every element within an array has an index, beginning with 0.
Example 5: In JavaScript, objects are composed of key-value pairs grouped together. They are a powerful way to structure data and functionality together. Each property or method in an object is accessed by its key name.
Example 6: Variables in JavaScript are not limited to holding values of a single type; they can be reassigned to hold different types of values over their lifecycle.
JavaScript Identifiers
JavaScript identifiers are names given to variables, functions, and other entities to identify them in the code. They must start with a letter, underscore (_), or dollar sign ($), followed by letters, digits, underscores, or dollar signs. Identifiers are case-sensitive and cannot be reserved keywords.
Example:
The Assignment Operator
The assignment operator in JavaScript is the equal sign (=), used to assign values to variables. It takes the value on its right and stores it in the variable on its left.
Example:
JavaScript Data Types
Data types are broadly categorized into primitive types and reference types.
Primitive Types
Primitive types are data that are not objects and have no methods. There are seven primitive data types in JavaScript:
- Number: Represents both integer and floating-point numbers, e.g., 42, 3.14.
- String: Represents textual data, e.g., "Hello, world!".
- Boolean: Represents a logical entity and can have two values: true and false.
- Undefined: Represents a variable that has not been assigned a value, e.g., let a;.
- Null: Represents the intentional absence of any object value.
- Symbol: A unique and immutable primitive value used as the key of an object property.
- BigInt: Represents numbers larger than 2^53 - 1, the largest number JavaScript can reliably represent with the Number type.
Reference Types (Objects)
Reference types refer to objects, which are collections of properties. Unlike primitive types, objects can store multiple values and can be changed over time.
- Object: The base object from which all other objects inherit properties and methods, e.g., { name: "Alice", age: 30 }.
- Array: Used to store multiple values in a single variable, e.g., ['apple', 'banana', 'cherry'].
- Function: Represents code that can be called to perform a specific task, e.g., function greet() { console.log("Hello, world!"); }.
One Statement, Many Variables
In JavaScript, it's possible to declare multiple variables in a single statement, making your code more concise and readable. This is achieved by separating each variable declaration with a comma within the statement. You can use var, let, or const for such declarations, depending on the scope and reassignment needs of the variables being declared.
Example Using let
In this example, three variables of different types are declared and initialized in one line: a string, a number, and a boolean. This method not only saves space but also groups related declarations together, enhancing code readability.
Example Using const
Here, three constants are declared in a single statement. Note that each constant must be initialized at the time of declaration when using const, as their values cannot be reassigned later.
Declaring a JavaScript Variable
One must create JavaScript variables before using it. In programming terms, we call this declaring a variable. In Javascript, variable can be declared using either let, var, or const keywords.
Here we are creating two variables, one using let and another using var. You can even try writing these lines in your web browser's console.
Value = undefined
When you declare a variable without assigning a value to it, JavaScript automatically assigns it the value undefined.
Example:
Here, address is declared but not initialized, so its value is undefined. If you attempt to use a variable that has been declared but not initialized, you will get undefined when trying to access its value. This helps in debugging and understanding the state of variables in your code.
Re-Declaring JavaScript Variables
Re-declaring JavaScript variables using the var keyword can have subtle implications, depending on where and how it is done.
Re-Declaring with var When you re-declare a variable using var, JavaScript does not remove the previous instance of the variable. In the global scope or within the same function scope, re-declaring a variable with var essentially has no effect.
Example:
Re-Declaring with let and const Attempting to re-declare a variable within the same scope using let or const will result in a SyntaxError. This is because let and const have block scope, and JavaScript enforces stricter rules to prevent the accidental overwriting of values.
Example:
JavaScript Arithmetic
JavaScript supports a variety of arithmetic operations that help you to perform mathematical calculations in your code. Some of them are:
- Addition (+): Adds two numbers together or concatenates strings.
- Subtraction (-): Subtracts one number from another.
- Multiplication (*): Multiplies two numbers.
- Division (/): Divides one number by another.
- Modulus (%): Returns the remainder of a division operation.
JavaScript Dollar Sign $
In JavaScript, the dollar sign ($) functions like any other letter in variable names and has no special meaning within the JavaScript language itself.
Example:
JavaScript Underscore (_)
In JavaScript, the underscore (_) has no special operational significance in the core JavaScript language but is conventionally used to indicate specific types of variables or to adhere to certain naming conventions.
Example:
Conclusion
- Javascript variables can be declared using var, let, or const, each serving different scopes and use cases, with let and const being preferable for modern code due to their block-scoping benefits.
- JavaScript supports various data types, including primitive and reference types, enabling versatile data manipulation.
- Arithmetic operations and assignment operators are essential for performing calculations and updating variable values.
- The dollar sign ($) and underscore (_) are valid characters in identifiers, offering flexibility in naming conventions and sometimes indicating special purposes or library associations.