JavaScript. Variables (global, local, constants). Eval is evil

When a program needs to store a value 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 a program specifies the name of a variable, the value is substituted for it.

The variable got its name due to the fact that its value can be changed during program execution.

Constants

A constant is simply a symbolic name for a value. A constant makes it possible to refer to a value by name, which means that when a program specifies the name of a constant, the value is substituted instead. 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 using the const keyword 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 are variables and constants needed?

Variables and constants help you do program code clearer. Let's look at a small example:

TotalPrice = 2.42 + 4.33; // Total price

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

TotalPrice = candyPrice + oilPrice;

Now, instead of remembering what these values ​​mean, you can see that the script adds up the price of candy 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 throughout the rest of the script code. If a decision is made later 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 value was assigned to the variable (or constant).

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 constant is assigned a value of a reference type, the reference to the value becomes immutable, and the value itself remains changeable:

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

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

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

Const VARIABLE_NAME = value;

By agreement, JavaScript constant identifiers are uppercase.

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

Variables declared with keyword let are changeable. This means 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 unchangeable. In other words, you can't reassign them to different values. Trying to reassign a constant variable will result in a type error TypeError .

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

Additionally, a variable that is declared using the keyword const, must be immediately initialized with a value. The following example calls SyntaxError(syntax error) due to the absence 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.

Last update: 04/05/2018

Variables are used to store data in a program. Variables are designed to store some temporary data or data that can change its value during operation. The var and let keywords are used to create variables. For example, let's declare the variable myIncome:

Var myIncome; // another option let myIncome2;

Each variable has a name. The name is a random string of alphanumeric characters, an underscore (_), or a dollar sign ($), and names must not begin with numeric characters. That is, we can use letters, numbers, and underscores in the name. However, all other characters are prohibited.

For example, correct names variables:

$commission someVariable product_Store income2 myIncome_from_deposit

The following names are incorrect and cannot be used:

222lol @someVariable my%percent

Also, you cannot give variables names that match reserved keywords. There aren't many keywords in JavaScript, so this rule not difficult to follow. For example, the following name would be incorrect because for is a keyword in JavaScript:

Var for;

List of reserved words in JavaScript:

abstract, boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, export, extends, false, final, finally, float, for, function, goto, if, implements, import, in, instanceof, int, inteface, long, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, volatile, void, while, with

When naming variables, keep in mind that JavaScript is case sensitive language, that is, in the following code two different variables are declared:

Var myIncome; var MyIncome;

You can define several variables at once, separated by commas:

Var myIncome, percentage, sum; let a, b, c;

Using the equal sign (also called assignment operator) you can assign any value to a variable:

Var income = 300; let price = 76;

The process of assigning an initial value to a variable is called initialization.

Now the income variable will store the number 300, and the price variable will store the number 76.

The great thing about variables is that we can change their value:

Var income = 300; income = 400; console.log(income); let price = 76; price = 54; console.log(price);

Constants

Using the const keyword, you can define a constant that, like a variable, stores a value, but that value cannot be changed.

Const rate = 10;

If we try to change its value, we will encounter an error:

Const rate = 10; rate = 23; // error, rate is a constant, so we cannot change its value

It is also worth noting that since we cannot change the value of a constant, it must be initialized, that is, when we define it, we must provide it with an initial value. If we don't do this, then again we will encounter an error:

const rate; // error, rate is not initialized

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 using the function keyword. The function syntax in JavaScript looks like this:

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

A function declaration begins with the keyword function 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 in curly braces, like a for or if statement.

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 calling the function, the username is passed as an argument. The argument is the actual value that is passed to the function (in this case the username, for example 8host).

// Invoke greet function with "8host" as the argument
greet("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 code for the greetUser.js file looks like this:

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

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

Now you know how to reuse a function.

In addition to parameters, variables can be declared inside functions. These variables are called local and exist only within their function block. The variable scope determines the availability 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, a function outputs a 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 what functions without a name parameter are called). Currently the function is called add, but in function expressions the name is usually omitted.

// 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 simply use => symbols.

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

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

Note: If the arrow function has no parameters, you need to add empty parentheses ().

Arrow functions that consist only 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 introduces you to 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:

From the author: Perhaps this will be surprising, but JavaScript has long lacked support for constants, i.e. registered values ​​that do not change throughout the execution of your entire script. In the absence of any alternatives, most constants were declared using variables.

An example of declaring a constant using a variable:

var DAYSINWEEK = 7;

var DAYSINWEEK = 7 ;

This is both dangerous and impractical because it allows you to change the value of the DAYSINWEEK variable in your script at any time. Developers have come up with a variety of ways to distinguish variables that are ostensibly constants from regular variables in JavaScript, ranging from naming variables in CAPITAL LETTERS ONLY (the best practice) to solutions that I'll talk about later. Fortunately, in latest version ECMAScript (a specification that is a standard) introduced this constant:

JavaScript. Quick start

const DAYSINWEEK = 7;

const DAYSINWEEK = 7 ;

And now DAYSINWEEK can be accessed as a variable, but you will never be able to change its value:

console.log(DAYSINWEEK); > 7 DAYSINWEEK = 8; > error

console. log(DAYSINWEEK);

DAYSINWEEK = 8 ;

> error

Once a constant has been declared (constants must be initialized with the const keyword, followed by a constant name that follows variable naming conventions), its name will be reserved: you can no longer name a variable DAYSINWEEK and have a constant with that same name, or vice versa.

The const keyword has good support in modern browsers: IE11 and Spartan, Firefox 31+, Opera 12+, Safari 5.1.7+, iOS 7 and higher, along with Chrome 36+. However, there are a few important caveats:

Chrome does not support displaying an error when attempting to overwrite a constant. The value of the constant will not be changed in any case, but an inexperienced developer may think that the new value has been applied since no error was output.

JavaScript. Quick start

Learn the basics of JavaScript with a hands-on example of how to create a web application.

Constants do not create a new scope in Webkit. Those. constants can be visible outside the current scope.

Firefox 35 and below allows you to change the value of a const on the fly. This is fixed in Firefox versions 36+.

It should also be noted that problems with Webkit only occur if strict mode is not used (which will be discussed in a future article).

Is it possible to use the const keyword in real projects now?

The choice of whether or not to use the const keyword in your code will depend on several factors: the most important thing is what versions of browsers your site visitors are using, since using the const keyword will be considered an error in browsers such as IE10. If you want to use the const keyword in development, but are not ready to use it in real projects, then you have several options:

Option 1: use a transpiler (“transpiler”)

Transpilers, as the name suggests, transform your code at compile time into another language: in this case, from the version of the ES6 specification (which introduced the const keyword) to ES5. This allows you to write code in more new version language, but the actual project will use a version that is compatible with a wider range of browsers. Eddie Osmani composed

Connection