JavaScript variables. Constants

Working in Javascript, we can enter numerical, string and boolean values, but they work if the program contains the necessary information. For this, variables have been created that allow you to store various kinds of information in themselves and are like a kind of container to which we can turn at any time and get the information that is located in it.

Variable creation

A variable is created in two steps: declaring the variable and assigning a name to it.

First, we must declare a variable, that is, declare it, this is done using the var keyword. Next, we write the instruction, this is the name of the variable, its name as we will refer to it, for example I will write dwstv.


It's up to you to name the variables, of course, but there are a few rules that must be followed in order for javascript to work:

  • first rule, avoid using reserved words... Certain words in JavaScript are used in the system itself, such as the word var with which we declare a variable. In addition, some words like alert, document, window are considered special properties of a web page. If you try to use them as variables, you will get an error message. Here you can see the list of reserved words.
  • second rule, variable name must start with a letter, $ or _... That is, the variable cannot start with a number or punctuation mark: the name 1dwstv and & dwstv will not work, but the names $ dwstv and _dwstv will.
  • third rule, variable names can contain letters, numbers, $ and _ symbols, and spaces or other special characters cannot be used in the name: dws & tv and dws tv are invalid names, but this format can be dws_tv and dwstv1 or dws_tv_1.
  • fourth rule, variable names are case sensitive... The JavaScript interpreter interprets lowercase and uppercase letters differently, that is, the DWSTV variable differs from the dwstv variable, and also from the DwStv and Dwstv variables.
  • fifth rule, n it is not recommended to use characters other than Latin, variables written in Cyrillic, although they will work, are not guaranteed, besides, they will not be understood by colleagues from other countries.

These are the main five rules that I recommend to follow, in addition to them I also want to say, assign clear and expressive names to your variables. Name the variables in accordance with the type of data that you store in them, this will help you in the future to understand what is written, and, looking at such variables, it will be clear what the speech is about.

When naming variables, try to make them easy to read. When using multiple words, add an underscore between them, or start each word after the first with a capital letter. For example, dwsTv or dws_tv.

Using variables

At the beginning of the lesson, we sorted out what a variable consists of, now, when we know how to create it, we can store any data types in it at our discretion.

In order to put data into a variable, a special symbol is used, the equal sign (\u003d), it is called an assignment operationbecause it is used to assign a value to a variable.


For example, put a digital value in the dwstv variable, the number of subscribers is 8500, we declare the var dwstv variable; and in the second line we put the value dwstv \u003d 8500;

Var dwstv; dwstv \u003d 7200;

And so, in the first line we created a variable, and in the second we saved the value to it. We can also create a variable and store values \u200b\u200bin it with a single instruction, for example:

Var dwstv \u003d 7200;

In a variable, we can store any data types that we went through in previous lessons, these can be numeric, string and boolean values:

Var dwstv \u003d 7200; var lessons \u003d ‘JavaScript’; var youtubeKanal \u003d 'DwsTV'; var subscribers \u003d ‘7700’; var content \u003d true;

We can also save space and time by declaring variables with one var key, for example:

Var lessons \u003d ‘JavaScript’, youtubeKanal \u003d ‘DwsTV’, subscribers \u003d ‘7700’, content \u003d true;

After we have stored the values \u200b\u200bin variables, we have the opportunity to access this data. To do this, just use the name of the variable itself.

For example, if we need to open an alert dialog and display the value stored in the kanal variable, we just need to write the variable name in the alert function.

Alert (kanal);

Please note that we do not enclose variables in quotes - they are only for strings, so we do not write alert (‘kanal’), since in this case we will get the words kanal, not the value stored in the variable.

Now I think you figured out why strings should be quoted: the javaScript interpreter treats words without quotes either as special objects (for example, the alert () command), or as variable names.

And there is also a moment when we declared a variable with the var keyword, and we want to change the value in the variable, it is not necessary to re-declare it by writing the word var, it is enough to call the variable name and assign a new value to it.

Subscribers \u003d ‘10000’;

By the end of this lesson, I want to say that by learning any language, you will not learn to program. Undoubtedly, you will learn something new, but most likely your brain will not remember this information, since you do not work with it. It is impossible to learn a language without practice, so from this lesson you get a small task so that the information provided will fit in with you and you can work with it.

Practical task:

Create three variables, one with a numeric value, the second with a string value, and the third with a boolean value. Declare all variables with one keyword var, and display them on the page. Then override the variable with a numeric value, and display the result using the alert () function.


At the beginning of the next video, we will analyze this problem, share your results in the comments, write if anyone has any questions. Whoever liked the lesson and wants to support the project, just share it on social networks.

In the next lesson, we'll take a closer look at how to work with data types and variables, get acquainted with mathematical operations and the order of their execution, and also analyze methods for combining string and numeric values.

The lesson was prepared by Denis Gorelov.

Variables are a fundamental building block of many programming languages; they are one of the most important concepts for aspiring programmers. There are many different properties of variables in JavaScript, as well as a few rules to follow when naming them. JavaScript has three keywords used to declare a variable - var, let, and const - and each of them affects how the variable is interpreted in your code.

This tutorial will introduce you to variables, how to declare and name them, and explain the difference between var, let, and const. In addition, you will learn what variable hoisting is and how scope affects variable behavior.

What are variables

A variable is a named chunk of memory used to store different values. A piece of information that can be referenced multiple times can be stored in a variable for later use or modification. In JavaScript, the value contained within a variable can be any data type, including a number, string, or object.

Prior to the ECMAScript 2015 (ES6) language specification, which JavaScript is currently based on, there was only one way to declare a variable - using the var keyword. Therefore, most of the old codes and manuals use only var to declare variables. Let's take a look at the differences between var, let and const.

The var keyword allows you to demonstrate the concept of the variable itself. In the example below, we are declaring a variable and assigning a value to it.

// Assign the string value 8host to the username identifier
var username \u003d "8host_blog";

This expression has several parts:

  • Declaring a variable using the var keyword;
  • Variable name (or identifier), username;
  • The assignment operator, represented by the syntax \u003d;
  • The assigned value is "8host_blog".

Now you can use the username variable in your code. JavaScript will remember that username represents the value 8host_blog.

// Check if variable is equal to value
if (username \u003d\u003d\u003d "8host_blog") (
console.log (true);
}
true

As mentioned earlier, variables can be expressed with any JavaScript data type. In this example, variables are expressed as string, number, object, boolean, and null.

// Assignment of various variables
var name \u003d "Morty";
var spartans \u003d 300;
var kingdoms \u003d ["mammals", "birds", "fish"];
var poem \u003d (roses: "red", violets: "blue");
var success \u003d true;
var nothing \u003d null;

Using console.log, you can view the value of any variable:

// Send spartans variable to the console
console.log (spartans);
300

Variables store data in memory that can later be used or modified. Variables can also be reassigned and assigned a new value. The simple example below demonstrates how a password can be stored in a variable and then updated.

// Assign value to password variable
var password \u003d "hunter2";
// Reassign variable value with a new value
password \u003d "hunter3";
console.log (password);
"hunter3"

In a real program, the password is likely to be stored securely in the database. However, this simple example illustrates a situation in which you can update the value of a variable. The value of the password variable was hunter2, but it was assigned a new value, hunter3, and now JavaScript will use the new value.

Variable naming

In JavaScript, variable names are called identifiers. Several rules for naming identifiers can be found in the manual. Here they are in brief:

  • Variable names can only contain letters, numbers (0-9), dollar sign ($), and underscore (_).
  • Variable names cannot contain whitespace characters.
  • Variable names must not start with a number.
  • There are several reserved keywords that cannot be used as variable names.
  • Variable names are case sensitive.

JavaScript also has a camelCase convention for function and variable names declared with var or let. In this case, the first word is written in lower case, and each next word begins with a capital letter (words are written without spaces between them). Most variables that are not constants will follow this convention, with a few exceptions. Variable names that are constants (declared with the const keyword) are usually written in uppercase.

There seem to be quite a few rules, but it seems so only at first glance. When working with JavaScript often, you will quickly memorize them.

Difference between var, let and const

JavaScript uses three different keywords to declare variables, which add an extra layer of complexity. These keywords differ in variable scoping, hoisting, and reassignment.

You might be wondering which of the three keywords you should use in your programs. It is common practice to use const as often as possible, and let in loops and for reassignment. Typically var is used in legacy code.

JavaScript scope

Scope in JavaScript refers to the current context of the code that determines the accessibility of variables. The scope can be local and global:

  • Global variables are those that are declared outside the block.
  • Local variables are those that are declared inside a block.

In the example below, we will create a global variable.


var creature \u003d "wolf";

You know that variables can be reassigned. In the local scope, you can create new variables with the same name as variables in the outer scope without modifying or overriding the original value.

The example below creates a global variable species. Inside the function, there is a local variable with the same name. By sending them to the console, you will see that the value of the variable differs depending on the scope, but the original value does not change.

// Initialize a global variable
var species \u003d "human";
function transform () (
// Initialize a local, function-scoped variable
var species \u003d "werewolf";
console.log (species);
}
// Log the global and local variable
console.log (species);
transform ();
console.log (species);
human
werewolf
human

In this example, the local variable is scoped at the function level. Variables declared with the var keyword always belong to this scope (that is, they recognize functions as having a separate scope). So the local variable is not available in the global scope.

However, the new let and const keywords are block-scoped. This means that a new local scope is created from any block, including function blocks, if statements, and for and while loops.

To illustrate the difference between function and block level variables, create a new variable in the if block using let.

var fullMoon \u003d true;
// Initialize a global variable
let species \u003d "human";
if (fullMoon) (
// Initialize a block-scoped variable
let species \u003d "werewolf";

}


It is not a full moon. Lupine is currently a human.

In this example, species has one global value (human) and one local value (werewolf). However, if you use var, you get a different result.

// Use var to initialize a variable
var species \u003d "human";
if (fullMoon) (
// Attempt to create a new variable in a block
var species \u003d "werewolf";
console.log (ʻIt is a full moon. Lupine is currently a $ (species) .`);
}
console.log (ʻIt is not a full moon. Lupine is currently a $ (species) .`);
It is a full moon. Lupine is currently a werewolf.
It is not a full moon. Lupine is currently a werewolf.

As a result, both the global variable and the block level variable return the same value, werewolf. This is because instead of creating a new local variable, var will reassign the same variable in the same scope. var doesn't understand that if must be part of a different, new scope. It is generally a good idea to declare variables at the block level, as this reduces the risk of inadvertently overriding variable values.

Raising variables

Most of the examples so far have used the var keyword to declare a variable, and the variable has been initialized with a value. After declaration and initialization, you can access the value or reassign the variable.

If you try to use a variable before it is declared and initialized, it will return undefined.


console.log (x);
// Variable assignment
var x \u003d 100;
undefined

However, if you omit the var keyword, the variable will not be declared, but only initialized. This will return a ReferenceError and stop script execution.

// Attempt to use a variable before declaring it
console.log (x);
// Variable assignment without var
x \u003d 100;
ReferenceError: x is not defined

This has to do with hoisting - this is JavaScript behavior that moves variable and function declarations to the top of their scope. Since only the actual declaration is hoisted and not the initialization, undefined is returned in the first example.

To better demonstrate this concept, we wrote the following code and explained how JavaScript reads it:

// The code we wrote
console.log (x);
var x \u003d 100;
// How JavaScript interpreted it
var x;
console.log (x);
x \u003d 100;

JavaScript stores x in memory as a variable before executing the script. Since the variable was called before it was defined, the result is returned undefined, not 100. However, this does not raise a ReferenceError or stop the script. Although the var keyword hasn't actually changed the location of var, it demonstrates how hoisting works. This behavior can cause problems because the programmer who wrote this code most likely expects the output of x to be true and not undefined.

Also lifting can lead to unpredictable results, as in the following example:


var x \u003d 100;
function hoist () (
// A condition that should not affect the outcome of the code
if (false) (
var x \u003d 200;
}
console.log (x);
}
hoist ();
undefined

In this example, the global variable x is 100. Depending on the if statement, x can change to 200, but since the condition was false, it should not affect the value of x. Instead, x was hoisted before the start of the hoist () function and the value became undefined.

This unpredictable behavior can cause program errors. Since let and const are defined at the block level, they will not be hoisted in the same way as in the example below.

// Initialize x in the global scope
let x \u003d true;
function hoist () (
// Initialize x in the function scope
if (3 \u003d\u003d\u003d 4) (
let x \u003d false;
}
console.log (x);
}
hoist ();
true

Duplicate variable declarations that are possible with var will throw an error with let and const.

// Attempt to overwrite a variable declared with var
var x \u003d 1;
var x \u003d 2;
console.log (x);
2
// Attempt to overwrite a variable declared with let
let y \u003d 1;
let y \u003d 2;
console.log (y);

Uncaught SyntaxError: Identifier 'y' has already been declared
So, variables declared with var can be affected by hoisting. Hoisting is a mechanism in JavaScript where variable declarations are stored in memory. This can lead to undefined variables in your code. The let and const keywords solve this problem by throwing an error when you try to use a variable before declaring it or declare a variable more than once.

Constants

Many programming languages \u200b\u200buse constants - these are values \u200b\u200bthat cannot be changed. That is, values \u200b\u200bassigned to a constant cannot be reassigned.

By general convention, const identifiers are uppercase. This sets them apart from other variables.

In the example below, the SPECIES variable is initialized as a constant using the const keyword. Attempting to reassign a variable will result in an error.

// Assign value to const
const SPECIES \u003d "human";
// Attempt to reassign value
SPECIES \u003d "werewolf";
console.log (SPECIES);
Uncaught TypeError: Assignment to constant variable.

Since const values \u200b\u200bcannot be reassigned, they must be declared and initialized at the same time, or an error will occur.

// Declare but do not initialize a const
const TODO;
console.log (TODO);
Uncaught SyntaxError: Missing initializer in const declaration

Values \u200b\u200bthat cannot be changed during programming are called immutable, and values \u200b\u200bthat can be changed are called mutable (this is obvious). Constant values \u200b\u200bcannot be reassigned, but they are mutable because the properties of objects declared with const can be changed.

// Create a CAR object with two properties
const CAR \u003d (
color: "blue",
price: 15000
}
// Modify a property of CAR
CAR.price \u003d 20000;
console.log (CAR);
(color: "blue", price: 20000)

Constants allow you to inform other programmers working on a project and yourself that a given variable should not be reassigned. To declare a variable that can be reassigned, use let.

Conclusion

In this tutorial, you learned what a variable is, familiarized yourself with the rules for naming variables and learned how to reassign their values. You also learned about variable scoping and hoisting, the limitations of the var keyword, and how let and const fix these problems.

Variables serve as "containers" for storing information.

Do You Remember School Algebra?

Do you remember school algebra? x \u003d 5, y \u003d 6, z \u003d x + y

Do you remember that a letter (eg x) could have been used to store a value (eg 5), and that you could use the information above to calculate that z is 11?

These letters are called variables, and variables can be used to store values \u200b\u200b(x \u003d 5) or expressions (z \u003d x + y).

JavaScript variables

Just like in algebra, JavaScript variables are used to store values \u200b\u200bor expressions.

A variable can have a short name, such as x, or a more descriptive name, such as carname.

Rules for JavaScript variable names:

  • Variable names are case sensitive (y and Y are two different variables)
  • Variable names must start with a letter or underscore

Comment: Since JavaScript is case sensitive, variable names are also case sensitive.

Example

The value of a variable can change during script execution. You can refer to a variable by its name to display or change its value.

Declaring (Creating) JavaScript Variables

Creating variables in JavaScript is more commonly referred to as "declaring" variables.

You are declaring JavaScript variables using the keyword var:

After executing the suggestions above, the variable x will contain the value 5 and carname will contain the value Mercedes.

Comment: When assigning a text value to a variable, enclose it in quotation marks.

Comment: If you re-declare a variable, it will not lose its value.

JavaScript Local Variables

A variable declared inside a JavaScript function becomes LOCAL and will only be available within this function. (the variable has local scope).

You can declare local variables with the same name in different functions, because local variables are recognized in the function in which they are declared.

Local variables are destroyed when the function exits.

You will learn more about functions in later JavaScript lessons.

JavaScript Global Variables

Variables declared outside of a function become GLOBAL, and all scripts and functions on the page can access them.

Global variables are destroyed when you close the page.

If you declare a variable without using "var", the variable always becomes GLOBAL.

Assigning Values \u200b\u200bto Undeclared JavaScript Variables

If you assign values \u200b\u200bto variables that have not yet been declared, the variables will be automatically declared as global variables.

These suggestions:

You will learn more about operators in the next JavaScript tutorial.

This chapter covers basic grammar, variable declarations, data types, and literals.

The basics

JavaScript borrows most of its syntax from Java, but has also been influenced by languages \u200b\u200bsuch as Awk, Perl, and Python.

JavaScript case sensitive and uses character encoding Unicode... For example, the word Früh (early in German) can be used as a variable name.

Var Früh \u003d "foobar";

But, the variable früh is not the same as Früh because JavaScript is case sensitive.

Comments

Syntax comments is the same as in C ++ and many other languages:

// Comment on one line. / * Comment spanning multiple lines. * / / * You cannot nest / * comment in a comment * / SyntaxError * /

ads

There are three kinds of declarations in JavaScript:

var Declares a variable, variable initialization with a value is optional. let Declares a local variable in the scope of a block; initializing the variable to a value is optional. const Declares a read-only named constant.

Variables

You can use variables as symbolic names for values \u200b\u200bin your application. Variable names are called identifiers and must follow certain rules.

A JavaScript identifier must start with a letter, an underscore (_), or a dollar sign ($); subsequent characters can also be numbers (0-9). Because JavaScript is case sensitive, letters include characters "A" through "Z" (uppercase) and characters "a" through "z" (lowercase).

You can use ISO 8859-1 or Unicode letters in identifiers such as å or ü. You can also use both characters in identifiers.

Some examples of valid names: Number_hits, temp99, _name.

Variable declaration

You can declare a variable in three ways:

  • Using the var keyword. For example var x \u003d 42. This syntax can be used to declare both local and global variables.
  • Just assign a value to the variable. For example, x \u003d 42. Variables declared in this way are global. Such a declaration generates a strict mode. This method is not recommended.
  • Using the let keyword. For example let y \u003d 13. This syntax can be used to declare a local variable in the scope of a block.

Assigning values

A variable declared via var or let without being assigned an initial value is undefined.

If you try to access an undeclared variable or variable before it is declared, a ReferenceError exception will be thrown:

Var a; console.log ("The value of a is" + a); // The value of the variable a is undefined console.log ("The value of b is" + b); // Uncaught ReferenceError: b not defined console.log ("The value of c is" + c); // The value of the variable c is undefined var c; console.log ("The value of x is" + x); // Uncaught ReferenceError: x is not defined let x;

You can use undefined to determine if a variable has a value. In the following example, the variable input is not assigned a value and the if statement evaluates to true:

var input; if (input \u003d\u003d\u003d undefined) (doThis ( ); ) else (doThat ( ) ; }

The undefined value behaves like false when used in a boolean context. For example, the following code executes the myFunction because myArray element is undefined:

var myArray \u003d; if (! myArray [0]) (myFunction ( ) ; }

The undefined value is converted to NaN when used in a numeric context:

var a; a + 2; // NaN

If an array is created using a literal in the top-level script, then JavaScript interprets the array every time it evaluates an expression that contains the literal. In addition, the literal used in the function is created every time the function is called.

Extra commas in array literals

It is not necessary to include all elements in the array literal. If you put two commas in a row, then the missing elements will be undefined. For instance:

var fish \u003d ["Lion",, "Angel"]; // ["Lion", undefined, "Angel"]

This array has 2 elements with values \u200b\u200band one empty (fish is "Lion", fish is undefined, and fish is "Angel").

If you put a comma at the end of the list of items, it will be ignored. In the following example, the length of the array is 3. No myList. All other commas in the list indicate a new item.

Comment: Extra commas can cause errors in older versions of browsers, so it's best to avoid using them.

var myList \u003d ["home",, "school",]; // ["home", undefined, "school"]

In the following example, the length of the array is four and the elements myList and myList are undefined:

var myList \u003d [, "home",, "school"]; //

In the following example, the length of the array is four and the elements myList and myList are undefined. Only the last comma is ignored.

var myList \u003d ["home",, "school",,]; // ["home", undefined, "school", undefined]

Understanding the behavior of extra commas is important to understanding JavaScript as a language. However, when writing your own code, keep in mind that explicitly declaring missing elements as undefined improves the clarity of the code and the ease of maintenance.

Logical literals

The Boolean type has two literal values: true and false.

Don't confuse the primitive Boolean values \u200b\u200btrue and false with the true and false values \u200b\u200bof a Boolean object. The Boolean object is a wrapper object over a boolean primitive. For more details, read Boolean.

Integer literal

Integers can be written in decimal, hexadecimal, octal, and binary systems.

  • A decimal integer literal consists of a sequence of digits without a leading zero.
  • A leading zero in an integer literal indicates that it is in octal. Octal integers consist of only the digits 0-7.
  • Leading characters 0x (or 0X) indicate that the number is hexadecimal. Hexadecimal integers can consist of the digits 0-9 and the letters a-f and A-F.
  • Leading characters 0b (or 0B) indicate that the number is binary. Binary numbers can only include the digits 0 and 1.

Some examples of integer literals:

0, 117 and -345 (decimal) 015, 0001 and -077 (octal) 0x1123, 0x00111 and -0xF1A7 (hex) 0b11, 0b0011 and -0b11 (binary)

Floating point literal

Floating point numbers can consist of the following parts:

  • A decimal integer that can have a sign (the "+" or "-" character preceding the number),
  • Decimal point ("."),
  • Fractional part (another decimal number),
  • Exhibitor.

The exponent consists of an "e" or "E" followed by an integer, which may be signed. A floating point number must consist of at least one digit and either a decimal point or the character "e" (or "E").

In a more concise form, the syntax is as follows:

[(+ | -)] [. digits] [(E | e) [(+ | -)] digits]

3.14 -3.1E + 12 -.3333333333333333333 .1e-23

Object literal

An object literal is a list of zero or more pairs of property names and associated values, enclosed in curly braces (()). You should not use an object literal at the beginning of an expression, since this will result in an error or behavior that you do not expect, because the "(" will be interpreted as the start of a block.

The following example assigns the string "Saturn" to the myCar property of the car object, sets the getCar property to the result of calling the CarTypes ("Honda") function, and sets the special property to the value of the Sales variable:

var Sales \u003d "Toyota"; function CarTypes ( name) (if (name \u003d\u003d "Honda") (return name;) else (return "Sorry, we do not sell" + name + "." ; )) var car \u003d (myCar: "Saturn", getCar: CarTypes ( "Honda"), special: Sales); console. log ( car. myCar); // Saturn console. log ( car. getCar); // Honda console. log ( car. special); // Toyota

In addition, you can use numeric or string literals in property names, or nest one object within another. For instance:

var car \u003d (manyCars: (a: "Saab", "b": "Jeep"), 7: "Mazda"); console. log ( car. manyCars. b); // Jeep console. log ( car [7]); // Mazda

The object property name can be any string, including an empty string. If the property name is not a valid JavaScript identifier, then it must be enclosed in quotation marks. To refer to such names, use square brackets () rather than a period (.):

var unusualPropertyNames \u003d ("": "An empty string", "!": "Bang!") console. log ( unusualPropertyNames. ""); // SyntaxError: Unexpected stringconsole. log ( unusualPropertyNames [""]); // "An empty string" console. log ( unusualPropertyNames. ! ); // SyntaxError: Unexpected token!console. log ( unusualPropertyNames ["!" ]); // "Bang!"

In ES2015, object literals are extended to support setting the prototype in the shorthand construct for foo: setting foo, defining methods, making super calls, and evaluating property names in expressions. Together, they make object literals and class declarations similar, and allow object design to take advantage of the same capabilities.

Var obj \u003d (// __proto__ __proto__: theProtoObj, // Shorthand for 'handler: handler' handler, // Methods toString () (// Super calls return "d" + super.toString ();), // Dynamic calculation of property names ["prop_" + (() \u003d\u003e 42) ()]: 42);

Take a look at the following example:

var foo \u003d (a: "alpha", 2: "two"); console. log ( foo. a); // alpha console. log ( foo [2]); // two // console.log (foo.2); // SyntaxError: Unexpected number// console.log (foo [a]); // ReferenceError: a is not definedconsole. log ( foo ["a"]); // alpha console. log ( foo ["2"]); // two

RegExp literal

The regexp literal is a pattern between slashes. The following example is a literal regex:

Var re \u003d / ab + c /;

String literal

A string literal is zero or more characters enclosed in double (") or single (") quotes. The string must be delimited by single quotes, i.e. either both single or both double. For instance:

"foo" "bar" "1234" "one line \\ n another line" "John" s cat "

You can call any of the String object methods on a string literal: JavaScript will automatically convert the string literal to a temporary String object, call the method, and then destroy the temporary String object. You can also use the String.length property with a string literal:

Console. log ( "John" s cat ". Length); // The number of characters in the string, including space.// In this case, the string length is 10.

String templates are also available in ES2015. String patterns are syntactic sugar for constructing strings. This is similar to the string interpolation capabilities in Perl, Python and others. Additionally, a tag can be added to customize the construction of strings, avoiding injection attacks and building high-level data structures from the contents of the string.

// Simple string creation via literal string ʻIn JavaScript "\\ n" is a line-feed.` // Multi-line strings ʻIn JavaScript this is not legal.` // String interpolation var name \u003d "Bobby", time \u003d "today "; `Hello $ (name), how are you $ (time)?` // Build the HTTP request prefix used to interpret replacements and construct POSTs`http: //foo.org/bar? A \u003d $ (a) & b \u003d $ ( b) Content-Type: application / json X-Credentials: $ (credentials) ("foo": $ (foo), "bar": $ (bar)) `(myOnReadyStateChangeHandler);

You should use string literals unless you specifically need a String object. For more information on the String object, read String.

Using special characters in strings

Besides ordinary characters, you can also include special characters in strings.

"one line \\ n another line"

The following table lists the special characters that you can use.

Special characters in JavaScript
Symbol Value
\\ b Backspace
\\ f Translation or page feed (Form feed)
\\ n Line feed (New line)
\\ r Carriage return
\\ t Tab (Tab)
\\ v Vertical tab
\" Apostrophe or single quote
\" Double quote
\\ Backslash (Backslash)
\XXX

Latin-1 character represented by three octal numbers XXX from 0 to 377. For example, \\ 251 (symbol ©).

\\ x XX

Latin-1 character represented by two hexadecimal numbers XX 00 to FF. For example, \\ xA9 (© character).

\\ u XXXX

Unicode character represented by four hexadecimal numbers XXXX... For example, \\ u00A9 (© character).

\\ u (XXXXX) The character is in UTF-32BE. For example, \\ u (2F804) means the same as the regular \\ uD87E \\ uDC04.

Escaping characters

For characters not listed in the above table, the leading backslash is ignored. This use is deprecated and you should avoid it.

You can insert a quotation mark in a string by preceding it with a backslash. This is called escaping quotes. For instance:

var quote \u003d "He read \\" The Cremation of Sam McGee \\ "by R.W. Service."; console. log ( quote); // He read "The Cremation of Sam McGee" by R.W. Service.

To include a backslash in a string, you need to precede it with another backslash. For instance:

var home \u003d "c: \\\\ temp"; // c: \\ temp

You can also escape line feed. The backslash and line feed will be removed from the string content. For instance:

var str \u003d "this string \\ is broken \\ across multiple \\ lines." console. log ( str); // this string is broken across multiplelines.

Although JavaScript does not support the "heredoc" syntax (formatted text in a single string variable), you can emulate it by adding a newline and a backslash to the end of each line:

var poem \u003d "Roses are red, \\ n \\ Violets are blue. \\ n \\ I" m schizophrenic, \\ n \\ And so am I. "

Additional Information

This chapter focuses on the basic syntax for declarations and types. For more information on JavaScript constructs read:

The next chapter covers control constructs and error handling.

Last update: 05.04.2018

Variables are used to store data in the program. Variables are designed to store some temporary data or data that can change its value during operation. 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 an arbitrary set of alphanumeric characters, underscore (_), or dollar sign ($), and names must not begin with numeric characters. That is, we can use letters, numbers, underscores in the title. However, all other characters are prohibited.

For example, the correct variable names are:

$ commision 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 the reserved keywords. There are not many keywords in JavaScript, so this rule is not difficult to follow. For example, the following name would be incorrect because for is a JavaScript keyword:

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, , 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, procent, sum; let a, b, c;

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

Var income \u003d 300; let price \u003d 76;

The process of initializing a variable is called initialization.

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

The distinguishing feature of variables is that we can change their value:

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

Constants

The const keyword can be used to define a constant that, like a variable, stores a value, but this value cannot be changed.

Const rate \u003d 10;

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

Const rate \u003d 10; rate \u003d 23; // error, rate is 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 do not do this, then again we will face an error:

Const rate; // error, rate is not initialized