Declarating variable javascript
Programs need to store data, to store data variables are declared and values are assigned
In javascript there are five keywords for declaring variables:
Programs need to store data, to store data variables are declared and values are assigned
In javascript there are five keywords for declaring variables:
- var
- let
- const
- function
- class
- The Keywords var, let, const declare newly named variables
- when declared in the global 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 it 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
- the variable can hold primitive data 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
- 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 that has never been rewritten to upgrade to the latest javascript 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#.
- variables declared with var are declared within the global scope or the scope of a function,not a block scope
- additionallly 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
- because of this confusion and other reason two new keywords for declaring variables were added in ES 2015: 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