A variable is a literal assigned to an identifier, so you can reference and use it later in the program.
A variable must be declared before you can use it. There are 3 ways to do this, using
const, and those 3 ways differ in how you can interact with the variable later on.
var was the only construct available for defining variables.
var a = 0
If you forget to add
var you will be assigning a value to an undeclared variable, and the results might vary.
In modern environments, with strict mode enabled, you will get an error. In older environments (or with strict mode disabled) this will initialize the variable and assign it to the global object.
If you don’t initialize the variable when you declare it, it will have the
undefined value until you assign a value to it.
var a //typeof a === 'undefined'
You can redeclare the variable many times, overriding it:
var a = 1 var a = 2
You can also declare multiple variables at once in the same statement:
var a = 1, b = 2
The scope is the portion of code where the variable is visible.
A variable initialized with
var outside of any function is assigned to the global object, has a global scope and is visible everywhere.
A variable initialized with
var inside a function is assigned to that function, it’s local and is visible only inside it, just like a function parameter.
Any variable defined in a function with the same name as a global variable takes precedence over the global variable, shadowing it.
It’s important to understand that a block (identified by a pair of curly braces) does not define a new scope. A new scope is only created when a function is created, because
var does not have block scope, but function scope.
let is a new feature introduced in ES2015 and it’s essentially a block scoped version of
var. Its scope is limited to the block, statement or expression where it’s defined, and all the contained inner blocks.
let and completely discard the use of
letseems an obscure term, just read
let color = 'red'as let the color be red and it all makes much more sense
let outside of any function - contrary to
var - does not create a global variable.
var in the top level defines a global variable that’s (in the browser) is added to the
window object. A
const) declaration outside of a block still create a variable that’s available across the app code, but it is not assigned to
Variables declared with
let can be changed later on in the program, and reassigned. Once a
const is initialized, its value can never be changed again, and it can’t be reassigned to a different value.
const a = 'test'
We can’t assign a different literal to the
a const. We can however mutate
a if it’s an object that provides methods that mutate its contents.
const does not provide immutability, just makes sure that the reference can’t be changed.
const has block scope, same as
const for variables that don’t need to be reassigned later in the program.
Why? Because we should always use the simplest construct available to avoid making errors down the road.
More js tutorials:
- The Complete ECMAScript 2015-2019 Guide
- A list of sample Web App Ideas
- Introduction to Unicode and UTF-8
- Introduction to ES Modules
- Introduction to CommonJS
- A Moment.js tutorial
- The ES6 Guide
- The ES2016 Guide
- The ES2017 Guide
- The ES2018 Guide
- How to use Async and Await with Array.prototype.map()
- Async vs sync code
- HTML Canvas API Tutorial
- What is a Single Page Application?
- An introduction to WebAssembly
- Introduction to JSON
- The JSONP Guide
- Should you use or learn jQuery in 2020?
- Introduction to PeerJS, the WebRTC library
- Work with objects and arrays using Rest and Spread
- The TypeScript Guide
- Loosely typed vs strongly typed languages
- The node_modules folder size is not a problem. It's a privilege
- The String replace() method
- The String search() method
- The ES2019 Guide
- The String charAt() method
- The String charCodeAt() method
- The String codePointAt() method
- The String concat() method
- The String endsWith() method
- The String includes() method
- The String indexOf() method
- The String lastIndexOf() method
- The String localeCompare() method
- The String match() method
- The String normalize() method
- The String padEnd() method
- The String padStart() method
- The String repeat() method
- The String slice() method
- The String split() method
- The String startsWith() method
- The String substring() method
- The String toLocaleLowerCase() method
- The String toLocaleUpperCase() method
- The String toLowerCase() method
- The String toString() method
- The String toUpperCase() method
- The String trim() method
- The String trimEnd() method
- The String trimStart() method
- The String valueOf() method
- The Number isInteger() method
- The Number isNaN() method
- The Number isSafeInteger() method
- The Number parseFloat() method
- The Number parseInt() method
- The Number toString() method
- The Number valueOf() method
- The Number toPrecision() method
- The Number toExponential() method
- The Number toLocaleString() method
- The Number toFixed() method
- The Number isFinite() method
- The Object assign() method
- The Object create() method
- The Object defineProperties() method
- The Object defineProperty() method
- The Object entries() method
- The Object freeze() method
- The Object getOwnPropertyDescriptor() method
- The Object getOwnPropertyDescriptors() method
- The Object getOwnPropertyNames() method
- The Object getOwnPropertySymbols() method
- The Object getPrototypeOf() method
- The Object is() method
- The Object isExtensible() method
- The Object isFrozen() method
- The Object isSealed() method
- The Object keys() method
- The Object preventExtensions() method
- The Object seal() method
- The Object setPrototypeOf() method
- The Object values() method
- The Object hasOwnProperty() method
- The Object isPrototypeOf() method
- The Object propertyIsEnumerable() method
- The Object toLocaleString() method
- The Object toString() method
- The Object valueOf() method
- How to rename fields when using object destructuring
- How to send urlencoded data using Axios
- How to upload a file using Fetch
- How to use top-level await in ES Modules
- How to send the authorization header using Axios
- How to remove all the node_modules folders content
- How to get the first n items in an array in JS
- How to divide an array in multiple equal parts in JS
- How to load an image in an HTML canvas
- How to write text into to an HTML canvas
- How to fix the TypeError: Cannot assign to read only property 'exports' of object '#<Object>' error
- How to create an exit intent popup
- How to check if an element is a descendant of another
- How to force credentials to every Axios request
- Gatsby, how to change the favicon
- Loading an external JS file using Gatsby
- Parcel, how to fix the `regeneratorRuntime is not defined` error
- Object destructuring with types in TypeScript
- The Deno Handbook: a concise introduction to Deno 🦕
- Event bubbling and event capturing
- event.stopPropagation vs event.preventDefault() vs. return false in DOM events
- In which ways can we access the value of a property of an object?
- What's the difference between a method and a function?
- The importance of timing when working with the DOM
- Introduction to XState
- How to handle promise rejections
- How I fixed a "cb.apply is not a function" error while using Gitbook
- Gatsby, fix the "cannot find module gatsby-cli/lib/reporter" error