JavaScript Variables - Exercise 2

Global variables are values defined at the top level so other parts of the program can access them. They should be used carefully because shared global state is easy to overwrite by mistake.

javascript

const appName = "Simply JavaScript";

The var keyword declares a variable with function scope rather than block scope. It is part of older JavaScript and is now used less often than let and const.

javascript

function demo() {
  var count = 5;
  if (true) {
    var count = 10;
  }
  console.log(count); // 10
}

Variable shadowing happens when an inner scope declares a variable with the same name as one in an outer scope. Inside the inner scope, the new declaration hides the outer one.

javascript

const x = 10;

function myFunction() {
  const x = 20;
  console.log(x); // 20
}

The let keyword declares a variable with block scope. That means the variable exists only inside the nearest block, such as an if statement or loop.

javascript

let x = 5;

{
  let x = 10;
  console.log(x); // 10
}

Reserved keywords are words with a special meaning in the language grammar. Because JavaScript already uses them, they cannot be used as identifiers.

javascript

const class = "A"; // SyntaxError

In JavaScript:

  • var: Function-scoped, can be redeclared, and is initialized to undefined when hoisted.
  • let: Block-scoped, cannot be redeclared in the same scope, and cannot be used before its declaration line.

The const keyword declares a block-scoped binding that cannot be reassigned after initialization. It does not make referenced objects immutable: const user = {}; user.name = 'Ada' is valid.

javascript

const PI = 3.14;
// PI = 3; // TypeError

In JavaScript:

  • let: Use it when the variable needs to be reassigned.
  • const: Use it when the binding should stay the same after declaration. For example, const limit = 10 cannot be assigned again.

Strict mode turns on safer language rules. It helps catch mistakes earlier, such as creating accidental globals, and prevents some error-prone legacy behavior.

javascript

"use strict";
undeclaredValue = 5; // ReferenceError

You can concatenate strings with the + operator or by using template literals. Template literals are usually easier to read when values need to be inserted into a string.

javascript

const firstName = "John";
const lastName = "Doe";

const fullName1 = firstName + " " + lastName;
const fullName2 = `${firstName} ${lastName}`;