JavaScript Variables - Exercise 1
Question 1: What is a variable in JavaScript?
A variable in JavaScript is a named binding for a value. You use variables to store data so your program can read it later, update it, or pass it into functions.
const age = 5;
Question 2: What are the rules for naming variables in JavaScript?
In JavaScript, variable names:
- Must start with a letter, underscore (_), or dollar sign ($).
- Can include letters, digits, underscores, and dollar signs after the first character.
- Are case-sensitive.
- Cannot contain spaces or hyphens.
- Cannot be a reserved keyword.
In JavaScript:
- var: Function-scoped, hoisted, and mostly kept for older code.
- let: Declares a block-scoped local variable. It can be reassigned but cannot be redeclared in the same scope.
- const: Declares a block-scoped local variable that cannot be reassigned. It must be initialized when declared.
An identifier is the name used for a variable, function, class, parameter, or other named item in your code.
let score = 10;
In JavaScript, camelCase is a naming convention where the first word starts with a lowercase letter, and each additional word starts with an uppercase letter.
const userName = "Hello World";
Use the const keyword to declare a
constant. A const binding must be given a
value immediately and cannot later be reassigned.
const PI = 3.14;
Hoisting means JavaScript processes declarations before
the surrounding code runs. With var, the
name exists at the start of the scope and is initialized
to undefined. With let and
const, the declaration is hoisted too, but
it stays in the temporal dead zone until its actual
declaration line.
console.log(count); // undefined
var count = 5;
The scope of a variable determines where that variable can be accessed. In modern JavaScript, the most common scopes are:
- Global scope: Variables declared outside functions and blocks are available broadly.
- Function scope: Variables declared inside a function are available only inside that function.
-
Block scope: Variables declared with
letorconstinside a block are available only inside that block.
You can check the type of a value with the
typeof operator. It returns a string
such as "number" or "string".
console.log(typeof 42); // Output: "number"
The == operator compares values after
type coercion, while === compares both
value and type without coercion. In most code,
=== is the safer default.
console.log(1 == "1"); // Output: true
console.log(1 === "1"); // Output: false