Variables in JavaScript
Our first program will demonstrate how to declare and use variables in JavaScript. Here’s the full source code:
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:
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.