23.07.2020

JavaScript basics. JavaScript. Variables (global, local, constants)


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

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

Const VARIABLENAME = value;

By agreement constant identifiers in JavaScript are in uppercase.

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

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

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

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

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

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

Const RED; // SyntaxError

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

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

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

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

Constants

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

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

Const MAX = 10;

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

Why variables and constants are needed

Variables and constants help make programming code clearer. Consider 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 (candy price), and 4.33 to the variable (or constant) oilPrice (butter price):

TotalPrice = candyPrice + oilPrice;

Now, instead of remembering what these values ​​mean, you can see that the scenario adds up the price of sweets with the price of butter.

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

Scope of constants

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

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

Constants and Reference Types

When a value of a reference type is assigned to a constant, the reference to the value becomes immutable, while the value itself remains mutable:

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

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 a variable myIncome:

VarmyIncome; // another option let myIncome2;

Each variable has a name. The name is an arbitrary set of alphanumeric characters, an underscore (_), or a dollar sign ($), and names must not begin with numeric characters. That is, we can use letters, numbers, underscores in the name. 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 invalid and may not be used:

222lol @someVariable my%percent

Also, do not give variables names that match the reserved keywords. There are not many keywords in JavaScript, so this rule is not hard 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, two different variables are declared in the following code:

VarmyIncome; var MyIncome;

You can define multiple variables separated by commas:

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

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

Var income = 300; let price = 76;

The process of giving a variable an initial value 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

The const keyword can be used to define a constant, which, like a variable, holds a value, but the 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 can't 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 defining it, we must provide it with an initial value. If we do not 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 everybody, 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 everything inside 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.60m; 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 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 whats 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 */ 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. 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; defa ult: 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 a 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 with the function keyword. The function syntax in JavaScript looks like this:

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

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

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

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

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

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

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

Now you know how you can reuse a function.

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

Returning values

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

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

add(9, 7);

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

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

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

Function expressions

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

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

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

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

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

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

Named function expressions can be used for debugging.

Arrow functions

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

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

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

multiply(30, 4);
120

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

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

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

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

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

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

Conclusion

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

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

Tags:

2022
maccase.ru - Android. Brands. Iron. news