Variables in JavaScript

Our first program will demonstrate how to declare and use variables in JavaScript. Here’s the full source code:

// Variables can be declared using let, const, or var
let a = "initial";
console.log(a);

// You can declare multiple variables at once
let b = 1, c = 2;
console.log(b, c);

// JavaScript will infer the type of initialized variables
const d = true;
console.log(d);

// Variables declared without initialization are undefined
let e;
console.log(e);

// In JavaScript, we don't need to declare variable types
const f = "apple";
console.log(f);

In JavaScript, variables are declared using let, const, or var. The let keyword is used for variables that can be reassigned, while const is used for variables that should remain constant.

You can declare multiple variables at once by separating them with commas.

JavaScript is a dynamically typed language, so it will infer the type of initialized variables. There’s no need to explicitly declare variable types.

Variables declared without initialization are undefined in JavaScript, rather than having a zero value.

To run this JavaScript code, you can save it in a file (e.g., variables.js) and execute it using Node.js:

$ node variables.js
initial
1 2
true
undefined
apple

Alternatively, you can run this code in a browser’s console or use an online JavaScript playground.

JavaScript’s variable declaration and initialization are more flexible compared to statically typed languages. The language handles type inference automatically, making it easier to work with variables of different types.