JavaScript: Variables and Constants. javascript basics assigning values ​​to variables

Last update: 05.04.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, the correct variable names are:

$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 will be incorrect, since for - 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

I too have had a problem with this. And after quite a while searching for the answer and looking at all the responses by everyone, I think I"ve come up with a viable solution to this.

It seems that most of the answers that I"ve come across is using functions to hold the constants. As many of the users of the MANY forums post about, the functions can be easily over written by users on the client side. I was intrigued by Keith Evetts" answer that the constants object can not be accessed by the outside, but only from the functions on the inside.

So I came up with this solution:

Put inside everything an anonymous function so that way, the variables, objects, etc. cannot be changed by the client side. Also hide the "real" functions by having other functions call the "real" functions from the inside. I also thought of using functions to check if a function has been changed by a user on the client side. If the functions have been changed, change them back using variables that are "protected" on the inside and cannot be changed.

/*Tested in: IE 9.0.8; Firefox 14.0.1; Chrome 20.0.1180.60 m; Not Tested in Safari*/ (function())( /*The two functions _define and _access are from Keith Evetts 2009 License: LGPL (SETCONST and CONST). They"re the same just as he did them, the only things I changed are the variable names and the text of the error messages. */ //object literal to hold the constants var j = (); /*Global function _define(String h, mixed m). I named it define to mimic the way PHP " defines" constants. The argument "h" is the name of the const and has to be a string, "m" is the value of the const and has to exist. If there is already a property with the same name in the object holder , then we throw an error. If not, we add the property and set the value to it. This is a "hidden" function and the user doesn't see any of your coding call this function. You call the _makeDef() in your code and that function calls this function. - You can change the error messages to whatever you want them to say. */ self._define = function(h,m) ( if (typeof h !== "string") ( throw new Error("I don\"t know what to do."); ) if (!m) ( throw new Error("I don\"t know what to do."); ) else if ((h in j)) ( throw new Error("We have a problem!"); ) else ( j[h] = m; return true; ) ); /*Global function _makeDef(String t, mixed y). I named it makeDef because we "make the define" with this function. The argument "t" is the name of the const and doesn't need to be all caps because I set it to upper case within the function, "y" is the value of the value of the const and has to exist. I make different variables to make it harder for a user to figure out whats going on. We then call the _define function with the two new variables. You call this function in your code to set the constant. You can change the error message to whatever you want it to say. */ self._makeDef = function(t, y) ( if(!y) ( throw new Error("I don\"t know what to do."); return false; ) q = t.toUpperCase(); w = y; _define(q, w); ); /*Global function _getDef(String s). I named it getDef because we "get the define" with this function. The argument "s" is the name of the const and doesn't "t need to be all capse because I set it to upper case within the function. I make a different variable to make it harder for a user to figure out what's going on. The function returns the _access function call. I pass the new variable and the original string along to the _access function. I do this because if a user is trying to get the value of something, if there is an error the argument doesn"t get displayed with upper case in the error message. You call this function in your code to get the constant. */ self._getDef = function(s) ( z = s.toUpperCase(); return _access(z, s); ); /*Global function _access(String g, String f). I named it access because we "access" the constant through this function. The argument "g" is the name of the const and its all upper case, "f" is also the name of the const, but its the original string that was passed to the _getDef() function. If there is an error, the original string, "f", is displayed. This makes it harder for a user to figure out how the constants are being stored. If there is a property with the same name in the object holder, we return the constant value. If not, we check if the "f" variable exists, if not, set it to the value of "g" and throw an error. This is a "hidden" function and the user doesn't see any of your coding call this function. You call the _getDef() function in your code and that function calls this function. You can change the error messages to whatever you want them to say. */ self._access = function(g, f) ( if (typeof g !== "string") ( throw new Error("I don\"t know what to do."); ) if (g in j) ( return j[g]; ) else ( if(!f) ( f = g; ) throw new Error("I don\"t know what to do. I have no idea what \""+f+" \" is."); ) ); /*The four variables below are private and cannot be accessed from the outside script except for the functions inside this anonymous function. These variables are strings of the four above functions and will be used by the all-dreaded eval() function to set them back to their original if any of them should be changed by a user trying to hack your code. */ var _define_func_string = "function(h,m) ("+" if (typeof h !== "string") ( throw new Error("I don\\"t know what to do."); )"+" if (!m) ( throw new Error("I don\\"t know what to do."); )"+" else if ((h in j)) ( throw new Error("We have a problem!"); )"+" else ("+" j[h] = m;"+" return true;" +" )"+" )"; var _makeDef_func_string = "function(t, y) ("+" if(!y) ( throw new Error("I don\\"t know what to do."); return false ; )"+" q = t.toUpperCase();"+" w = y;"+" _define(q, w);"+" )"; var _getDef_func_string = "function(s) ("+" z = s.toUpperCase();"+" return _access(z, s);"+" )"; var _access_func_string = "function(g, f) ("+" if (typeof g !== "string") ( throw new Error("I don\\"t know what to do."); )"+" if (g in j) ( return j[g]; )"+" else ( if(!f) ( f = g; ) throw new Error("I don\\"t know what to do. I have no idea what \\""+f+"\\" is. "); )"+" )"; /*Global function _doFunctionCheck(String u). I named it doFunctionCheck because we"re "checking the functions" The argument "u" is the name of any of the four above function names you want to check. This function will check if a specific line of code is inside a given function. If it is, then we do nothing, if not, then we use the eval() function to set the function back to its original coding using the function string variables above. This function will also throw an error depending upon the doError variable being set to true This is a "hidden" function and the user doesn't see any of your coding call this function. You call the doCodeCheck() function and that function calls this function. - You can change the error messages to whatever you want them to say. */ self._doFunctionCheck = function(u) ( var errMsg = "We have a BIG problem! You\"ve changed my code."; var doError = true; d = u; switch(d.toLowerCase()) ( case "_getdef": if(_getDef.toString().indexOf("z = s.toUpperCase();") != -1) ( /*do nothing*/ ) else ( eval("_getDef = "+_getDef_func_string); if(doError === true) ( ​​throw new Error(errMsg); ) ) break; case "_makedef": if(_makeDef.toString().indexOf("q = t.toUpperCase();") != -1 ) ( /*do nothing*/ ) else ( eval("_makeDef = "+_makeDef_func_string); if(doError === true) ( ​​throw new Error(errMsg); ) ) break; case "_define": if(_define. toString().indexOf("else if((h in j)) (") != -1) ( /*do nothing*/ ) else ( eval("_define = "+_define_func_string); if(doError === true) ( ​​throw new Error(errMsg); ) ) break; case "_access": if(_access.toString().indexOf("else ( if(!f) ( f = g; )") != -1) ( /*do nothing*/ ) else ( eval("_access = "+_access_func_string); if(doError === true) ( ​​throw new Error(errMsg); ) ) break; default: if(doError === true) ( throw new Error("I don\"t know what to do."); ) ) ); /*Global function _doCodeCheck(String v). I named it doCodeCheck because we"re "doing a code check". The argument "v" is the name of one of the first four functions in this script that you want to check. I make a different variable to make it harder for a user to figure out whats going on. You call this function in your code to check if any of the functions has been changed by the user. */ self._doCodeCheck = function(v) ( l = v; _doFunctionCheck(l); ) ; )())

It also seems that security is really a problem and there is not way to "hide" you programming from the client side. A good idea for me is to compress your code so that it is really hard for anyone, including you, the programmer, to read and understand it. There is a site you can go to: http://javascriptcompressor.com/. (This is not my site, don"t worry I"m not advertising.) This is a site that will let you compress and obfuscate Javascript code for free.

  1. Copy all the code in the above script and paste it into the top textarea on the javascriptcompressor.com page.
  2. Check the Base62 encode checkbox, check the Shrink Variables checkbox.
  3. Press the Compress button.
  4. Paste and save it all in a .js file and add it to your page in the head of your page.

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 for statements or if.

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. An argument is the actual value that is passed to the function (in in this case this is 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, but 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:

Variables and constants in JavaScript. Declaring variables and assigning values ​​to them. Global and local variables. 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 begin with a number. Keep in mind that JavaScript is case sensitive and the variables a1 and A1 are different variables. It is not recommended to use Cyrillic, although it is possible.
Variables in JavaScript are declared with the var keyword:

Var Peremennaya_1 var Peremennaya_2

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

Assigning Values ​​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 = "The assigned text is enclosed 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.

Local and global variables

If a variable is declared inside a function, then it is local and will be available (visible) only within this 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 (visible) 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 your code easier to work with when you have to use duplicate values ​​or expressions. It is enough to set the value of the constant once and you can use it as much as you like by inserting it into the code of your programs. JavaScript does not have a keyword to declare constants; regular variables are used instead of constants. To distinguish constants from variables, they are usually denoted in capital letters, using an underscore if necessary:

Var DRUG_CHELOVEKA = "Dog"

The given example of a constant is not entirely complete, since the word “Dog” is already easy to remember and insert where needed. You can use constants in JavaScript to record and insert more complex values, for example, difficult-to-remember codes, character sets, long text, web addresses, addresses Email, telephone numbers, various coefficients.

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

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, the latest version of ECMAScript (a specification that is a standard) introduced a real constant:

JavaScript. Fast 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 rules), 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 above, 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. Fast 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