Understanding Variables in JavaScript
Hello HaWkers, this is the third article in our series of articles that will cover the in-depth look at our JavaScript Roadmap - EVERYTHING you need to Learn 🦅. If you don't know what I'm talking about, click on the previous link.
Well, let's get started!
Within the programming universe, variables play a fundamental role. In JavaScript, this role is expanded by its dynamicity and versatility. This article aims to clarify what variables are, how to declare them, and how they behave within the JavaScript environment.
Data Types in Variables
In JavaScript, variables can store different types of data. While some languages ​​require you to explicitly declare the data type of a variable, JavaScript is dynamically typed. This means that the data type of a variable can change during program execution. Some of the most common types include:
- Number: For numbers, whether integer or float.
- String: For character sequences.
- Boolean: For true or false values.
- Object: For data collections or constructor instances.
- Undefined: For uninitialized variables.
- Null: Represents the absence of value.
Variables and Data Types: A Deeper Look
In JavaScript, the type of a variable is determined by its value:
let x = 10; //Numberlet y = 'HaWkers!'; //Stringlet z = true; // Booleanconsole.log(typeof x); // Returns "number"console.log(typeof y); // Returns "string"console.log(typeof z); // Returns "boolean"
This allows us to use the same variable for different data types:
let data = 2023;console.log(data); // 2023data = 'JavaScript';console.log(data); // JavaScript
What are variables?
Variables, in simple terms, are "boxes" where we store values. Imagine that you have a series of drawers, and in each of them, you store a different object. Variables work in a similar way, storing data that can be numbers, strings, objects, among others.
Declaring variables
In JavaScript, we have several ways to declare variables, the most common being through the keywords var
, let
, const
. Each of them has its peculiarities:
var
: It was the traditional way of declaring variables before ES6. Variables declared withvar
are, by default, hoisting and have function scope.let
: Introduced with ES6, it allows you to declare variables with block scope, avoiding many problems related tovar
.const
: Also from ES6, it is used to declare constants, that is, values ​​that cannot be reassigned after their declaration.
Var, Let or Const? A Question of Immutability
When choosing between var
, let
and const
, immutability is an important consideration. When you declare a variable with const
, you are not just saying that the variable cannot be reassigned; you are making a claim about immutability:
const myArray = [1, 2, 3];myArray.push(4);// This is allowed!myArray = [1, 2, 3, 4];// This will cause an error!
Although we can modify the array declared as constant, we cannot reassign a new value to it.
Startup vs. Declaration
In JavaScript, it is possible to declare a variable without initializing it:
let myVariable;console.log(myVariable);// Returns undefined
But, we can assign a value to it later:
myVariable = 'Now I have a value!';console.log(myVariable);// Returns "Now I have a value!"
Hoisting
Hoisting is a peculiar JavaScript behavior that "moves" variable declarations to the top of their scope. In practice, it means that a variable can be used before being declared. However, it is best practice to declare variables at the beginning of their scope to avoid confusion.
Naming rules
Although JavaScript is a flexible language, there are some rules for naming variables:
- Names can contain letters, numbers, underscores (_) and dollar signs ($), but cannot begin with a number.
- Using language keywords as variable names is not permitted.
- Variable names are case sensitive, that is,
Name
andname
are different. - It is recommended to use the camelCase convention for variable names with more than one word.
Temporal Variables with Template Strings
Instead of concatenating variables into strings using the plus sign (+), modern JavaScript offers Template Strings for embedding variables within strings:
let name = 'HaWker';console.log(`Hello, ${name}!`);
This makes it easier to read and format texts that include variables.
Operations with Variables
You are not limited to just storing values ​​in variables. You can also perform operations:
let a = 5;let b = 10;let sum = a + b;console.log(`The sum of ${a} and ${b} is ${sum}.`);// Returns "The sum of 5 and 10 is 15."
Variable scope
The scope of a variable refers to the part of the code where it can be accessed. In JavaScript, we basically have three scopes: global, function and block.
Global Scope (global scope)
Variables declared outside of any function or block belong to the global scope. They can be accessed from anywhere in the code, which can sometimes cause conflicts and unexpected errors.
Care with Global Variables
Global variables can be useful, but they are also risky. They can be accessed or modified from anywhere in the code, which can lead to unexpected behavior:
var globalVar = `I'm global!`;function modify() { globalVar = 'I was modified!';}modify();console.log(globalVar);// This will print: I have been modified!
Therefore, it is advisable to limit the use of global variables and prefer narrower scopes whenever possible.
Function scope
Variables declared inside a function using var
have function scope. This means that they can only be accessed within that function.
Difference
The main difference between global and function scope is accessibility. While global scope variables are accessible throughout the code, function scope variables are restricted to the function where they were declared. With the advent of ES6 and the introduction of let
, we also have block scope, which limits access to a certain block of code, such as loops or conditionals.
Function vs. Block: Visualizing Scopes
JavaScript ES6 introduced let
and const
, which are block scoped. Let's look at the difference between function scope and block scope:
function testFunction() { var functionScope = `I'm in the role!`; if (true) { let blockScope = `I'm in the block!`; console.log(functionScope); // Returns "I'm in the role!" console.log(blockScope); // Returns "I'm on the block!" } console.log(functionScope); // Returns "I'm in the role!" // console.log(scopoBloco); // This would cause an error}testFunction();
Conclusion
Well HaWkers, as you can see, understanding variables is crucial to mastering JavaScript or any other programming language. By understanding the nuances of declaration, hoisting, and scope, you will be better prepared to write clean, efficient, and error-free code.
Back to Roadmap JavaScript - EVERYTHING you need to learn 🦅.