JavaScript Variables
###1: Create a Variable using var Keyword and log it to the console
Code:
var num = 10;
console.log(num); // 10
Outcome:
- The console will display
10
. - The variable
num
is declared usingvar
and assigned the value10
.
###2: Create a Variable using let Keyword and log it to the console
Code:
let Str = "Hello Chai";
console.log(Str); // "Hello Chai"
Outcome:
- The console will display
Hello Chai
. - The variable
Str
is declared usinglet
and assigned the value"Hello Chai"
.
3: Create a constant using const Keyword and log it to the console
Code:
const bool = true;
console.log(bool); // True
Outcome:
- The console will display
true
. - The constant
bool
is declared usingconst
and assigned the valuetrue
.
###4: Make variables with different data types and print their type to the console
Code:
let number = 10;
let string = "hello World";
let boolean = true;
let object = {
name: "Chai",
key: "code"
};
let array = ['Fruits', 'Chai', 'Vegetable'];
console.log(typeof number); // number
console.log(typeof string); // string
console.log(typeof boolean); // boolean
console.log(typeof object); // object
console.log(typeof array); // object (arrays are of type object in JavaScript)
Outcome:
- The console will display:
number string boolean object object
- The types of the variables are printed using the
typeof
operator.
5: Declare a variable using let Keyword and assign it a value and reassign its value
Code:
let chai = "code";
console.log(chai); // "code"
chai = "Hitesh Sir";
console.log(chai); // "Hitesh Sir"
Outcome:
- The console will display:
code Hitesh Sir
- The variable
chai
is declared usinglet
, initially assigned the value"code"
, and then reassigned the value"Hitesh Sir"
.
6: Make a constant using const Keyword and try to reassign the value and Identify the error
Code:
const chaiCode = "ChaiCode.com";
console.log(chaiCode); // "ChaiCode.com"
chaiCode = "www.chaicode.com"; // This line will cause an error
Outcome:
-
The console will display:
ChaiCode.com
-
Then, it will throw an error:
TypeError: Assignment to constant variable
. -
The constant
chaiCode
is declared usingconst
and assigned the value"ChaiCode.com"
. Attempting to reassign it results in an error since constants cannot be reassigned.
This CHallenge provides a comprehensive overview of JavaScript variables, covering variable declarations (var
, let
, const
), type checking, reassignment rules, and usage examples. Each section includes code snippets, expected outcomes, and summaries of key learnings.