Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
const | Variables and Data Types
Introduction to JavaScript
course content

Conteúdo do Curso

Introduction to JavaScript

Introduction to JavaScript

1. Basic Concepts
2. Variables and Data Types
3. Basic Operations
4. Conditional Statements
5. Loops
6. Functions

bookconst

Another way to define a variable in JavaScript is using the const keyword. The primary difference between let and const is that variables created using const cannot change their values, whereas using the let keyword allows changes to the variable's value.

Let's compare the behavior of variables using let and const. Take a look at the following example where we can change the value of the a variable:

123456
// A variable changing let a = 5; console.log(a); // Print the initial value of `a` a = 10; console.log(a); // Print the updated value of `a`
copy

In contrast, let's examine the behavior of the b variable. We will encounter an error: TypeError: Assignment to a constant variable.

1234567
// A constant cannot be changed const b = 7; console.log(b); // Print the initial value of `b` // Attempting to reassign a `const` variable will result in an error b = 8; // This line will throw an error: "TypeError: Assignment to constant variable." console.log(b);
copy

Usage

Constants are used as immutable variables. You can define a constant once and use it multiple times.

Constants provide data integrity while allowing for quick refactoring.

Note

Refactoring involves making structural changes to the code, such as modifying values, variable/function names, and more.

For example, consider maxHeight for site elements. You can release a site update by changing the maximum height of elements with just one modification in the code. However, it's important to note that you cannot change the maximum height during runtime, ensuring data integrity.

1234567
const maxHeight = 250; console.log(maxHeight - 15); console.log(maxHeight - 12); console.log(maxHeight - 5); console.log(maxHeight - 13); console.log(maxHeight - 22); console.log(maxHeight - 52);
copy
question-icon

Define a constant variable:

= 50;

Clique ou arraste solte itens e preencha os espaços

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 3
some-alt