JS variable, scope, Memory (including pre-analytic interview Questions)

Source: Internet
Author: User
Tags variable scope

one, Variable 1. Variable name:
    • Variable name starts with $, letter, underscore
    • Hump Naming method
    • Variable names make sense
2. Variable declaration
    • Declaring multiple Variables:var message, name, age;

    • Duplicate declarations are not valid, just look at the first declaration of "special: function names within the functions of the inner participation function (functions created by function Declaration) have the same name, with the function name declaration as the"

<  Script    >  console . log  (typeof  a)     function  a  () {}  var  a =  10  Span class= "op";  <  /script>  //output: function   
<  Script    >         var  a =  10   function  a  () {}  console . log  (typeof  a)  <  /script>  //output: number   
<  Script    >  (function  (a) { console .  (a)  var  a =  function  () {}  console . log  (a)      ) (100 )  <  /script>  //output: 100 function body   
// 特殊情况<script>    (function{        console.log(a);        functiona{}        console.log(a);    })(100);</script>// 输出: 函数体  函数体
3. Variable assignment (initialize) delay scope chain look for variable, then assign value
    • Multiple assignments are valid, only the last assignment is evaluated

    • When assigning a value, the variable is found, along the scope chain, and the global variable is not created Globally.

    • therefore, var A variable that is not declared is a global variable

4. by Scope: local variables: with varStatement Note distinction: declaration, initialization (assignment)Global Variables: No varStatement. Not recommendedIi. data types of variables: simple data types, complex data types
    • JS has 6 types of Data: 5 simple data types, 1 complex data types
    • At first glance, 6 data types are not enough to represent all of the data, but because the ECMAScript data is dynamic, there is no need to define additional data types.
1. Data type of the detection variable---typeof () typeof is an operator, not a function
    • Usage:
      • typeof(变量)
      • typeof 变量
    • Return:
      • typeof(变量) = undefined: Declares a variable, but not initialized (assigned value), or an error if the variable is not declared
      • typeof(变量) = boolean: The variable is a Boolean
      • typeof(变量) = string: variable is a string
      • typeof(变量) = number: variable is numeric
      • typeof(变量) = object: variable is an object or null
      • typeof(变量) = function: Variables are functions
2. Undefined type
    • The data type has only one value, and the value is itselfundefined
    • variable is undefined type: variable declared (var), but uninitialized/assigned
3. NULL type
    • The data type has only one value, and the value is itselfnull
    • Null represents an empty object pointer, which can be saved with this variable as long as the variable you want to save has not actually saved the Object.
    • nullAnd undefined is a completely different two values but null == undefined returnstrue
4. Boolean Type
    • all variables can be converted to Boolean , with only two values for the Boolean typetrue 、 false
    • Go boolean function:Boolean()
空字符串、0、NaN、null、undefined 转布尔值为 `false`特殊:空对象 转布尔值 为true
5. Number Type
    • This type is represented using the IEEE745 format: integers , floating-point values
二进制(0、1)八进制(第一位是0,范围0 ~ 7)十进制(0 ~ 9)十六进制(开头是0x,范围0 ~ 9,A ~ F 字母部分大小写)浮点数值:浮点数值中必须有一个小数点,且小数点后最少有一位小数;浮点值计算不准确内存空间:整数值内存空间的两倍 === 浮点数值内存空间;所以 1.0 会被转为整数值 1 再被存储
    • JS Range of values
      • ECMAScript can't save all the values in the WORLD.
      • Determine if the value is in the value range of JSisFinite()
    • NaN: (this is not a numeric value) but it is a special value
      • Nan and any numeric values are not equal, including itself
      • isNaN()Validation is not a numeric value, implicit conversions occur
isNaN(NaN);     // trueisNaN(10);      // falseisNaN("10");    // false (默认转为数值)isNaN(true);    // false (true转为1)isNaN("blue");  // trueisNaN("aa11");  // true
    • Numeric conversions (null will be converted to values, undefined will be converted to Nan)
      • Number()Available with any data type; special cases (convert strings, objects, undefined values of non-pure values to nan; convert boolean, null, Pure numeric string, to Numeric)
      • down integer conversion : parseInt(string / number, radix) (the second argument turns into a binary): the string starts with a number, if it is not a digit, and the string starts with a number, resolves to a stop without a number, and does not retain the decimal
      • Floating-point conversions : The parseFloat(string / number) string starts with a number that is not a digit, and a Nan is returned, and the string starts with a lion, parsing until the number stops and the decimal is preserved .
      • The parameters of parseint ()/parsefloat () can also be numeric, but generally not used
      • toFixed(几位小数)Keep several decimals;---> return string
parseInt(‘112ac.44‘);       // 112parseInt(‘ac112.44‘);       // NaNparseFloat("34 45 66");     // 34parseFloat(‘22.34a5‘);      // 22.34
6. String Type
    • String characteristics: immutable; array variable
    • String(变量)any type of data can be converted to a string
    • 变量.toString()Cannot convert null and undefined, will error
7. Type of Object
    • Complex Data types: is a collection of data and functions
Iii. Type value base value type of variable
    • Simple data types are primitive type values: null, undefined, boolean, number, string

    • deep copy (stored in stack Memory): equivalent to recreate a variable, two values do not affect each other

Reference type value
    • Complex data types belong to reference type Values: object

    • To add attributes, methods, and properties to a reference type worthwhile variable by means of The. ---> This concludes that JS is a dynamic language, data is loosely typed.

    • shallow copy (stored in heap Memory): A variable of a reference type actually contains not the object itself, but a pointer to that object, a value that copies a reference type from one variable to another, and actually copies a pointer, and two variables eventually point to the same object

    • delete 对象.方法 / 属性Delete a reference Type's properties, methods

Determining the type value of a variable
    • Determine what the base type of a value is in:typeof

    • To determine which reference type a value is In: 对象 instanceof 引用类型的构造函数 , returns a Boolean value

four, the scope of the variable 1. Global Scope/global variables
    • The global execution environment is considered an window object, and all global variables are window properties and methods

    • Global variables: <script> </script> variables defined directly in

2. Local scope/local variable---> for functions only, also known as Lexical scopes
    • Local variables: variables that are redefined in local scope, outside the local scope are inaccessible

    • Local scope: var variables that are not declared are automatically added to the Global environment

    • The local environment of a function has access not only to the scope of the current level, but also to the parent scope, the parent scope cannot access the child scope "access variables across scopes, access only the outer scope, cannot access the inner scope"

3. ES5: variable does not have block-level scope, local scope (lexical Action) only for function
    • therefore, { } It is not a block-level scope; local scopes are only for functions, not for if and for statements

    • ES6 improvements to Block-level scopes

4. Variable Scope chain
    • concept: Take the function as an example, each function has a scope, if wrapped in other functions, wrap his function also has scope, so until the global scope, formed a scope chain structure, the chain structure is called the scope chain.

    • Each time you enter a new execution environment, you create a scope chain that is used to search for variables and functions.

5. Variable Search Principles
    • just look for the declaration, first in the current scope to find, no words to go to the outer scope of the search; know to find window global scope
V. Pre-parsing of Variables 1. Pre-analytic concepts: Lifting variable declarations to the top of the current scope
    • The declaration of a variable (a primitive type value Variable/complex Type value Variable) is advanced to the topmost level of the current scope, but the initialization (assignment) is not advanced
2. Basic type variable pre-parse/function pre-parse
    • Declaration elevation of a variable

      • var aaa; ascension, assignment does not increase

      • Outputs a variable that is not assigned a value, as a resultundefined

    • The declaration of a function promotes "important"

      • Call a function that is not assigned a value, error
function  fn ()  {}    整体提升函数体var  =function{}   只提升var  ;
3. Analysis of pre-analytic topics
    • In the current scope, the name of the variable/lifted function is lifted first; the code is executed from top to bottom, from left to Right.

    • Function call is found, return to function creation Area execution function

    • Duplicate declarations are not valid, just look at the first declaration of "special: function names within the functions of the inner participation function (functions created by function Declaration) have the same name, with the function name declaration as the"

      • function declaration mode creation: function fn() { } pre-parsing is: The whole function of the body in advance

      • function Expression creation: var fn = function() { } pre-parse is put: var fn; advance

Pre-analytic Surface Questions
    • Question 1th: what to output
<script>    console.log(typeof a);    functiona{}    var=10;</script>
    • Question 2nd: what to output
<script>    var=10;        functiona{}        console.log(typeof a);</script>
    • Question 3rd: what to output
<script>    (function{        console.log(num);        =123;        console.log(num);    })(100);</script>
    • Question 4th: what to output
<script>    (function{        console.log(a);        var=function{}        console.log(a);    })(100);</script>
    • Question 5th: what to output
<script>    (function{        console.log(a);        functiona{}        console.log(a);    })(100);</script>
    • Question 6th: What is the "important" output?
<script>    var=1;    functiona{        =2;        return x;    }    a(x);    console.log(x);</script>
    • Question 7th: What is the "important" output?
<  Script    >     var  num =  123   function  f1  () { console . log  (num)        }  f2  ()  function  f2         () { num =  456   f1     ()  }  console . log  (num)  <  /script>   
    • Question 8th: What is the "important" output?
<script>    if (‘a‘in{        var=10;        console.log(‘进入‘);    }    console.log(a);</script>
Answers to pre-analytic surface questions
    • Question 1th: function
    • Question 2nd: number
    • 3rd question: 100 123
    • 4th question: 100 Function Body
    • Question 5th: function Body function body
    • 6th question: 1 Because the function x is a function parameter, it can be understood as a local variable inside the function, outside the function can not access the
    • 7th Question: 456 456
    • 8th question: 10 Any undeclared attribute is on the prototype chain of window
Vi. life-cycle local scope of variables
    • After the code executes, the local execution environment is destroyed; all variables and functions are destroyed immediately.
Global scope (window)
    • The global execution environment will not be destroyed until the application exits (close the browser, etc.)
Seven Memory Leaks1. Memory leak concept
    • Memory Leak: refers to the program in the middle of the dynamic allocation of memory, but at the end of the program did not release this part of memory;

    • Restart the computer, or close the program to resolve a memory leak

    • Memory leaks, and computer hardware does not matter, and software code writing about

2. Problem 3 caused by memory Leak. JS in Solution: JS Garbage automatic recovery mechanism
    • JS garbage Automatic recovery mechanism principle : Garbage collector, a period of time, will no longer use the local variables destroyed, freed its occupied memory

    • however, c, C # and other languages, need to manually track the use of memory

4. JS in the Solution: JS global variable/reference type variableNeed to manually free up memory
    • The variable is not referenced, which frees up memory

    • variable = null;

Eight Memory Overflow---> solutions: Data Cache 1. Memory Overflow Concept
    • A memory overflow is when a user exceeds the bounds of its buffer when it operates on its data buffer
2. Memory overflow causes issue 3. JS in solution: object/array simulation cache data
    • Store the data that needs to be cached in an Object/array
Caching action
    • Staging data to avoid repetitive calculations/requests, and improve program performance
Cache usage Steps
    • (1) Use the data, first to the cache to view, and then remove the use
    • (2) no data in the cache, calculate/request, and then cache the Data.
Cache application: Fibonacci Recursive functions
    • Fibonacci-cut Sequence Optimization "cache"
<Script>    varCache= {};    function Fn4(m){        if(cache[m]){            returncache[m];        }        if(m=== 1 ||M=== 2){cache[m]= 1;            return 1;        } Else {            returncache[m]= Fn4(m-1)+ Fn4(m-2);        }    }    Console.Log(Fn4( $));</script>
nine, memory leaks and memory overflow relationship
    • Memory leaks are one of the causes of memory overflow, and memory leaks accumulate to cause memory overflow

    • Memory leaks can be done by perfecting the code to avoid

    • Memory overflow can be adjusted to reduce the frequency of occurrence, but not completely avoid

JS variable, scope, Memory (including pre-analytic interview Questions)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.