2.variables in JavaScript
Table of contents
Certainly! In JavaScript, variables are used to store and manage data. Here's a basic overview of how to declare and use variables:
Declaration: You declare a variable using the
var
,let
, orconst
keyword, followed by the variable name.// Using var (old way, not recommended) var myVar; // Using let (block-scoped) let myLet; // Using const (block-scoped, constant value) const myConst;
Initialization: You can also assign a value to a variable at the time of declaration.
let myVar = 10; const myConst = "Hello, World!";
Note:
const
variables must be initialized at the time of declaration, and their value cannot be changed later.Data Types:
JavaScript is a dynamically-typed language, which means you don't explicitly declare the data type of a variable.
Common data types include:
Number
(e.g.,let num = 42;
)String
(e.g.,let greeting = "Hello";
)Boolean
(e.g.,let isTrue = true;
)Array
(e.g.,let myArray = [1, 2, 3];
)Object
(e.g.,let person = { name: "John", age: 25 };
)
Variable Naming Rules:
Variable names can contain letters, digits, underscores, and dollar signs.
They must begin with a letter, underscore, or dollar sign.
JavaScript is case-sensitive, so
myVar
andmyvar
are different variables.
// Example usage:
let firstName = "John";
let age = 25;
let isStudent = true;
console.log(firstName); // John
console.log(age); // 25
console.log(isStudent); // true
Subscribe to my newsletter
Read articles from Shofique Rian directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by