In this article, you will learn how to determine constants in JavaScript using the const keyword.

ES6 provides new way constant declarations using the keyword const. Keyword const creates a reference to a read-only value.

Const VARIABLENAME = value;

By agreement constant identifiers in JavaScript are in uppercase.

Keyword const looks like key let word in that it creates block-scoped variables, but values ​​declared with const, cannot be changed.

Variables declared with a keyword let are changeable. This means that you can change their values ​​at any time, as shown in the following example.

let v = 10;
v = 20;
v = v + 5;
console log(v); // 35

However, variables created with the keyword const, are immutable. In other words, you cannot reassign them different values. Attempting to reassign a constant variable will result in a type error TypeError .

Const TAX = 0.1;
TAX = 0.2 ; // TypeError

Also, a variable that is declared with the keyword const, must be immediately initialized with a value. The following example calls SyntaxError(syntax error) due to the lack of an initializer in the declaration of a constant variable.

Const RED; // SyntaxError

As mentioned earlier, like variables declared with the keyword let, variables declared with keyword const, have block scope.

That's all, and in the next article we will talk about using the keyword const with object literals in JavaScript.

Variables and constants in JavaScript. Declaring variables and assigning values ​​to them. Variables global and local. Using constants.

Declaring Variables in JavaScript

Variable names in JavaScript can consist of letters, numbers, the $ sign, and the _ sign, and the variable name cannot start with a number. Keep in mind that JavaScript is case sensitive and a1 and A1 are different variables. Cyrillic is not recommended, although it is possible.
Variables in JavaScript are declared with the var keyword:

Var Peremennaya_1 var Peremennaya_2

Using variables in JavaScript without a declaration is not recommended. This is possible, but may lead to errors.

Assigning a value to variables

Assigning a value to declared variables in JavaScript:

Peremennaya_1 = 25 Peremennaya_2 = "The assigned text is enclosed in straight quotes"

You can assign a value to variables immediately upon declaration:

Var Peremennaya_1 = 25 var Peremennaya_2 = "We enclose the assigned text in straight quotes"

The value of a variable in JavaScript can change during program execution. When writing text to a variable, it must be enclosed in straight quotes.

Variables local and global

If a variable is declared within a function, then it is local and will be available (have visibility) only within that function. When a function exits, local variables in JavaScript are destroyed, so you can use variables with the same name in different functions.

If a variable is declared outside of functions, then it is global and will be available (have visibility) in all functions within the page. Global variables are destroyed in JavaScript when the page is closed.

Constants in JavaScript

Constants are designed to make it easier to work with code when you have to use repeated values ​​or expressions. It is enough to set a value for the constant once and you can use it as much as you like, inserting it into the code of your programs. JavaScript doesn't have a keyword for declaring constants; regular variables are used instead of constants. To distinguish constants from variables, they are usually denoted capital letters, using an underscore if necessary:

Var DRUG_CHELOVEKA = "Dog"

The given example of a constant is not quite complete, since the word “Dog” is already easy to remember and insert where necessary. You can use constants in JavaScript to write and paste more complex values, such as hard-to-remember codes, character sets, long text, web addresses, addresses Email, phone numbers, different coefficients.

In JavaScript, constants can be rewritten like variables, but if you do that, then the meaning of constants is lost.

A function is a block of code that performs an action or returns a value. Functions are custom code that can be reused; therefore, thanks to the functions, programs become modular and more productive.

This tutorial offers several ways to define and call a function and use function parameters in JavaScript.

Function definition

Functions are defined or declared with the function keyword. The function syntax in JavaScript looks like this:

function nameOfFunction() (
// Code to be executed
}

A function declaration begins with the function keyword followed by the name of the function. Function names follow the same rules as variable names: they can contain letters, numbers, underscores, and dollar signs, and are often written in camel case. The name is followed by a set of parentheses that can be used for optional parameters. The function code is contained within curly braces, like for or if statements.

As you may have noticed, the value of the name parameter is not assigned in the code, this is done when the function is called. When the function is called, the username is passed as an argument. The argument is the actual value that is passed into the function (in this case, the username, such as 8host).

// Invoke greet function with "8host" as the argument
welcome("8host");

The 8host value is passed to the function via the name parameter. Now the name parameter will represent this value in this function. The greetUser.js file code looks like this:

// Initialize custom greeting function
function greet(name) (
console.log(`Hello, $(name)!`);
}
// Invoke greet function with "8host" as the argument
welcome("8host");

When you run this program, you will get this output:

Now you know how you can reuse a function.

In addition to parameters, variables can be declared inside functions. These variables are called local and only exist within their function block. The variable scope determines the accessibility of variables; variables that are defined inside a function are not accessible from outside the function, but they can be used as many times as the function to which they belong is used in the program.

Returning values

You can use more than one parameter in a function. You can pass multiple values ​​to a function and return a value. For example, create a sum.js file and declare a function in it that will find the sum of two values, x and y.

// Initialize add function
function add(x, y) (
return x + y;
}

add(9, 7);

This code defines a function with parameters x and y. The function then gets the values ​​9 and 7. Run the program:

The program will add the resulting values, 9 and 7, and return the result 16.

When the return keyword is used, the function stops executing and returns the value of the expression. In this case, the browser will display the value in the console, however this is not the same as using console.log() to output to the console. When called, the function outputs the value to where it was called from. This value can be used or placed in a variable.

Function expressions

In the previous section, you declared a function that adds two numbers and returns the resulting value. You can also create a function expression by assigning a function to a variable.

Use the previous function to apply the resulting value to the sum variable.

// Assign add function to sum constant
const sum = function add(x, y) (
return x + y;
}
// Invoke function to find the sum
sum(20, 5);
25

Now the constant sum is a function. This expression can be shortened by turning it into an anonymous function (this is how functions without a name parameter are called). Currently, the function is called add, but the name is usually omitted in function expressions.

// Assign function to sum constant
const sum = function(x, y) (
return x + y;
}
// Invoke function to find the sum
sum(100, 3);
103

Now the function no longer has a name, it has become anonymous.

Named function expressions can be used for debugging.

Arrow functions

Until now, functions have been defined using the function keyword. However, there is a newer and more concise way to define a function - the ECMAScript 6 arrow functions. Arrow functions are represented by an equal sign followed by a greater than sign: =>.

Arrow functions are always anonymous and are a type of function expression. Try creating a basic arrow function to find the sum of two numbers.

// Define multiply function
const multiply = (x, y) => (
return x*y;
}

multiply(30, 4);
120

Instead of writing function, you can just use the symbols =>.

If the function has only one parameter, the parentheses can be omitted. In the following example, the function squares x, so it needs only one number as an argument.

// Define square function
const square = x => (
return x*x;
}
// Invoke function to find product
square(8);
64

Note: If there are no parameters in the arrow function, empty parentheses () must be added.

Arrow functions that only consist of a return statement can be shortened. If the function consists of only one return line, you can omit the curly braces and the return statement, as in the example below.

// Define square function
const square = x => x * x;
// Invoke function to find product
square(10);
100

Conclusion

This tutorial walks you through declaring functions, function expressions, and arrow functions, returning values, and assigning function values ​​to variables.

A function is a block of code that returns a value or performs an action.

Tags:

When a program needs to store a value in order to use it later, that value is assigned to a variable. A variable is simply a symbolic name for a value that provides the ability to get the value by name, that is, when the variable name is specified in the program, the value is substituted for it.

A variable gets its name from the fact that its value can be changed during program execution.

Constants

A constant is just a symbolic name for a value. A constant makes it possible to refer to a value by name, which means that when the name of the constant is specified in the program, the value is substituted for it. Constants are used to store data that should not change during program execution.

Before a constant can be used, it must be declared. Constants are declared with the keyword const followed by the name of the constant. In order to distinguish constants from variables in the program code, it was agreed to give constants names written in capital letters:

Const MAX = 10;

Once a constant has been created, attempting to redefine it to a variable or attempting to assign a value to an existing constant will cause an error.

Why variables and constants are needed

Variables and constants help make code easier to understand. Consider a small example:

TotalPrice = 2.42 + 4.33; // total price

The numbers here can mean anything. To make it clear what is summed up here, the value 2.42 can be assigned to the variable (or constant) candyPrice (candy price), and 4.33 to the variable (or constant) oilPrice (butter price):

TotalPrice = candyPrice + oilPrice;

Now, instead of remembering what these values ​​mean, you can see that in the scenario, the price of sweets is added to the price of butter.

Also, variables and constants help save time when debugging a script. Instead of using the same literal everywhere, you can assign it to a variable (or constant) at the beginning of the script, and then use the variable (or constant) instead of the literal in the rest of the script code. If later a decision is made to change the value, then changes in the code will have to be made not in several places, but only in one place - where the variable (or constant) was assigned a value.

Scope of constants

The same rules apply to constants as to variables declared with the let keyword:

Const MAX = 5; // Global constant ( const MAX = 10; // Block constant console.log(MAX); // 10 ) console.log(MAX); // 5 foo(); // 15 console.log(MAX); // 5 function foo() ( const MAX = 15; // Local constant console.log(MAX); )

Constants and Reference Types

When a value of a reference type is assigned to a constant, the reference to the value becomes immutable, and the value itself remains available for change:

Const obj = (a: 5); obj.a = 10; console.log(obj.a); // 10

It is a set of conventions and rules that must be observed when writing JavaScript code. This agreement is based on Sun's documents for the Java programming language. But since JavaScript is not Java, the document has been revised with respect to the JavaScript language.

long term value software, is directly dependent on the quality of the code. During its existence, the program passes through a huge number of hands and eyes of developers. If the program code is written in such a way that it can clearly convey its structure and characteristics, then the probability of breaking it is reduced if it is amended by other developers or by the author himself after a long period of time.

agreements on program code, can help improve the quality of the output, and reduce the chance of product failure.

JavaScript files

JavaScript programs must be stored in .js files.

JavaScript code should not be embedded in HTML files if the code is not specific to a single session. The code in HTML greatly increases the weight of the page without the possibility of reduction due to caching and compression.