• JavaScript Variables. Constants. Data types How to store numbers in javascript variables

    The programmer wants to create a global variable film and another variable that has the same name but only acts in the showBadFilm() function. What message will the alert output from the showGoodFilm() function? What message will be displayed if this function is called again, but after calling the showBadFilm() function?

    Good or bad movie? var film = "Red viburnum"; function showGoodFilm() ( alert(film + " - good film!"); ) function showBadFilm() ( film = "September 11"; alert(film + " - bad film!"); ) showGoodFilm(); // what will the alert display? showBadFilm(); // what will the alert display? showGoodFilm(); // what will the alert display?

    Solution:

    Notice that the showBadFilm() function does not have the var keyword before the film variable. Therefore, JavaScript assumes that you want to override the value of a global variable, rather than create a local variable of the same name. Therefore, calling the showGoodFilm() function again will print: "September 11 is a good movie!"

    • Data type checking

      Which primitive data type are the following variables? Try to answer without running the script.

      Checking the data type var film = "Red Viburnum"; var 07_agent = "Agent"; var num = 10; var num1 = "10"; var u = true; var x; alert(typeof Film); //??? alert(typeof 07_agent); //??? alert(typeof num); //??? alert(typeof num1); //??? alert(typeof u); //??? alert(typeof x); //???

      Solution:

      Notice that the first variable is declared with the name film , and the variable in the alert is Film . These are two different variables because JavaScript is a case-sensitive language. The name 07_agent starts with a number, and this will cause a syntax error and, as a result, the script will not work.

    The var statement declares a variable, optionally initializing it to a value.

    The source for this interactive example is stored in a GitHub repository. If you"d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

    Syntax var varname1 [= value1] [, varname2 [= value2]... [ , varnameN [= valueN]]]; varnameN Variable name. It can be any legal identifier. valueN Initial value of the variable. It can be any legal expression. Default value is undefined. Description

    var declarations, wherever they occur, are processed before any code is executed. This is called hoisting, and is discussed further below.

    The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value.

    Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed. The differences between declared and undeclared variables are:

    1. Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.

    Function x() ( y = 1; // Throws a ReferenceError in strict mode. var z = 2; ) x(); console.log(y); // 1 console.log(z); // Throws a ReferenceError: z is not defined outside x.

    2. Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed.

    Console.log(a); // "undefined" or "" depending on browser console.log("still going..."); // still going... var a = 1; console.log(a); // 1 console.log("still going..."); // still going...

    3. Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).

    Var a = 1; b = 2; delete this.a; // Throws a TypeError in strict mode. Fails silently otherwise. delete this.b; console.log(a, b); // Throws a ReferenceError. // The "b" property was deleted and no longer exists.

    Because of these three differences, failure to declare variables will very likely lead to unexpected results. Thus it is recommended to always declare variables, regardless of whether they are in a function or global scope. And in ECMAScript 5 strict mode, assigning to an undeclared variable throws an error.

    var hoisting

    Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it"s declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

    Bla = 2; var bla; // ...is implicitly understood as: var bla; bla = 2;

    For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it"s clear which variables are function scoped (local) and which are resolved on the scope chain.

    It"s important to point out that the hoisting will affect the variable declaration, but not its value"s initialization. The value will indeed be assigned when the assignment statement is reached:

    Function do_something() ( console.log(bar); // undefined var bar = 111; console.log(bar); // 111 ) // ...is implicitly understood as: function do_something() ( var bar; console .log(bar); // undefined bar = 111; console.log(bar);

    Examples Declaring and initializing two variables var a = 0, b = 0; Assigning two variables with single string value var a = "A"; var b = a; // ...is equivalent to: var a, b = a = "A";

    Be mindful of the order:

    Var x = y, y = "A"; console.log(x + y); //undefinedA

    Here, x and y are declared before any code is executed, but the assignments occur later. At the time " x = y " is evaluated, y exists so no ReferenceError is thrown and its value is undefined . So, x is assigned the undefined value. Then, y is assigned the value "A" . Consequently, after the first line, x === undefined && y === "A" , hence the result.!}

    Initialization of several variables var x = 0; function f() ( var x = y = 1; // Declares x locally; declares y globally. ) f(); console.log(x, y); // 0 1 // In non-strict mode: // x is the global one as expected; // y is leaked outside of the function, though!

    The same example as above but with a strict mode:

    "use strict"; var x = 0; function f() ( var x = y = 1; // Throws a ReferenceError in strict mode. ) f(); console.log(x, y);

    Implicit globals and outer function scope

    Variables that appear to be implicit globals may be references to variables in an outer function scope:

    Var x = 0; // Declares x within file scope, then assigns it a value of 0. console.log(typeof z); // "undefined", since z doesn't exist yet function a() ( var y = 2; // Declares y within scope of function a, then assigns it a value of 2. console.log(x, y); // 0 2 function b() ( x = 3; // Assigns 3 to existing file scoped x. y = 4; // Assigns 4 to existing outer y. z = 5; // Creates a new global variable z, and assigns it a value of 5. // (Throws a ReferenceError in strict mode.) b(); // Creates z as a global variable. console.log(x, y, z); (); // Also calls b. console.log(x, z); // 3 5 console.log(typeof y);

    Specifications Specification Status Comment
    ECMAScript 1st Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.0
    ECMAScript 5.1 (ECMA-262)
    The definition of "var statement" in that specification.
    Standard
    ECMAScript 2015 (6th Edition, ECMA-262)
    Standard
    ECMAScript Latest Draft (ECMA-262)
    The definition of "variable statement" in that specification.
    Draft
    Browser compatibility

    The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

    Update compatibility data on GitHub

    Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.jsvar
    Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 3Opera Full support YesSafari Full support YesWebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 1.0nodejs Full support Yes

    The syntax rules for creating variable names in JavaScript are:

    • The following symbols are used for variable names: a-z, A-Z, numbers, the $ symbol, and the underscore (_).
    • The variable name cannot begin with a number.
    • JavaScript is case sensitive, something to keep in mind when programming. itcounter and it C ounter are different variables.
    • JavaScript has no restrictions on the length of a variable name.

    Examples of correct variable names:

    • itcounter
    • $_itcounter
    • it_counter

    Incorrect variable names:

    • 9room
    • it-counter
    • #itcounter
    • &itcounter

    Variables are declared with the var command.

    Variables can store strings and numbers. In fact, you can store other types of data, but we'll talk about them later.

    String variables

    To write a string to a variable, you need to enclose its value in quotes, double or single.

    Var $stroka_1 = "Hello!"; var $stroka_2 = "Caution!";

    You can include a double quote in a string created with a single quote, and vice versa.

    Var $stroka_1 = ""Hello!" is a greeting."; var $stroka_2 = ""Caution!" is a warning."; document.write($stroka_1); document.write("

    To display a quote of the same type, it must be escaped with a backslash character. It's simple:


    "); document.write($stroka_2);

    Variable values ​​can be assigned to other variables:

    Var $stroka_1 = "\"Hello!\" is a greeting."; var $stroka_2 = "\"Caution!\" is a warning."; document.write($stroka_1); document.write("
    "); document.write($stroka_2); $stroka_2 = $stroka_1; document.write("
    "); document.write($stroka_2);

    In this example, we first assigned one string value to the $stroka_2 variable, but then assigned it the value of the $stroka_1 variable.

    Concatenating Strings

    Very often you need to combine several lines into one. For example, our last example is too cumbersome.

    Combining (concatenating) strings in JavaScript is done using the + sign.

    To display 2 string variables separated by a tag
    variables you can use one command document.write() .

    Var $stroka_1 = ""Hello!" is a greeting."; var $stroka_2 = ""Caution!" is a warning."; document.write($stroka_1 + "
    " + $stroke_2);

    The concatenation operator + can also be used in variables:

    Var $stroka_1 = ""Hello!" is a greeting."; var $stroka_2 = ""Caution!" is a warning."; var $stroka_3 = $stroka_1 + "
    " + $stroka_2; document.write($stroka_3);

    Numeric variables

    To create a numeric variable, you simply assign it a numeric value.

    Var $count_1 = 23; var $count_2 = 10.34; document.write($count_1 - $count_2);

    Now another example:

    Var $count_1 = 23; // Numeric variable. var $stroka_1 = "57"; // String variable. document.write($stroka_1 + $count_1);

    You see, the value of the $stroka_1 variable is in quotes, which means it is a text variable. Then we add the text and numeric variables and get the string "5723", this is how JavaScript works in such cases - it turns the number into a string and adds it to the summed string.

    Boolean variables

    There is such a type of variables - Boolean. It's simple, there are only two values: true and false, that is, true (true) and false (false).

    This data type is used in comparison operations. Here are simple examples:

    • 9 > 1 is true.
    • 2 > 5 is a lie.
    var $count = 2

    Now let's try to substitute Boolean values ​​into arithmetic operations. Let's summarize the two comparison operations:

    Var $count = (3 > 2) + (4 > 2); document.write($count);

    This is a weird post, I know. But the $count variable will be equal to 2. In a mathematical context, the value of true = 1 and the value of false = 0.

    Comparison operators are used in a commonly used if statement in JavaScript. The word if in English means - if.

    Var $count = 100; if ($count == 100) document.write("The $count variable is 100.");

    In this example, a message will be displayed on the screen because the condition of the if statement ($count == 100) is true. If you change the value of the $count variable to 99, then the condition ($count == 100) will become false and nothing will be displayed on the screen.

    Simple Variable Types

    In JavaScript, variables are classified into several types. We have already looked at string, numeric and Boolean (logical) types. Here is a broader list of simple types:

    • string - string variable.
    • number - numeric variable.
    • boolean - Boolean variable.
    • null is a special value for “nothing”.
    • undefined - type “no value assigned”.

    The value of a null variable forms its own separate null type, consisting of the only possible null value. null is a special value that has the meaning of "nothing" or "the value is unknown."

    Var $price = null; // this means that the price is not known.

    In JavaScript, you can find out the type of variables using the typeof statement.

    Var $count; document.write(typeof $count + "
    "); var $count = true; document.write(typeof $count + "
    "); var $count = "true"; document.write(typeof $count + "
    "); var $count = 100; document.write(typeof $count + "
    "); var $count = null; document.write(typeof $count + "
    ");

    The syntax of the typeof statement could be:

    • typeof $count
    • typeof($count)

    So, run the code from the last example and look at the result. The type of the null variable will be object. This is a bug in the language and will probably never be fixed due to the need to keep existing JavaScript scripts compatible with new versions of the language.

    The object type is no longer a primitive type; we will talk about it in other lessons.

    A variable is simply a symbolic name for a value. A variable allows you to refer to a value by name, which means that when a variable name is specified in a program, the value is substituted.

    Announcement

    Before a variable can be used, it must be declared. Variables are declared using the var or let keyword followed by the variable name:

    Var num; let num2;

    Once you use the var or let keyword, you can declare multiple variables, separating them with commas:

    Var num, num2; let num3, num4;

    Initialization and value assignment

    The declaration of variables can be combined with their initialization. Initialization is the assignment of an initial value to a variable. You can assign a value to a variable using the assignment operator, which is denoted by the equals symbol (=):

    Var color = "black"; let num = 10, num2 = 15;

    Variables in JavaScript don't have a type, so a variable can be assigned a value of any type, and then the same variable can be assigned a value of another type:

    Var a = 10; let b = 20; a = "text"; b = "text";

    If a variable was declared with no value assigned to it, it will have the special value undefined until it is assigned another value:

    Var a; let b; console.log(a); // undefined console.log(b); // undefined

    Accessing a value

    Once a variable is declared, the var or let keyword does not need to be specified when using the variable. To access the value of a variable in a program, you just need to write the name of the variable, the JavaScript interpreter will replace it with the value that is stored in the variable:

    Var x = 10, msg = "Hello"; alert(x); document.write(msg); Try »

    Since the variable name is replaced by its value, you can copy the value from one variable to another:

    Var a = 10; let b; b = a; // Same as b = 10;

    If you try to use an undeclared variable, an error will be thrown:

    Console.log(x); // Error