JavaScript - tutorial - 01 -variables

revision:


Content

JS variables are containers for storing data values. Declaring variables with "var", "const", or "let". The scope of a variable is the region of the program in which it is defined. The scope determines the accessibility (visibility) of variables. Declaring and destructuring variables Variable examples


JS variables are containers for storing data values.

top

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.


Declaring variables with "var", "const", or "let".

top

var : the most common variable; can be reassigned, re-declared and updated.

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).

examples
code:
                    <div>  
                        <a class="spec" id="id1"></a>
                    </div>    
                    <script>
                        var name = "Ayda";
                        const greeting = "Hello ";
                        let result = greeting + ', ' + name;
                        document.getElementById("id1").innerHTML = result;
                    </script>
                

const : can not be reassigned and not accessible before they appear within the code.

"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".

examples
code:
                    <div>
                        <a class="spec" id="id2"></a>    
                    </div>
                    <script>
                        const myBirthday = '01.12.2000';
                        document.getElementById('id2').innerHTML = myBirthday;
                    
                

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 : similar to "const", however, "let" variable can be reassigned but not re-declared.

"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.

examples

code:
                    <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>
                


code:
                    <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>
                

code:
                    <div>
                        <a  class="spec" id="id6"></a><br>       
                    </div>
                    <script>
                        let total = 0, count = 1;
                        while (count <= 10) {
                            total += count;
                            count += 1;
                        }
                        let result3 = total; 
                        document.getElementById('id6').innerHTML = result3;
                    </script>
                

The scope of a variable is the region of the program in which it is defined.

top

JavaScript variables have only two scopes: local scope and global scope.

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.

examples

outside myFunction() carName is undefined.



code:
                    <div class="spec">
                        <a id="id7"></a><br>
                        <a id="id8"></a><br>         
                    </div>
                    <script>
                        myFunction();
                        function myFunction() {
                            var carName = "Volvo";
                            document.getElementById("id7").innerHTML = typeof carName + " : " + carName;
                        }
                        document.getElementById("id8").innerHTML = typeof carName;
                    </script>
                

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.

examples

code:
                <div class="spec">
                    <a id="id9"></a><br>        
                </div>
                <script>
                    var carName = "Volvo";  
                    myFunction1();
                    function myFunction1() {
                    document.getElementById("id9").innerHTML = "I can display " +  carName;
                    }
                </script>
            

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable

examples

code:
                <div class="spec">
                    <a id="id10"></a><br>         
                </div>
                <script>
                    myFunction2();
                    // code here can use carName as a global variable
                    document.getElementById("id10").innerHTML = "I can display " +  carName;
                    function myFunction2() {
                        carName = "Volvo";
                    }
                </script>
            

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).


The scope determines the accessibility (visibility) of variables.

top

JavaScript has 3 types of scope: block scope, function scope, global scope.

block scope

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.

local scope

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.

function scope

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.

global JavaScript variables

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.

automatically global

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

global variables in HTML

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

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.


Declaring and destructuring variables

top

Assign values to multiple variables

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];
            

Declaring variables

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

                

Destructuring assignment

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;
                

Destructuring with the spread operator

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 examples

top

Variables and block scope

code:
                    <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>
                

JavaScript.info - examples

exmaples
a variable:
                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!
            
multiple variables:
                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';    
            
variable naming:
                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
            
reserved names:
                let let = 5; // can't name a variable "let", error!
                let return = 5; // also can't name it "return", error!
                
            
constants:
                const myBirthday = '18.04.1982';
                
                const myBirthday = '18.04.1982';
                myBirthday = '01.01.2001'; // error, can't reassign the constant!
            
uppercase constants:
                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