Assembly in Progress...

Variables in JavaScript

Variables in JavaScript are basically names or references to storage locations in memory. A variable name needs to start with a letter (lowercase is most common, though uppercase can be used), an underscore( _ ) or dollar sign( $ ). Variables will be either local, which means they are only accessible within a function or brackets, or global, which means they are accessible anywhere. Variable Declarations
  • var - function scoped.
  • const - block scoped by curly brackets {} and unchangeable.
  • let - block scoped and changeable.
  • The last option is to declare directly, which will make it part of the global scope and, generally, not a good idea.

Note: A variable name that starts with an underscore means nothing specific in JavaScript, but, in other languages it can indicate a private variable. Private variables should not be exposed outside of where they are created and often hold sensitive information like account numbers or similar data. With this, many JavaScript developers have an unofficial use of the underscore before a variable to imply the variable is meant to be private. Check out this link to an article that explains this all well.

Code examples
var varVariable = "I am a var variable. I stay inside the function where I am called.";

const constVariable = "I am a const variable. I stay inside curly brackets.";

let letVariable = "I am a let variable. I stay inside curly brackets.";

globalVariable = " I am a global variable and available anywhere. Be careful as I can cause problems.";

const _underscoreVariable = "If you see an underscore at the beginning of a variable name, it might mean to treat it as private.";

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

q
↑ Back to Top