• JavaScript language code conventions. JavaScript Basics

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

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

    Constants

    A constant is simply a symbolic name for a value. A constant allows you to refer to a value by name, which means that when a program specifies the name of a constant, the value is substituted instead. Constants are used to store data that should not change during program execution.

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

    Const MAX = 10;

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

    Why are variables and constants needed?

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

    TotalPrice = 2.42 + 4.33; // Total price

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

    TotalPrice = candyPrice + oilPrice;

    Now, instead of remembering what these values ​​mean, you can see that the script adds up the price of candy to the price of butter.

    Also, variables and constants help save time when debugging a script. Instead of using the same literal everywhere, you can assign it to a variable (or constant) at the beginning of the script, and then use the variable (or constant) instead of the literal throughout the rest of the script code. If a decision is later 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 value was assigned to the variable (or constant).

    Scope of constants

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

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

    Constants and reference types

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

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

    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. Quick start

    const DAYSINWEEK = 7;

    const DAYSINWEEK = 7 ;

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

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

    console. log(DAYSINWEEK);

    DAYSINWEEK = 8 ;

    > error

    Once a constant has been declared (constants must be initialized with the const keyword, followed by a constant name that follows variable naming 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 higher, along with Chrome 36+. However, there are a few important caveats:

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

    JavaScript. Quick start

    Learn the basics of JavaScript with a hands-on example 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 has been fixed in Firefox 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 a newer version of the language, but the actual project will use a version that is compatible with a wider range of browsers. Eddie Osmani composed

    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 a keyword const. Keyword const creates a reference to a read-only value.

    Const VARIABLE_NAME = value;

    By agreement, JavaScript constant identifiers are uppercase.

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

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

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

    However, variables created with the keyword const, are unchangeable. In other words, you can't reassign them to different values. Trying to reassign a constant variable will result in a type error TypeError .

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

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

    Const RED; // SyntaxError

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

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

    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 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 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 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.