revision:
All JavaScript variables must be identified with unique names, which are called identifiers.
The general rules for constructing names for variables/unique identifiers are:
1/ names can contain letters, digits, underscores, and dollar signs;
2/ names must begin with a letter;
3/ names can also begin with $ and _ (i.e. underscore);
4/ names are case sensitive (y and Y are different variables);
5/ reserved words (like JavaScript keywords) cannot be used as names.
In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.
Many variables can be declared in one statement: start the statement with "var" and separate the variables by comma(s).
If you re-declare a JavaScript variable, it will not lose its value.
The scope is global when a "var" variable is declared outside a function: any variable that is declared with "var" outside a function block is available for use in the whole window.
"var" is function scoped when it is declared within a function: it is available and can be accessed only within that function.
Variables defined with "var" move to the top when code is executed (i.e. hoisted).
"const" has to be initialised and once it has been assigned, it cannot be reinitialised. "const" can be scoped into blocks, but you cannot do loops with "const".
Example code: convert Fahrenheit / Celsius: two functions can help to convert Fahrenheit to Celsius and the other way around.
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32; // Examples celsiusToFahrenheit(15); // 59 celsiusToFahrenheit(0); // 32 celsiusToFahrenheit(-20); // -4
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9; // Examples fahrenheitToCelsius(59); // 15 fahrenheitToCelsius(32); // 0
const celsiusToFahrenheit = (celsius) => 1.8 * celsius + 32; // Examples celsiusToFahrenheit(15); // 59 celsiusToFahrenheit(0); // 32
"let" is block scoped. A block is a chunk of code bounded by {} : a block lives in curly braces and anything within curly braces is a block. A variable declared in a block with "let" is only available for use within that block.
"let" can be updated but not re-declared : a variable declared with "let" can be updated within its scope, but cannot be re-declared within its scope.
When using "let", you don't have to bother if you have used a name for a variable before as a variable exists only within its scope.
<div> <a class="spec" id="id3"></a></br> </div> <script> let user='John'; let age = 25; let message = 'Hello'; let result2 = user + " , " + age + " , " + message; document.getElementById('id3').innerHTML = result2; </script>
<div> <a class="spec" id="id4"></a><br> <a class="spec" id="id5"></a><br> </div> <script> let admin, name; name = 'John'; admin = name; document.getElementById('id4').innerHTML = name; document.getElementById('id5').innerHTML = admin; </script>
Local JavaScript variables: variables declared within a JavaScript function, become "LOCAL" to the function. Local variables have function scope: they can only be accessed from within the function. Since local variables are only recognized inside their functions, variables with the same name can be used in different functions. Local variables are created when a function starts, and deleted when the function is completed.
outside myFunction() carName is undefined.
Global JavaScript variables: a variable declared outside a function, becomes "GLOBAL". A global variable has global scope: all scripts and functions on a web page can access it.
P.S. automatically Global: if you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
example
a GLOBAL variable can be accessed from any script or function.
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable
In JavaScript, objects and functions are also variables. Their scope determines the accessibility of variables, objects, and functions from different parts of the code.
The lifetime of a JavaScript variable starts when it is declared. Local variables are deleted when the function is completed. In a web browser, global variables are deleted when you close the browser window (or tab).
ES6 introduced two important new JavaScript keywords (let and const), which provide block scope in JavaScript. Variables declared inside a { } block cannot be accessed from outside the block. Variables declared with the var keyword can NOT have block scope, and variables declared inside a { } block can be accessed from outside the block.
Variables declared within a JavaScript function become LOCAL to the function. Since local variables are only recognized inside their functions, variables with the same name can be used in different functions. Local variables are created when a function starts, and deleted when the function is completed.
JavaScript has function scope: each function creates a new scope. Variables defined inside a function are not accessible (visible) from outside the function. Variables declared with "var", "let" and "const" are quite similar when declared inside a function. They all have function scope.
A variable declared outside a function becomes GLOBAL. Variables declared Globally (outside any function) have global scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared with "var", "let" and "const" are quite similar when declared outside a block. They all have global scope.
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
With JavaScript, the global scope is the JavaScript environment. In HTML, the global scope is the window object. Global variables defined with the "var" keyword belong to the window object. Global variables defined with the "let" keyword do not belong to the window object.
The lifetime of a JavaScript variable starts when it is declared. Function (local) variables are deleted when the function is completed. In a web browser, global variables are deleted when you close the browser window (or tab).
P.S. Function arguments (parameters) work as local variables inside functions.
You can assign values to multiple variables with array destructuring.
longhand
x = 1; y = 2; z = 3;
shorthand
let [x, y, z] = [1, 2, 3];
It's good practice to declare variable assignments at the beginning of functions. Shorthand methods can save lots of time and space when declaring multiple variables at the same time.
longhand
let x; let y; let z = 3; let name; let age; let favoriteFood = "Pizza"; let i = 0; let j = 0; let counter = 0; let message = 'Hello there'; let isFound = false; let isOpen = true; let text;
shorthand
let x, y, z=3; let name, age, favoriteFood = "Pizza"; let i = 0, j = 0, counter = 0; // counters let message = 'Hello there', text; // strings let isFound = false, isOpen = true; // booleans
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
longhand
const observable = require('mobx/observable'); const action = require('mobx/action'); const runInAction = require('mobx/runInAction'); const store = this.props.store; const form = this.props.form; const loading = this.props.loading; const errors = this.props.errors; const entity = this.props.entity;
shorthand
import { observable, action, runInAction } from 'mobx'; const { store, form, loading, errors, entity } = this.props;
You can use destructuring to assign multiple values in one line of code.
base
let num1, num2;
longhand
num1 = 10; num2 = 100;
shorthand
[num1, num2] = [10, 100];
This applies to objects too.
base
student = { name: "Matt", age: 29, };
longhand
let name = student.name; let age = student.age;
shorthand
let { name, age } = student;
You can use the spread operator (...) to destructure leftover values of an object. The spread operator (…) allows us to expand an iterable like array into its individual elements. Syntax of spread operator is a set of three dots followed by name of the iterable object.
base
const student = { name: "Matt", age: 23, city: "Helsinki", state: "Finland",}; const string = "Test" ;
longhand
const name = student.name; const age = student.age; const address = { city: student.city, state: student.state };
shorthand
const { name, age, ...address } = student; const array = [...string]; // array = ['T', 'e', 's', 't'];
Variables and block scope
<div> <p id="id11" style="padding-left: 2vw;font-style: italic;color:red" ></p> <p id="id12" style="padding-left: 2vw;font-style: italic;color:red" ></p> <p id="id13" style="padding-left: 2vw;font-style: italic;color:red" ></p> </div> <script> let age1 = 30; if(true){ let age1 = 40; let name = 'shaun'; let result2 = 'inside first code block: ' + age1 +" , " + name; document.getElementById('id11').innerHTML = result2; if(true){ let age = 50; let result3 = 'inside second code block: ' + age1; document.getElementById('id12').innerHTML = result3; } } let result4 = 'outside code block: ' + age1 + ' , ' + name; document.getElementById('id13').innerHTML = result4; </script>
let message; let message; message = 'Hello'; // store the string 'Hello' in the variable named message let message; message = 'Hello!'; alert(message); // shows the variable content let message = 'Hello!'; // define the variable and assign the value alert(message); // Hello!
let user = 'John', age = 25, message = 'Hello'; let user = 'John'; let age = 25; let message = 'Hello'; let user = 'John', age = 25, message = 'Hello'; let user = 'John' , age = 25 , message = 'Hello';
let userName; let test123; let $ = 1; // declared a variable with the name "$" let _ = 2; // and now a variable with the name "_" alert($ + _); // 3 let 1a; // cannot start with a digit let my-name; // hyphens '-' aren't allowed in the name
let let = 5; // can't name a variable "let", error! let return = 5; // also can't name it "return", error!
const myBirthday = '18.04.1982'; const myBirthday = '18.04.1982'; myBirthday = '01.01.2001'; // error, can't reassign the constant!
const COLOR_RED = "#F00"; const COLOR_GREEN = "#0F0"; const COLOR_BLUE = "#00F"; const COLOR_ORANGE = "#FF7F00"; // ...when we need to pick a color let color = COLOR_ORANGE; alert(color); // #FF7F00