JavaScript is a high-level, interpreted programming language primarily used for creating interactive and dynamic content on webpages. It was initially developed by Netscape Communications Corporation in collaboration with Sun Microsystems in 1995. JavaScript is now one of the core technologies of web development along with HTML and CSS.
JavaScript variables play a fundamental role in storing and manipulating data within JavaScript programs, and understanding how to declare and use variables is essential for writing effective JavaScript code.
In JavaScript, variables are used to store and manipulate data. Here's an overview of JavaScript variables:
1. Declaring Variables: In JavaScript, we can declare variables using the `var`, `let`, or `const` keywords.
var x; // Declaring a variable named x using var
let y; // Declaring a variable named y using let
const z = 10; // Declaring a constant variable named z using const (value cannot be changed)
2. Assigning Values: We can assign values to variables using the assignment operator (`=`).
x = 5; // Assigning the value 5 to the variable x
y = "Hello"; // Assigning the string "Hello" to the variable y
3. Variable Types: JavaScript variables can hold various types of data, including numbers, strings, booleans, objects, arrays, and functions.
var num = 10; // Number
var str = "JavaScript"; // String
var bool = true; // Boolean
var obj = { key: "value" }; // Object
var arr = [1, 2, 3]; // Array
var func = function() { /* Function definition */ }; // Function
4. Scope: Variables in JavaScript have function-level scope with `var` and block-level scope with `let` and `const`. This means that variables declared with `var` are function-scoped, while variables declared with `let` and `const` are block-scoped.
function scopeExample() {
if (true) {
var localVar = "Local"; // var is function-scoped
let blockVar = "Block"; // let is block-scoped
}
console.log(localVar); // Can access localVar outside the block
console.log(blockVar); // Error: blockVar is not defined
}
5. Hoisting: Variable declarations are hoisted to the top of their scope in JavaScript, meaning we can access a variable before it's declared. However, only the declaration is hoisted, not the initialization.
console.log(x); // undefined (variable is declared but not initialized)
var x = 5; // Variable declaration and initialization
6. Constants: Constants declared with `const` cannot be reassigned, but their properties can be modified if they are objects or arrays.
const PI = 3.14;
PI = 3.14159; // Error: Assignment to constant variable
Code Compiler Link: https://app.singhteekam.in/codecompiler/