JavaScript Variables - Exercise 2

In JavaScript, global variables are variables that are declared outside of any function. They have global scope and can be accessed from any part of the code.

javascript

var globalVar = 10;

In JavaScript, the var keyword is used to declare variables. It can be used to declare variables with both global and local scope, depending on where it is declared.

javascript

var x = 5; // Declares a variable x with global scope

In JavaScript, variable shadowing occurs when a variable with local scope shares the same name as a variable in a higher scope. The local variable "shadows" the variable in the higher scope, effectively hiding it within the local scope.

javascript

 var x = 10; // Global variable function myFunction() {
                        var x = 20; // Local variable, shadows the global
                        variable x console.log(x); // Output: 20 }

In JavaScript, the let keyword is used to declare block-scoped variables. Variables declared with let have limited scope within the block, statement, or expression where they are declared.

javascript

 let x = 5; // Declares a variable x with block scope {
                        let x = 10; // Declares a new variable x with block
                        scope, shadows the outer x console.log(x); // Output: 10
                        }

In JavaScript, reserved keywords are predefined words that have special meaning and cannot be used as variable names, function names, or identifiers.

javascript

var let = 5; // SyntaxError: Unexpected token 'let'

In JavaScript:

  • var: Has function scope or global scope. Variables declared with var are hoisted to the top of their function or global scope.
  • let: Has block scope. Variables declared with let are hoisted to the top of their block scope.

In JavaScript, the const keyword is used to declare constants. Constants are block-scoped and cannot be reassigned a new value once initialized.

javascript

const PI = 3.14; // Declares a constant PI with value
3.14 PI = 3; // TypeError: Assignment to constant variable

In JavaScript:

  • let: Allows reassignment of values. Variables declared with let can have their values changed.
  • const: Does not allow reassignment of values. Constants must be initialized with a value and cannot be reassigned a new value.

In JavaScript, strict mode is a mode that enforces stricter parsing and error handling rules. It helps catch common coding errors and avoid unwanted behavior in JavaScript programs.

javascript

 "use strict"; x = 5; // ReferenceError: x is not defined

In JavaScript, you can concatenate strings using the + operator or by using template literals (``).

javascript

var firstName = "John"; var lastName = "Doe"; var
fullName = firstName + " " + lastName; // Using + var
fullName = `${firstName} ${lastName}`; // Using template literals