top of page
Writer's picturecompnomics

Introducing Variables in JavaScript


Here's a JavaScript program showcasing different ways to declare and use variables. You can include this code in the <head></head> tab of your HTML page.








// Declaring a variable named `name` with string value
let name = "Alice";

// Declaring a variable named `age` with numeric value
const age = 30;

// Declaring a variable named `isStudent` with boolean value
var isStudent = true;

// Printing the variables to the console
console.log("Name:", name);
console.log("Age:", age);
console.log("Is Student:", isStudent);

// Modifying the `name` variable
name = "Bob";
console.log("Name after change:", name);

// Re-declaring `isStudent` with `let` keyword (allowed)
let isStudent = false;
console.log("Is Student after change:", isStudent);

// Attempting to re-declare `age` with `let` keyword (not allowed)
// let age = 35; // This will result in an error

// Trying to modify a `const` variable (not allowed)
// age = 40; // This will also result in an error

// Using different data types
let price = 10.50; // Number
let message = "Hello!"; // String
let isActive = null; // Null
let undefinedValue; // Undefined

console.log("Price:", price);
console.log("Message:", message);
console.log("isActive:", isActive);
console.log("undefinedValue:", undefinedValue);

This program demonstrates:

  • Declaring variables:

  • let: Used for variables that can be reassigned later.

  • const: Used for variables whose value should remain constant.

  • var: (Legacy use, avoid in modern JavaScript) Used for variables that can be reassigned, but has scoping issues.

  • Assigning values: Different data types (string, number, boolean, null, undefined) can be assigned.

  • Accessing and modifying variables: You can use the variable name to access and modify its value.

  • Scope: let and const have block-level scope, while var has wider scope (avoid using var).

Remember, understanding variables is crucial for writing any JavaScript program. Choose the appropriate keyword based on whether the value needs to be constant or reassigned.

20 views0 comments

Recent Posts

See All

コメント

5つ星のうち0と評価されています。
まだ評価がありません

評価を追加
bottom of page