Announcement

Collapse
No announcement yet.

Javascript variables

Collapse
X
Collapse
 

  • JavaScript
    started a blog post Javascript variables

    Javascript variables

    Welcome To Javascript Variable:

    In this blog, we will look into
    1. Types in Javascript
    2. Primitives and Objects
    3. Declaring Variables
    4. Stack Frames and Context and the heap
    5. Pass by Reference and value, declaration
    6. Examples
    Types in Javascript:
    • Most programming languages support the concept of types
    • A type is a description of the kind of data a variable is going to hold
    • A variable with a number type can hold a number, while a variable with a string type can hold a sequence of characters, such as a person's first name
    • Many languages require variables to be specifically typed before the program
    • executes, and when executing the variable, types cannot be changed; this is called strong-typing
    • JavaScript supports types, but it is not strongly-typed, it is loosely-typed
    • With JavaScript, the type of a variable is determined when the program
      executes (not before), and the type can change as the program executes
    • JavaScript has types, but because those types can change as the program
      executes, it is loosely-typed
    • JavaScript supports a few primitive types, with everything else being an object
    • Unlike languages such as C++, Java, and C#, all objects are just objects; there
      are not specific types of objects (except for function objects)


    Primitives and Objects

    Types:
    • Application data can either be a primitive type or an object type
    • There are five primitive types:
    • 1.undefined - an uninitialized variable
    • 2. number – all numbers are stored as binary floating-point
    • 3. boolean – true or false
    • 4. string - sequence of characters
    • 5. symbol – unique value used for property keys on objects
    • Everything else is an object, including functions and arrays

    • To determine the type of an object, the typeof operator is used
    • The typeof operator will return the primitive type of a variable; if the variable points to an object, it will return "object"
    • If typeof is used on a variable with a value of null, then it returns "object"
    • If typeof is used on a variable which points to a function object, then "function" is returned
    • Because classes are just an improved syntax for constructor functions, calling typeof on a class returns "function" as well
    Object Instances:
    • While all objects, regardless of how they are created, return back a type of "object", it is possible to determine which class or constructor function created an object
    • JavaScript provides an instanceof operator which can be used to test if an object is an instance created by a class or constructor function
    • The instanceof operator will traverse the prototype chain and return true for any super class or super constructor function
    • The prototype chain can be changed even after an object is created, revealing that instanceof is truly looking at the prototype chain at the moment the instanceof operator is evaluated
    Loose-Typing:
    • Loose-typing applies to variable types, object shapes, and object inheritance chains
    • In other languages, these three things would be fixed at compile-time, and unable to be changed at run-time
    • But JavaScript is not strongly-typed, it's loosely-typed, and this can be both a huge benefit and a huge problem


    Declaring Variables

    Declarations
    • Programs need to store data; to store data variables are declared and values are assigned
    • Think of a variable as a little box which can hold a value for later use
    • In JavaScript there are five keywords for declaring variables:
    • var, let, const — data
    • function, class — code as data
    • The keywords var, let, const declare new named variables
    • When declared in the global scope (not within a block scope or function scope), variables are available throughout the program
    • For global variables declared with var, their names become properties of the global object
    • Generally, declaring variables in the global scope is a bad practice, it can lead to conflicts and confusion in the code
    • When used within a function, they are local variables within the context of the executed function's stack frame
    • A stack frame contains all of the data associated with the invocation of a function, such as context, function name, source code, etc.
    • Variables can hold both primitive data (numbers, booleans, strings, and symbols) and object references
    • For the sake of simplicity, think of primitives vs. objects with respect to variables in the following way:
    • Variables containing primitive values store those values on context of the stack frame (this is not necessarily true within the JavaScript engine, but conceptually is easier to understand)
    • Variables containing objects really only contain a reference to the object, which is stored on the heap
    • So primitive values are stored within the variable itself, and objects are stored by reference within the variable, with the object itself being stored on the heap
    • For modern JavaScript coding, only let and const should be used to declare variables
    • The presence of var in source code indicates legacy code which has never been rewritten to upgrade to the latest JavaScript coding practices
    • The keyword var was the original way to declare variable with the initial release of JavaScript in 1995
    • Variables declared with var are read/write but exhibit some unexpected
    • characteristics, especially for developers coming from C++, Java and C#
    Declarations with 'let' and 'const':
    • Variables declared with var are declared within the global scope or the scope of a function, not block scope
    • Additionally, declarations are hoisted to the top of the global scope or the top of the function scope in which they are declared
    • Many developers are unaware of these qualities, which can lead to confusion and bugs in JavaScript code
    • In languages such as C++, Java, and C#, variables are declared within a block scope and declarations do not hoist
    • Because of this confusion and other reasons, two new keywords for declaring variables were added in ES2015: let and const
    • Declaring variables with let and const behave as most developers expect Variables are defined within a block scope, and there is no hoisting
    • Variables defined with const are immutable, while variables defined with let are mutable
    • When declaring variables, always prefer const to let, unless there is a specific reason for a variable to be mutated


    Stack Frames, Contexts, and the Heap:
    • Many developers get confused by variables, objects, and object properties
    • To understand the role of each kind of structure and its place in the larger memory structure of the running application, a deeper understanding of process and lower-level languages is required
    Click image for larger version  Name:	Screenshot 2021-09-10 at 2.41.52 PM.png Views:	1 Size:	23.3 KB ID:	598
    • A process is an instance of an executing application
    • A process' memory is allocated into sections Within a process' memory, there is a stack and heap
    • The stack is used to store function parameters, return addresses, and local variables
    • The heap is an unstructured, dynamically allocated memory store
    • Applications coded with lower-level languages such as C++ store in-memory data using these process-level memory sections
    • For example, variables are defined on the stack, and data can be stored on the heap using functions like malloc
    • Unlike a C++ program, JavaScript applications run within a JavaScript Engine
    • Typically, JavaScript Engines are implemented in C++
    Javascript Engines:
    • There are many JavaScript Engines, the most popular ones are:
    • * ChakraCore — Microsoft (Edge & Node.js)
    • * V8 — Google (Chrome & Node.js)
    • * SpiderMonkey — Mozilla (Firefox)
    • The engine is a C++ application, which executes JavaScript code within a virtual machine kind of environment
    • The engine runs natively on the device using the normal operating system provided process structures and uses its heap to store all of the JavaScript memory structures
    Javascript App Memory Structure within a Process:
    • Just like lower level languages, JavaScript uses the concept of a stack and heap to organize in- memory application data
    • But, a JavaScript application's stack and heap are nothing more than data structures stored in the process' heap
    • JavaScript uses an enhanced stack to support the use of closures
    • The stack is not a true process stack; in the V8 engine, it’s a C++ vector structure
    Click image for larger version  Name:	Screenshot 2021-09-10 at 2.49.25 PM.png Views:	1 Size:	50.5 KB ID:	599




    Stack Frame Definition:
    • JavaScript's stack is organized as stack frames; a new frame is created when a JavaScript function is invoked
    • A stack frame contains: function name, return address, the context of variables
    • The heap (not shown) contains objects
    • Example: A variable defined in the context of a stack frame points to an object on the heap
    Click image for larger version  Name:	Screenshot 2021-09-10 at 2.50.50 PM.png Views:	1 Size:	75.0 KB ID:	600




    Call Stack:
    • As functions invoke other functions, and those functions invoke more functions, a stack of function calls is created
    • Each line in the call stack is a stack frame
    • Using Chrome's developer tools, it’s possible to restart a stack frame
    • A stack trace can be generated as well
    Click image for larger version  Name:	Screenshot 2021-09-10 at 2.54.46 PM.png Views:	1 Size:	236.3 KB ID:	602





    Variables and Object Properties
    • The similarities/differences between variables and object properties can be confusing to developers
    • Both variables and object properties can be thought of as boxes which hold values
    • Those values can be primitive values or object references
    • Variables are defined on the context of the stack frame, while properties are defined on an object on the heap
    • Object properties are not variables, and vice versa
    Why?
    • Understanding the difference between variables on the stack frame and objects on the heap is essential to understanding how immutability works with respect to variable declarations (const) and object freezing (Object.freeze), and how they are not the same
    • Understanding stack frames and context is important to debugging applications and reading stack traces from errors that are thrown
    • Many problems that new JavaScript developers encounter are the result of not understanding how variables and objects work under the hood
    Attached Files
      You must be logged in to post a comment.

    Related Topics

    Collapse

    Working...
    X