JavaScript Variables
Summary
Introdution to variables in JavaScript using let
and const
. Differences between let
, const
, and var
. Variable naming conventions and best practices. Introduction to data types.
Introduction to Variables in JavaScript #
In modern JavaScript (ES6 or higher), variables (identifiers) are declared using the let
and const
keywords, providing block-level scoping and immutable binding respectively.
let
allows for variable reassignment and block scoping, meaning the variable is limited to the block in which it is defined.const
is used for variables whose values will not be re-assigned after declaration, providing immutability for the variable’s binding, although it doesn’t mean the value itself is immutable.
Examples #
// Using let
let x = 10;
x = 20; // Valid
// Using const
const y = 5;
y = 8; // Invalid, attempting to reassign a constant variable
// With both let and const, block scoping applies
{
let z = 15;
console.log(z); // Output: 15
}
console.log(z); // Error: z is not defined
// const for objects and arrays doesn't prevent mutation of their properties or elements
const person = { name: 'Alice' };
person.name = 'Bob'; // Valid, mutating a property of the object
Differences between let
, const
, and var
#
The main differences between let, const, and var in JavaScript are related to scoping, re-assignment, and immutability:
- Scoping
var
has function-level scope. Variables declared with var are function-scoped, meaning they are visible throughout the entire function in which they are declared.let
andconst
have block-level scope. They are limited to the block (enclosed within curly braces{}
) in which they are defined, such as loops or conditionals.
- Re-assignment
- Variables declared with
var
andlet
can be reassigned. - Variables declared with
const
cannot be reassigned. For objects and arrays, while you cannot reassign the variable itself, you can still modify the properties or elements of the object or array.
- Variables declared with
- Hoisting
- Variables declared with
var
are hoisted to the top of their scope. This means that you can access them before they are declared, but they will have an initial value of undefined. let
andconst
are also hoisted, but they are not initialized until the actual declaration statement is evaluated during runtime. Accessing them before their declaration results in aReferenceError
.
- Variables declared with
- Global Object Property
- Variables declared with
var
become properties of the global object (window in browsers). This can lead to unintended consequences and conflicts. - Variables declared with
let
andconst
do not become properties of the global object.
- Variables declared with
let
and const
provide more predictable behavior and better support for writing modular and maintainable code compared to var. It is generally recommended to use let
for variables that may be reassigned, and const
for variables that will not be reassigned after initialization.
With the introduction of let
and const
in ECMAScript 6 (ES6), it is generally recommended to avoid using var
in modern JavaScript codebases in favor of let
and const
.
Naming variables in JavaScript #
Reserved names #
Modern JavaScript has a list of reserved words that cannot be used as variable names, as they have special meanings within the language:
abstract
arguments
await
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
eval
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
let
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with
yield
Using any of these words as variable names would result in a syntax error. It is a good practice to choose descriptive variable names that clearly convey the purpose of the variable in your code.
Variable nameing best practices #
Variable names that should be avoided or will cause issues due to their special meanings or conventions within the language:
- Names starting with a number
Variable names cannot start with a number. - Names with special characters
Variable names cannot contain special characters except for$
and_
, which are allowed. Using$
at the beginning of a variable name is discouraged as it might clash with libraries or frameworks. - Names with hyphens
Variable names cannot contain hyphens (-
). - Names with spaces
Variable names cannot contain spaces. - Names with punctuation
Variable names cannot contain punctuation marks like.
,,
,:
,;
,!
,?
, etc. - Names matching built-in properties or methods
Avoid using names that match built-in properties or methods of objects. For example, usinglength
as a variable name for anything other than the length of an array could lead to confusion. - Names with ambiguous meanings
Avoid using names that are ambiguous or unclear in their meaning, as they can make the code harder to understand. For example, using single-character variable names likex
,y
, orz
may not convey the purpose of the variable effectively. - Names with reserved names in specific contexts
Some variable names may be reserved in certain contexts or environments. For example, names likedocument
,window
,global
, etc., may have special meanings in browser environments. - Names with leading or trailing underscores
Although underscores (_
) are allowed in variable names, using them at the beginning or end of a variable name is discouraged as it might clash with naming conventions or be reserved for specific purposes by libraries or frameworks. - Names with casing issues
JavaScript is case-sensitive, somyVariable
,MyVariable
, andMYVARIABLE
are treated as different variables. Avoid using names that differ only in casing to prevent confusion. - Names with reserved words in other languages
If you are working with code that may interact with other programming languages, be cautious of using variable names that are reserved in those languages. - Camel case
It is best practice to use camel case for variable names. For examplesMyVariable
ormyVariable
.
Following these guidelines will help ensure that your variable names are clear, meaningful, and free from potential conflicts or issues.
Loosly typed #
In loosely typed languages like JavaScript, variables are not bound to a specific data type. This means that a variable can hold different types of values over its lifetime.
Type coercion is common in loosely typed languages, where the interpreter automatically converts data from one type to another when needed. For example, “5” + 3 would result in the string “53” because the number 3 is coerced into a string and concatenated with “5”.
JavaScript’s loosely typed nature can lead to unexpected behaviors if not used carefully, as types can be coerced implicitly during operations.
Data types #
In JavaScript, the typeof
operator is used to determine the type of a given value or expression. It returns a string indicating the data type of the operand.
typeof 42; // "number"
typeof "Hello"; // "string"
typeof true; // "boolean"
typeof {}; // "object"
typeof []; // "object"
typeof function(){}; // "function"
typeof undefined; // "undefined"
typeof null; // "object" (historical quirk)
typeof null
returns "object", which is often considered a historical mistake in JavaScript, but it is maintained for backward compatibility.
Primitive data types #
For primitive types, typeof
returns the actual type as a string:
- number
- string
- boolean
- undefined
Objects #
For objects, typeof
returns “object”, though you can use other methods (like Array.isArray()
) to differentiate between array and non-array objects.
- object
- array
- function
Type Detection #
typeof
is particularly useful when you need to perform different actions based on the type of a variable or value:
function displayType(value) {
console.log(typeof value);
}
displayType(42); // "number"
displayType("Hello"); // "string"
typeof
is not always foolproof, especially for complex objects and arrays. For example, it can not differentiate between different kinds of objects (like a regular object and an instance of a class), nor can it distinguish between different types of objects (like a function and a plain object).
It may not always provide the granularity needed for type checking. For more complex type checking scenarios other methods and libraries may be more appropriate.
Further readings #
Sources and recommended, further resources on the topic:
License
License: JavaScript Variables by Jonas Jared Jacek is licensed under CC BY-NC-SA 4.0.
This license requires that reusers give credit to the creator. It allows reusers to distribute, remix, adapt, and build upon the material in any medium or format, for noncommercial purposes only. If others modify or adapt the material, they must license the modified material under identical terms. To give credit, provide a link back to the original source, the author, and the license e.g. like this:
<p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://www.ditig.com/publications/javascript-variables">JavaScript Variables</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://www.j15k.com/">Jonas Jared Jacek</a> is licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="license noopener noreferrer">CC BY-NC-SA 4.0</a>.</p>
For more information see the DITig legal page.