JavaScript Variables - Exercise 1
Question 1: What is a variable in JavaScript?
A variable in JavaScript is a symbolic name for a value. Variables are containers for storing data values.
var x = 5;
Question 2: What are the rules for naming variables in JavaScript?
In JavaScript, variable names:
- Must begin with a letter (a-z, A-Z), underscore (_), or dollar sign ($).
- Can contain letters, digits, underscores, and dollar signs.
- Are case-sensitive.
- Cannot be a reserved keyword.
In JavaScript:
- var: Declares a variable globally, or locally to an entire function regardless of block scope.
- 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, but its value cannot be reassigned. It must be initialized during declaration.
In JavaScript, an identifier is a name given to variables, functions, labels, and objects. Identifiers are used to identify and refer to these entities in the code.
var myVariable = 10;
In JavaScript, camelCase is a naming convention where the first letter of each word in a variable name is lowercase, except for the first word which is lowercase.
var myVariableName = "Hello World";
In JavaScript, you can declare a constant using the const keyword. Constants must be initialized with a value and cannot be reassigned a new value.
const PI = 3.14;
In JavaScript, variable hoisting is a behavior where variable declarations are moved to the top of their scope during the compilation phase, while the variable assignments remain in place.
console.log(x); // Output: undefined var x = 5;
In JavaScript, the scope of a variable determines where the variable is accessible within the code. There are two types of scope:
- Global scope: Variables declared outside of any function have global scope and can be accessed from anywhere in the code.
- Local scope: Variables declared within a function have local scope and can only be accessed within that function.
In JavaScript, you can check the type of a variable using the typeof operator.
console.log(typeof 42); // Output: "number"
In JavaScript, the == operator checks for equality after performing type conversion, while the === operator checks for strict equality without type conversion.
console.log(1 == "1"); // Output: true
console.log(1 === "1"); // Output: false